From a4b78b44ce136af6e98af2dd6df2e3a8253c6c96 Mon Sep 17 00:00:00 2001 From: Qstick Date: Fri, 3 Jan 2020 07:49:24 -0500 Subject: [PATCH] StyleCop (#1058) * Stylecop Rules and Fixes --- .editorconfig | 29 + .gitignore | 1 - src/Directory.Build.props | 11 + .../AlbumStudio/AlbumStudioModule.cs | 4 +- src/Lidarr.Api.V1/Albums/AlbumLookupModule.cs | 6 +- src/Lidarr.Api.V1/Albums/AlbumModule.cs | 30 +- .../Albums/AlbumModuleWithSignalR.cs | 13 +- .../Albums/AlbumReleaseResource.cs | 5 +- src/Lidarr.Api.V1/Albums/AlbumResource.cs | 15 +- .../Albums/AlbumStatisticsResource.cs | 13 +- .../Albums/AlbumsMonitoredResource.cs | 1 - .../Artist/ArtistEditorModule.cs | 11 +- .../Artist/ArtistEditorResource.cs | 1 - .../Artist/ArtistImportModule.cs | 7 +- .../Artist/ArtistLookupModule.cs | 5 +- src/Lidarr.Api.V1/Artist/ArtistModule.cs | 39 +- src/Lidarr.Api.V1/Artist/ArtistResource.cs | 24 +- .../Artist/ArtistStatisticsResource.cs | 13 +- .../Blacklist/BlacklistModule.cs | 2 +- .../Blacklist/BlacklistResource.cs | 9 +- .../Calendar/CalendarFeedModule.cs | 11 +- src/Lidarr.Api.V1/Calendar/CalendarModule.cs | 19 +- src/Lidarr.Api.V1/Commands/CommandModule.cs | 8 +- src/Lidarr.Api.V1/Commands/CommandResource.cs | 35 +- .../Config/DownloadClientConfigResource.cs | 4 +- src/Lidarr.Api.V1/Config/HostConfigModule.cs | 3 +- .../Config/HostConfigResource.cs | 3 +- .../Config/IndexerConfigModule.cs | 3 +- .../Config/IndexerConfigResource.cs | 2 +- .../Config/LidarrConfigModule.cs | 9 +- .../Config/MediaManagementConfigModule.cs | 2 +- .../Config/MediaManagementConfigResource.cs | 2 +- .../Config/MetadataProviderConfigModule.cs | 6 +- .../Config/MetadataProviderConfigResource.cs | 2 +- .../Config/NamingConfigModule.cs | 10 +- src/Lidarr.Api.V1/Config/UiConfigModule.cs | 8 +- src/Lidarr.Api.V1/Config/UiConfigResource.cs | 4 +- .../CustomFilters/CustomFilterModule.cs | 2 +- .../CustomFilters/CustomFilterResource.cs | 36 +- .../DiskSpace/DiskSpaceModule.cs | 6 +- .../DiskSpace/DiskSpaceResource.cs | 5 +- .../DownloadClient/DownloadClientModule.cs | 8 +- .../DownloadClient/DownloadClientResource.cs | 12 +- .../FileSystem/FileSystemModule.cs | 14 +- src/Lidarr.Api.V1/Health/HealthModule.cs | 4 +- src/Lidarr.Api.V1/Health/HealthResource.cs | 7 +- src/Lidarr.Api.V1/History/HistoryModule.cs | 20 +- src/Lidarr.Api.V1/History/HistoryResource.cs | 11 +- .../ImportLists/ImportListExclusionModule.cs | 4 +- .../ImportListExclusionResource.cs | 12 +- .../ImportLists/ImportListModule.cs | 4 +- .../ImportLists/ImportListResource.cs | 6 +- src/Lidarr.Api.V1/Indexers/IndexerModule.cs | 8 +- src/Lidarr.Api.V1/Indexers/IndexerResource.cs | 10 +- src/Lidarr.Api.V1/Indexers/ReleaseModule.cs | 3 +- .../Indexers/ReleaseModuleBase.cs | 2 +- .../Indexers/ReleasePushModule.cs | 12 +- src/Lidarr.Api.V1/Indexers/ReleaseResource.cs | 11 +- src/Lidarr.Api.V1/Logs/LogFileModule.cs | 3 +- src/Lidarr.Api.V1/Logs/LogFileModuleBase.cs | 12 +- src/Lidarr.Api.V1/Logs/LogModule.cs | 2 +- src/Lidarr.Api.V1/Logs/LogResource.cs | 7 +- src/Lidarr.Api.V1/Logs/UpdateLogFileModule.cs | 7 +- .../ManualImport/ManualImportModule.cs | 49 +- .../ManualImport/ManualImportResource.cs | 20 +- .../MediaCovers/MediaCoverModule.cs | 13 +- src/Lidarr.Api.V1/Metadata/MetadataModule.cs | 8 +- .../Metadata/MetadataResource.cs | 12 +- .../Notifications/NotificationModule.cs | 6 +- .../Notifications/NotificationResource.cs | 10 +- src/Lidarr.Api.V1/Parse/ParseModule.cs | 3 +- src/Lidarr.Api.V1/Parse/ParseResource.cs | 2 +- .../Profiles/Delay/DelayProfileModule.cs | 10 +- .../Profiles/Delay/DelayProfileResource.cs | 12 +- .../Metadata/MetadataProfileModule.cs | 2 +- .../Metadata/MetadataProfileResource.cs | 31 +- .../Metadata/MetadataProfileSchemaModule.cs | 19 +- .../Profiles/Metadata/MetadataValidator.cs | 1 - .../Quality/QualityCutoffValidator.cs | 1 - .../Profiles/Quality/QualityItemsValidator.cs | 8 - .../Profiles/Quality/QualityProfileModule.cs | 2 +- .../Quality/QualityProfileResource.cs | 22 +- .../Quality/QualityProfileSchemaModule.cs | 3 +- .../Profiles/Release/ReleaseProfileModule.cs | 3 +- .../Release/ReleaseProfileResource.cs | 12 +- src/Lidarr.Api.V1/ProviderModuleBase.cs | 14 +- src/Lidarr.Api.V1/ProviderResource.cs | 10 +- .../Qualities/QualityDefinitionModule.cs | 12 +- .../Qualities/QualityDefinitionResource.cs | 14 +- src/Lidarr.Api.V1/Queue/QueueActionModule.cs | 15 +- src/Lidarr.Api.V1/Queue/QueueDetailsModule.cs | 4 +- src/Lidarr.Api.V1/Queue/QueueModule.cs | 25 +- src/Lidarr.Api.V1/Queue/QueueResource.cs | 11 +- src/Lidarr.Api.V1/Queue/QueueStatusModule.cs | 10 +- .../RemotePathMappingModule.cs | 4 +- .../RemotePathMappingResource.cs | 12 +- .../RootFolders/RootFolderModule.cs | 5 +- .../RootFolders/RootFolderResource.cs | 13 +- src/Lidarr.Api.V1/Search/SearchModule.cs | 14 +- src/Lidarr.Api.V1/Search/SearchResource.cs | 4 +- .../System/Backup/BackupModule.cs | 11 +- .../System/Backup/BackupResource.cs | 2 +- src/Lidarr.Api.V1/System/SystemModule.cs | 10 +- src/Lidarr.Api.V1/System/Tasks/TaskModule.cs | 19 +- src/Lidarr.Api.V1/Tags/TagDetailsModule.cs | 4 +- src/Lidarr.Api.V1/Tags/TagDetailsResource.cs | 7 +- src/Lidarr.Api.V1/Tags/TagModule.cs | 2 +- src/Lidarr.Api.V1/Tags/TagResource.cs | 12 +- .../TrackFiles/MediaInfoResource.cs | 16 +- .../TrackFiles/TrackFileModule.cs | 19 +- .../TrackFiles/TrackFileResource.cs | 18 +- src/Lidarr.Api.V1/Tracks/RenameTrackModule.cs | 3 +- .../Tracks/RenameTrackResource.cs | 5 +- src/Lidarr.Api.V1/Tracks/RetagTrackModule.cs | 1 - .../Tracks/RetagTrackResource.cs | 13 +- src/Lidarr.Api.V1/Tracks/TrackModule.cs | 3 +- .../Tracks/TrackModuleWithSignalR.cs | 13 +- src/Lidarr.Api.V1/Tracks/TrackResource.cs | 17 +- src/Lidarr.Api.V1/Update/UpdateModule.cs | 4 +- src/Lidarr.Api.V1/Update/UpdateResource.cs | 8 +- src/Lidarr.Api.V1/Wanted/CutoffModule.cs | 10 +- src/Lidarr.Api.V1/Wanted/MissingModule.cs | 10 +- .../Authentication/AuthenticationService.cs | 16 +- .../Authentication/EnableAuthInNancy.cs | 25 +- src/Lidarr.Http/ClientSchema/FieldMapping.cs | 3 - src/Lidarr.Http/ClientSchema/SchemaBuilder.cs | 15 +- .../ErrorManagement/ErrorHandler.cs | 4 +- src/Lidarr.Http/ErrorManagement/ErrorModel.cs | 2 +- .../ErrorManagement/LidarrErrorPipeline.cs | 6 +- src/Lidarr.Http/Exceptions/ApiException.cs | 5 +- .../Exceptions/InvalidApiKeyException.cs | 3 +- .../Pipelines/CacheHeaderPipeline.cs | 9 +- .../Extensions/Pipelines/CorsPipeline.cs | 1 - .../Extensions/Pipelines/GZipPipeline.cs | 1 - .../Pipelines/IRegisterNancyPipeline.cs | 2 +- .../Pipelines/IfModifiedPipeline.cs | 6 +- .../Pipelines/LidarrVersionPipeline.cs | 2 +- .../Pipelines/RequestLoggingPipeline.cs | 6 +- .../Extensions/Pipelines/UrlBasePipeline.cs | 2 +- .../Extensions/ReqResExtensions.cs | 4 +- .../Extensions/RequestExtensions.cs | 4 +- .../Frontend/CacheableSpecification.cs | 38 +- .../Frontend/InitializeJsModule.cs | 2 - .../Frontend/Mappers/BrowserConfig.cs | 2 +- .../Frontend/Mappers/CacheBreakerProvider.cs | 2 +- .../Frontend/Mappers/FaviconMapper.cs | 4 +- .../Frontend/Mappers/HtmlMapperBase.cs | 4 +- .../Mappers/IMapHttpRequestsToDisk.cs | 3 +- .../Frontend/Mappers/IndexHtmlMapper.cs | 1 - .../Frontend/Mappers/LogFileMapper.cs | 2 +- .../Frontend/Mappers/LoginHtmlMapper.cs | 1 - .../Frontend/Mappers/ManifestMapper.cs | 2 +- .../Mappers/StaticResourceMapperBase.cs | 1 - .../Frontend/Mappers/UpdateLogFileMapper.cs | 2 +- .../Frontend/StaticResourceModule.cs | 3 +- src/Lidarr.Http/LidarrBootstrapper.cs | 11 +- src/Lidarr.Http/LidarrRestModule.cs | 7 +- .../LidarrRestModuleWithSignalR.cs | 23 +- src/Lidarr.Http/Mapping/MappingValidation.cs | 6 +- .../Mapping/ResourceMappingException.cs | 3 +- src/Lidarr.Http/PagingResource.cs | 2 +- src/Lidarr.Http/REST/BadRequestException.cs | 6 +- .../REST/MethodNotAllowedException.cs | 4 +- src/Lidarr.Http/REST/NotFoundException.cs | 6 +- src/Lidarr.Http/REST/ResourceValidator.cs | 3 +- src/Lidarr.Http/REST/RestModule.cs | 75 ++- src/Lidarr.Http/REST/RestResource.cs | 2 +- .../REST/UnsupportedMediaTypeException.cs | 2 +- src/Lidarr.Http/ResourceChangeMessage.cs | 8 +- src/Lidarr.Http/TinyIoCNancyBootstrapper.cs | 30 +- .../Validation/EmptyCollectionValidator.cs | 5 +- src/Marr.Data/Parameters/DbTypeBuilder.cs | 20 +- src/Marr.Data/QGen/Dialects/Dialect.cs | 2 +- .../QGen/Dialects/FirebirdDialect.cs | 2 +- src/Marr.Data/QGen/Dialects/OracleDialect.cs | 2 +- .../QGen/SqlitePagingQueryDecorator.cs | 2 +- .../BEncoding/BEncodedDictionary.cs | 2 +- src/MonoTorrent/Torrent.cs | 14 +- src/MonoTorrent/UriHelper.cs | 4 +- .../ClientSchemaTests/SchemaBuilderFixture.cs | 5 +- .../AutomationTestAttribute.cs | 3 +- src/NzbDrone.Automation.Test/MainPagesTest.cs | 50 +- .../CacheTests/CachedDictionaryFixture.cs | 2 +- .../CacheTests/CachedFixture.cs | 32 +- .../CacheTests/CachedManagerFixture.cs | 2 +- .../ConfigFileProviderTest.cs | 17 +- .../DiskTests/DiskProviderFixtureBase.cs | 14 +- .../DiskTests/DiskTransferServiceFixture.cs | 48 +- .../DiskTests/FreeSpaceFixtureBase.cs | 3 +- .../EnsureTest/PathExtensionFixture.cs | 1 - .../EnvironmentProviderTest.cs | 2 - .../EnvironmentProviderTest.cs | 2 - .../StartupArgumentsFixture.cs | 3 - .../ExtensionTests/FuzzyContainsFixture.cs | 6 +- .../ExceptByFixture.cs | 2 +- .../IPAddressExtensionsFixture.cs | 1 - .../ExtensionTests/UrlExtensionsFixture.cs | 6 +- src/NzbDrone.Common.Test/HashUtilFixture.cs | 2 +- .../Http/HttpClientFixture.cs | 2 +- .../Http/HttpHeaderFixture.cs | 12 +- .../Http/HttpRequestBuilderFixture.cs | 3 +- .../Http/HttpRequestFixture.cs | 2 +- .../Http/HttpUriFixture.cs | 2 +- .../Http/UserAgentBuilderFixture.cs | 2 +- .../CleanseLogMessageFixture.cs | 10 +- .../SentryTargetFixture.cs | 55 +- src/NzbDrone.Common.Test/OsPathFixture.cs | 4 +- .../PathExtensionFixture.cs | 10 +- .../ProcessProviderFixture.cs | 19 +- .../ServiceFactoryFixture.cs | 2 +- .../ServiceProviderFixture.cs | 6 +- .../TPLTests/DebouncerFixture.cs | 7 +- .../TPLTests/RateLimitServiceFixture.cs | 4 +- src/NzbDrone.Common/ArchiveService.cs | 6 +- src/NzbDrone.Common/Cache/CacheManager.cs | 3 +- src/NzbDrone.Common/Cache/Cached.cs | 4 +- src/NzbDrone.Common/Cache/CachedDictionary.cs | 3 +- src/NzbDrone.Common/Cache/ICached.cs | 2 +- src/NzbDrone.Common/Composition/Container.cs | 17 +- .../Composition/ContainerBuilderBase.cs | 14 +- src/NzbDrone.Common/Composition/IContainer.cs | 14 +- src/NzbDrone.Common/ConsoleService.cs | 1 + src/NzbDrone.Common/ConvertBase32.cs | 2 +- src/NzbDrone.Common/Crypto/HashProvider.cs | 2 +- .../Disk/DestinationAlreadyExistsException.cs | 12 +- src/NzbDrone.Common/Disk/DiskProviderBase.cs | 14 +- .../Disk/DiskTransferService.cs | 32 +- src/NzbDrone.Common/Disk/DriveInfoMount.cs | 1 - .../Disk/FileSystemLookupService.cs | 43 +- src/NzbDrone.Common/Disk/IMount.cs | 3 +- .../Disk/NotParentException.cs | 6 +- src/NzbDrone.Common/Disk/OsPath.cs | 49 +- src/NzbDrone.Common/EnsureThat/Ensure.cs | 2 +- .../EnsureThat/EnsureBoolExtensions.cs | 6 +- .../EnsureThat/EnsureCollectionExtensions.cs | 18 +- .../EnsureThat/EnsureDateTimeExtensions.cs | 19 +- .../EnsureThat/EnsureDecimalExtensions.cs | 14 +- .../EnsureThat/EnsureDoubleExtensions.cs | 14 +- .../EnsureThat/EnsureGuidExtensions.cs | 4 +- .../EnsureThat/EnsureIntExtensions.cs | 16 +- .../EnsureThat/EnsureLongExtensions.cs | 14 +- .../EnsureNullableValueTypeExtensions.cs | 7 +- .../EnsureThat/EnsureObjectExtensions.cs | 7 +- .../EnsureThat/EnsureShortExtensions.cs | 14 +- .../EnsureThat/EnsureStringExtensions.cs | 24 +- .../EnsureThat/EnsureTypeExtensions.cs | 6 +- .../EnsureThat/ExceptionFactory.cs | 2 +- .../EnsureThat/ExpressionExtensions.cs | 10 +- src/NzbDrone.Common/EnsureThat/Param.cs | 5 +- src/NzbDrone.Common/EnsureThat/TypeParam.cs | 2 +- .../EnvironmentInfo/AppFolderFactory.cs | 10 +- .../EnvironmentInfo/AppFolderInfo.cs | 7 +- .../EnvironmentInfo/BuildInfo.cs | 2 +- .../EnvironmentInfo/IOsVersionAdapter.cs | 3 +- src/NzbDrone.Common/EnvironmentInfo/OsInfo.cs | 7 +- .../EnvironmentInfo/OsVersionModel.cs | 4 +- .../EnvironmentInfo/PlatformInfo.cs | 10 +- .../EnvironmentInfo/RuntimeInfo.cs | 75 ++- .../Exceptions/LidarrStartupException.cs | 4 - .../Exceptions/NzbDroneException.cs | 3 - .../Exceptions/ServiceProviderException.cs | 2 - .../Expansive/CircularReferenceException.cs | 2 +- src/NzbDrone.Common/Expansive/Expansive.cs | 49 +- src/NzbDrone.Common/Expansive/PatternStyle.cs | 2 +- src/NzbDrone.Common/Expansive/Tree.cs | 2 +- src/NzbDrone.Common/Expansive/TreeNode.cs | 27 +- src/NzbDrone.Common/Expansive/TreeNodeList.cs | 19 +- .../Extensions/DictionaryExtensions.cs | 11 +- .../Extensions/ExceptionExtensions.cs | 29 +- .../Extensions/FuzzyContains.cs | 84 ++- .../Extensions/IEnumerableExtensions.cs | 18 +- .../Extensions/Int64Extensions.cs | 11 +- .../Extensions/LevenstheinExtensions.cs | 19 +- .../Extensions/ObjectExtensions.cs | 5 +- .../Extensions/PathExtensions.cs | 10 +- .../Extensions/StreamExtensions.cs | 1 + .../Extensions/StringExtensions.cs | 25 +- .../Extensions/TryParseExtensions.cs | 1 - .../Extensions/UrlExtensions.cs | 1 - src/NzbDrone.Common/HashUtil.cs | 5 +- .../Http/Dispatchers/ManagedHttpDispatcher.cs | 5 +- src/NzbDrone.Common/Http/GZipWebClient.cs | 2 +- src/NzbDrone.Common/Http/HttpAccept.cs | 2 +- src/NzbDrone.Common/Http/HttpClient.cs | 12 +- src/NzbDrone.Common/Http/HttpException.cs | 2 - src/NzbDrone.Common/Http/HttpHeader.cs | 18 +- 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 | 15 +- .../Http/JsonRpcRequestBuilder.cs | 2 +- .../Http/Proxy/HttpProxySettings.cs | 6 +- .../Http/Proxy/ManagedWebProxyFactory.cs | 2 + .../Http/TlsFailureException.cs | 8 +- .../Http/UnexpectedHtmlContentException.cs | 3 - src/NzbDrone.Common/Http/UserAgentBuilder.cs | 2 +- .../Instrumentation/CleansingJsonVisitor.cs | 7 +- .../Extensions/SentryLoggerExtensions.cs | 7 +- .../GlobalExceptionHandlers.cs | 7 +- .../Instrumentation/InitializeLogger.cs | 2 - .../Instrumentation/LogEventExtensions.cs | 3 +- .../Instrumentation/NzbDroneLogger.cs | 9 +- .../Instrumentation/Sentry/SentryCleanser.cs | 7 +- .../Instrumentation/Sentry/SentryDebounce.cs | 2 +- .../Instrumentation/Sentry/SentryTarget.cs | 51 +- src/NzbDrone.Common/Messaging/IEvent.cs | 2 +- src/NzbDrone.Common/Messaging/IMessage.cs | 2 +- src/NzbDrone.Common/Model/ProcessInfo.cs | 2 +- src/NzbDrone.Common/OAuth/OAuthRequest.cs | 16 +- src/NzbDrone.Common/OAuth/OAuthRequestType.cs | 2 +- .../OAuth/OAuthSignatureMethod.cs | 2 +- .../OAuth/OAuthSignatureTreatment.cs | 2 +- src/NzbDrone.Common/OAuth/OAuthTools.cs | 34 +- .../OAuth/WebParameterCollection.cs | 21 +- src/NzbDrone.Common/PathEqualityComparer.cs | 1 - .../Processes/ProcessProvider.cs | 30 +- .../Reflection/ReflectionExtensions.cs | 7 +- .../Serializer/HttpUriConverter.cs | 2 +- .../Serializer/IntConverter.cs | 3 +- src/NzbDrone.Common/Serializer/Json.cs | 8 +- src/NzbDrone.Common/Serializer/JsonVisitor.cs | 9 +- .../UnderscoreStringEnumConverter.cs | 2 + src/NzbDrone.Common/ServiceFactory.cs | 16 +- src/NzbDrone.Common/ServiceProvider.cs | 3 +- src/NzbDrone.Common/TPL/Debouncer.cs | 4 +- .../LimitedConcurrencyLevelTaskScheduler.cs | 115 ++-- src/NzbDrone.Common/TPL/RateLimitService.cs | 2 +- src/NzbDrone.Common/TPL/TaskExtensions.cs | 2 +- src/NzbDrone.Common/TinyIoC.cs | 301 +++++----- src/NzbDrone.Console/ConsoleAlerts.cs | 2 +- src/NzbDrone.Console/ConsoleApp.cs | 8 +- .../ArtistStatisticsFixture.cs | 12 +- .../BlacklistRepositoryFixture.cs | 14 +- .../Blacklisting/BlacklistServiceFixture.cs | 16 +- .../Configuration/ConfigCachingFixture.cs | 3 - .../Configuration/ConfigServiceFixture.cs | 1 - .../Datastore/BasicRepositoryFixture.cs | 11 +- .../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 | 10 +- .../Converters/QualityIntConverterFixture.cs | 12 +- .../Converters/TimeSpanConverterFixture.cs | 18 +- .../Converters/UtcConverterFixture.cs | 10 +- .../Datastore/DatabaseFixture.cs | 3 +- .../Datastore/DatabaseRelationshipFixture.cs | 9 +- .../Datastore/MappingExtentionFixture.cs | 4 - .../Datastore/MarrDataLazyLoadingFixture.cs | 64 +-- .../023_add_release_groups_etcFixture.cs | 100 ++-- ...30_add_mediafilerepository_mtimeFixture.cs | 350 ++++++------ ..._add_artistmetadataid_constraintFixture.cs | 105 ++-- .../Datastore/ObjectDatabaseFixture.cs | 15 +- .../PagingOffsetFixture.cs | 13 +- .../ToSortDirectionFixture.cs | 10 +- .../ReflectionStrategyFixture/Benchmarks.cs | 47 +- .../SqliteSchemaDumperFixture.cs | 3 +- .../AcceptableSizeSpecificationFixture.cs | 154 +++--- .../AlreadyImportedSpecificationFixture.cs | 9 +- .../CutoffSpecificationFixture.cs | 18 +- .../DiscographySpecificationFixture.cs | 12 +- .../DownloadDecisionMakerFixture.cs | 31 +- .../EarlyReleaseSpecificationFixture.cs | 9 +- .../HistorySpecificationFixture.cs | 37 +- .../MinimumAgeSpecificationFixture.cs | 2 +- .../MonitoredAlbumSpecificationFixture.cs | 5 +- .../PrioritizeDownloadDecisionFixture.cs | 20 +- .../ProtocolSpecificationFixture.cs | 6 +- ...ityAllowedByProfileSpecificationFixture.cs | 26 +- .../QueueSpecificationFixture.cs | 2 +- .../RawDiskSpecificationFixture.cs | 7 +- ...ReleaseRestrictionsSpecificationFixture.cs | 20 +- .../RepackSpecificationFixture.cs | 83 ++- .../RetentionSpecificationFixture.cs | 2 +- .../RssSync/DelaySpecificationFixture.cs | 14 +- .../DeletedTrackFileSpecificationFixture.cs | 47 +- .../RssSync/ProperSpecificationFixture.cs | 12 +- .../Search/ArtistSpecificationFixture.cs | 2 +- .../TorrentSeedingSpecificationFixture.cs | 4 +- .../UpgradeAllowedSpecificationFixture.cs | 30 +- .../UpgradeDiskSpecificationFixture.cs | 10 +- .../UpgradeSpecificationFixture.cs | 7 +- .../DiskSpace/DiskSpaceServiceFixture.cs | 5 +- .../CompletedDownloadServiceFixture.cs | 74 ++- .../DownloadApprovedFixture.cs | 23 +- .../Download/DownloadClientProviderFixture.cs | 2 - .../Blackhole/ScanWatchFolderFixture.cs | 6 +- .../Blackhole/UsenetBlackholeFixture.cs | 3 - .../DelugeTests/DelugeFixture.cs | 100 ++-- .../DownloadClientFixtureBase.cs | 26 +- .../TorrentDownloadStationFixture.cs | 58 +- .../UsenetDownloadStationFixture.cs | 28 +- .../HadoukenTests/HadoukenFixture.cs | 14 +- .../NzbVortexTests/NzbVortexFixture.cs | 70 +-- .../NzbgetTests/NzbgetFixture.cs | 93 ++-- .../QBittorrentTests/QBittorrentFixture.cs | 16 +- .../RTorrentTests/RTorrentFixture.cs | 41 +- .../SabnzbdQueueTimeConverterFixture.cs | 6 +- .../SabnzbdTests/SabnzbdFixture.cs | 66 +-- .../TransmissionTests/TransmissionFixture.cs | 4 +- .../TransmissionFixtureBase.cs | 13 +- .../UTorrentTests/UTorrentFixture.cs | 104 ++-- .../VuzeTests/VuzeFixture.cs | 1 - .../Download/DownloadServiceFixture.cs | 20 +- .../Download/FailedDownloadServiceFixture.cs | 5 +- .../PendingReleaseServiceTests/AddFixture.cs | 19 +- .../PendingReleaseServiceFixture.cs | 7 +- .../RemoveGrabbedFixture.cs | 18 +- .../RemovePendingFixture.cs | 21 +- .../RemoveRejectedFixture.cs | 17 +- .../RedownloadFailedDownloadServiceFixture.cs | 36 +- .../TrackedDownloadServiceFixture.cs | 16 +- .../Roksbox/FindMetadataFileFixture.cs | 2 +- .../Consumers/Wdtv/FindMetadataFileFixture.cs | 2 +- .../Consumers/Xbmc/FindMetadataFileFixture.cs | 2 +- src/NzbDrone.Core.Test/FluentTest.cs | 37 +- src/NzbDrone.Core.Test/Framework/CoreTest.cs | 14 +- src/NzbDrone.Core.Test/Framework/DbTest.cs | 9 +- .../Framework/DirectDataMapper.cs | 10 +- .../Framework/FileSystemTest.cs | 12 +- .../Framework/MigrationTest.cs | 3 +- .../Framework/NBuilderExtensions.cs | 12 +- .../Framework/TestDatabase.cs | 36 +- .../Checks/DeleteBadMediaCovers.cs | 20 +- .../Checks/DownloadClientCheckFixture.cs | 3 +- .../Checks/ImportListStatusCheckFixture.cs | 15 +- .../Checks/ImportMechanismCheckFixture.cs | 5 +- .../Checks/IndexerStatusCheckFixture.cs | 15 +- .../Checks/RemotePathMappingCheckFixture.cs | 135 ++--- .../Checks/RootFolderCheckFixture.cs | 2 +- .../HistoryTests/HistoryRepositoryFixture.cs | 7 +- .../HistoryTests/HistoryServiceFixture.cs | 22 +- .../CleanupAdditionalNamingSpecsFixture.cs | 2 +- .../CleanupAdditionalUsersFixture.cs | 2 +- .../CleanupOrphanedAlbumsFixture.cs | 4 +- .../CleanupOrphanedBlacklistFixture.cs | 6 +- .../CleanupOrphanedHistoryItemsFixture.cs | 2 +- .../CleanupOrphanedIndexerStatusFixture.cs | 2 +- .../CleanupOrphanedMetadataFilesFixture.cs | 2 +- .../CleanupOrphanedPendingReleasesFixture.cs | 2 +- .../CleanupOrphanedTrackFilesFixture.cs | 4 +- .../CleanupOrphanedTracksFixture.cs | 2 +- .../Housekeepers/CleanupUnusedTagsFixture.cs | 4 +- ...xFutureDownloadClientStatusTimesFixture.cs | 18 +- .../FixFutureImportListStatusTimesFixture.cs | 18 +- .../FixFutureIndexerStatusTimesFixture.cs | 18 +- .../UpdateCleanTitleForArtistFixture.cs | 3 +- .../Http/HttpProxySettingsProviderFixture.cs | 8 +- .../TorCacheHttpRequestInterceptorFixture.cs | 4 +- .../ImportListServiceFixture.cs | 2 +- .../ImportListSyncServiceFixture.cs | 33 +- .../Spotify/SpotifyFollowedArtistsFixture.cs | 74 ++- .../Spotify/SpotifyMappingFixture.cs | 3 +- .../Spotify/SpotifyPlaylistFixture.cs | 134 +++-- .../Spotify/SpotifySavedAlbumsFixture.cs | 77 ++- .../ArtistSearchServiceFixture.cs | 12 +- .../SearchDefinitionFixture.cs | 6 +- .../GazelleTests/GazelleFixture.cs | 2 +- .../HeadphonesTests/HeadphonesFixture.cs | 16 +- .../IPTorrentsTests/IPTorrentsFixture.cs | 20 +- .../IndexerTests/IndexerServiceFixture.cs | 2 +- .../IndexerIntegrationTests.cs | 7 +- .../NewznabTests/NewznabFixture.cs | 20 +- .../NewznabRequestGeneratorFixture.cs | 10 +- .../NewznabTests/NewznabSettingFixture.cs | 7 - .../IndexerTests/NyaaTests/NyaaFixture.cs | 10 +- .../OmgwtfnzbsTests/OmgwtfnzbsFixture.cs | 16 +- .../IndexerTests/RarbgTests/RarbgFixture.cs | 8 +- .../IndexerTests/TestIndexer.cs | 1 - .../IndexerTests/TestIndexerSettings.cs | 1 - .../TestTorrentRssIndexer.cs | 10 +- .../TorrentRssIndexerFixture.cs | 6 +- .../TorrentRssParserFactoryFixture.cs | 8 +- .../TorrentRssSettingsDetectorFixture.cs | 17 +- .../TorrentleechTests/TorrentleechFixture.cs | 18 +- .../TorznabTests/TorznabFixture.cs | 14 +- .../WafflesTests/WafflesFixture.cs | 16 +- .../Instrumentation/DatabaseTargetFixture.cs | 6 +- .../CoverExistsSpecificationFixture.cs | 4 +- .../MediaCoverServiceFixture.cs | 10 +- .../MediaFiles/AudioTagServiceFixture.cs | 173 +++--- .../DiskScanServiceTests/ScanFixture.cs | 67 ++- .../DownloadedAlbumsCommandServiceFixture.cs | 17 +- .../DownloadedTracksImportServiceFixture.cs | 15 +- .../MediaFiles/ImportApprovedTracksFixture.cs | 14 +- .../DeleteTrackFileFixture.cs | 2 +- .../MediaFiles/MediaFileRepositoryFixture.cs | 76 +-- .../MediaFileServiceTests/FilterFixture.cs | 67 +-- .../MediaFileServiceFixture.cs | 3 +- .../MediaFileTableCleanupServiceFixture.cs | 13 +- .../RenameTrackFileServiceFixture.cs | 6 +- .../MoveTrackFileFixture.cs | 4 +- .../AggregateFilenameInfoFixture.cs | 108 ++-- .../Identification/AlbumDistanceFixture.cs | 51 +- .../Identification/DistanceFixture.cs | 54 +- .../Identification/GetCandidatesFixture.cs | 57 +- .../IdentificationServiceFixture.cs | 69 +-- .../Identification/MunkresFixture.cs | 152 +++--- .../Identification/TrackDistanceFixture.cs | 16 +- .../TrackGroupingServiceFixture.cs | 121 ++-- .../Identification/TrackMappingFixture.cs | 89 +-- .../TrackImport/ImportDecisionMakerFixture.cs | 46 +- .../FreeSpaceSpecificationFixture.cs | 14 +- .../NotUnpackingSpecificationFixture.cs | 2 +- .../SameFileSpecificationFixture.cs | 2 +- .../UpgradeSpecificationFixture.cs | 5 +- .../UpgradeMediaFileServiceFixture.cs | 19 +- .../CommandEqualityComparerFixture.cs | 6 +- .../Commands/CommandExecutorFixture.cs | 3 - .../Messaging/Commands/CommandQueueFixture.cs | 11 +- .../Events/EventAggregatorFixture.cs | 117 ++-- .../MetadataRequestBuilderFixture.cs | 6 +- .../SearchArtistComparerFixture.cs | 2 +- .../SkyHook/SkyHookProxyFixture.cs | 57 +- .../SkyHook/SkyHookProxySearchFixture.cs | 20 +- .../MusicTests/AddAlbumFixture.cs | 4 +- .../MusicTests/AddArtistFixture.cs | 10 +- .../AlbumMonitoredServiceFixture.cs | 7 +- .../AlbumRepositoryFixture.cs | 31 +- .../MusicTests/AlbumServiceFixture.cs | 34 +- .../ArtistMetadataRepositoryFixture.cs | 20 +- .../ArtistRepositoryFixture.cs | 23 +- .../FindByNameInexactFixture.cs | 6 +- .../UpdateMultipleArtistFixture.cs | 2 - .../MusicTests/EntityFixture.cs | 52 +- .../MusicTests/MoveArtistServiceFixture.cs | 26 +- .../RefreshAlbumReleaseServiceFixture.cs | 17 +- .../MusicTests/RefreshAlbumServiceFixture.cs | 58 +- .../MusicTests/RefreshArtistServiceFixture.cs | 27 +- .../MusicTests/RefreshTrackServiceFixture.cs | 5 +- .../MusicTests/ShouldRefreshAlbumFixture.cs | 5 +- .../MusicTests/ShouldRefreshArtistFixture.cs | 2 +- .../NotificationBaseFixture.cs | 18 +- .../SynologyIndexerFixture.cs | 17 +- .../Xbmc/GetArtistPathFixture.cs | 14 +- .../Xbmc/OnReleaseImportFixture.cs | 18 +- .../NotificationTests/Xbmc/UpdateFixture.cs | 10 +- .../OrganizerTests/BuildFilePathFixture.cs | 10 +- .../OrganizerTests/CleanFixture.cs | 3 +- .../FileNameBuilderTests/CleanTitleFixture.cs | 2 +- .../FileNameBuilderFixture.cs | 34 +- .../FileNameBuilderTests/TitleTheFixture.cs | 5 +- .../OrganizerTests/GetAlbumFolderFixture.cs | 14 +- .../OrganizerTests/GetArtistFolderFixture.cs | 12 +- .../ParserTests/ArtistTitleInfoFixture.cs | 3 +- .../ParserTests/CrapParserFixture.cs | 7 +- .../FingerprintingServiceFixture.cs | 35 +- .../ParserTests/HashedReleaseFixture.cs | 4 +- .../ParserTests/MusicParserFixture.cs | 5 - .../ParserTests/NormalizeTitleFixture.cs | 4 +- .../ParserTests/ParserFixture.cs | 18 +- .../ParsingServiceTests/GetAlbumsFixture.cs | 22 +- .../ParsingServiceTests/GetArtistFixture.cs | 2 +- .../ParserTests/PathParserFixture.cs | 7 +- .../ParserTests/QualityParserFixture.cs | 37 +- .../ParserTests/ReleaseGroupParserFixture.cs | 3 + .../Delay/DelayProfileServiceFixture.cs | 3 +- .../MetadataProfileRepositoryFixture.cs | 4 +- .../Metadata/MetadataProfileServiceFixture.cs | 9 +- .../Profiles/ProfileRepositoryFixture.cs | 12 +- .../Profiles/ProfileServiceFixture.cs | 6 +- .../Qualities/QualityIndexCompareToFixture.cs | 1 - .../PreferredWordService/CalculateFixture.cs | 11 +- .../GetMatchingPreferredWordsFixture.cs | 4 +- .../ArchiveProviderFixture.cs | 4 +- .../GetAudioFilesFixture.cs | 36 +- .../RecycleBinProviderTests/CleanupFixture.cs | 6 +- .../DeleteFileFixture.cs | 1 - .../RecycleBinProviderTests/EmptyFixture.cs | 8 +- .../QualityDefinitionServiceFixture.cs | 4 +- .../Qualities/QualityFixture.cs | 34 +- .../Qualities/QualityModelComparerFixture.cs | 1 - .../Qualities/RevisionComparableFixture.cs | 8 +- .../QueueTests/QueueServiceFixture.cs | 13 +- .../RemotePathMappingServiceFixture.cs | 8 +- .../RootFolderServiceFixture.cs | 5 +- .../ThingiProviderTests/NullConfigFixture.cs | 2 +- .../ProviderBaseFixture.cs | 2 +- .../ProviderStatusServiceFixture.cs | 1 - .../UpdatePackageProviderFixture.cs | 3 +- .../UpdateTests/UpdateServiceFixture.cs | 11 +- .../ValidationTests/GuidValidationFixture.cs | 2 +- .../SystemFolderValidatorFixture.cs | 4 +- .../Analytics/AnalyticsService.cs | 4 +- .../ArtistStats/AlbumStatistics.cs | 1 - .../ArtistStats/ArtistStatistics.cs | 3 +- .../ArtistStats/ArtistStatisticsService.cs | 23 +- .../Authentication/UserService.cs | 10 +- src/NzbDrone.Core/Backup/BackupService.cs | 12 +- .../Backup/MakeDatabaseBackup.cs | 6 +- .../Backup/RestoreBackupFailedException.cs | 6 +- src/NzbDrone.Core/Blacklisting/Blacklist.cs | 2 +- .../Blacklisting/BlacklistRepository.cs | 6 +- .../Blacklisting/BlacklistService.cs | 44 +- .../Blacklisting/ClearBlacklistCommand.cs | 2 +- .../AccessDeniedConfigFileException.cs | 6 +- src/NzbDrone.Core/Configuration/Config.cs | 2 +- .../Configuration/ConfigFileProvider.cs | 9 +- .../Configuration/ConfigRepository.cs | 6 +- .../Configuration/ConfigService.cs | 11 +- .../Configuration/IConfigService.cs | 4 +- .../InvalidConfigFileException.cs | 6 +- .../Datastore/BasicRepository.cs | 8 +- .../Datastore/ConnectionStringFactory.cs | 6 +- .../Converters/BooleanIntConverter.cs | 4 +- .../Datastore/Converters/CommandConverter.cs | 2 +- .../Converters/EmbeddedDocumentConverter.cs | 30 +- .../Datastore/Converters/EnumIntConverter.cs | 2 +- .../PrimaryAlbumTypeIntConverter.cs | 15 +- .../Converters/ProviderSettingConverter.cs | 6 +- .../Converters/QualityIntConverter.cs | 7 +- .../Converters/ReleaseStatusIntConverter.cs | 15 +- .../SecondaryAlbumTypeIntConverter.cs | 14 +- .../Datastore/Converters/TimeSpanConverter.cs | 2 +- .../Datastore/Converters/UtcConverter.cs | 2 +- .../Datastore/CorruptDatabaseException.cs | 12 +- src/NzbDrone.Core/Datastore/DbFactory.cs | 6 +- .../Datastore/Events/ModelEvent.cs | 4 +- .../Datastore/Extensions/MappingExtensions.cs | 22 +- .../Extensions/PagingSpecExtensions.cs | 8 +- .../Extensions/RelationshipExtensions.cs | 9 +- .../Datastore/IEmbeddedDocument.cs | 2 +- src/NzbDrone.Core/Datastore/LazyList.cs | 4 +- src/NzbDrone.Core/Datastore/LogDatabase.cs | 1 - src/NzbDrone.Core/Datastore/MainDatabase.cs | 1 - .../Datastore/Migration/001_initial_setup.cs | 2 - .../Migration/003_add_medium_support.cs | 3 +- .../004_add_various_qualities_in_profile.cs | 91 ++-- .../Migration/005_metadata_profiles.cs | 1 - .../Migration/012_add_release_status.cs | 4 +- .../019_add_ape_quality_in_profiles.cs | 7 +- .../Migration/023_add_release_groups_etc.cs | 66 +-- .../029_health_issue_notification.cs | 2 +- .../030_add_mediafilerepository_mtime.cs | 4 +- .../031_add_artistmetadataid_constraint.cs | 2 +- .../Migration/032_old_ids_and_artist_alias.cs | 2 +- .../Migration/035_multi_disc_naming_format.cs | 2 - .../036_add_download_client_priority.cs | 1 - .../Framework/MigrationController.cs | 9 +- .../Framework/NzbDroneSQLiteProcessor.cs | 3 +- .../Migration/Framework/SqliteSchemaDumper.cs | 20 +- .../Migration/Framework/SqliteSyntaxReader.cs | 32 +- .../Migration/Framework/TableDefinition.cs | 5 - .../Datastore/ModelConflictException.cs | 4 +- .../Datastore/ModelNotFoundException.cs | 3 +- src/NzbDrone.Core/Datastore/ResultSet.cs | 2 +- src/NzbDrone.Core/Datastore/TableMapping.cs | 48 +- .../DecisionEngine/DownloadDecision.cs | 2 +- .../DownloadDecisionComparer.cs | 4 +- .../DecisionEngine/DownloadDecisionMaker.cs | 12 +- .../DownloadDecisionPriorizationService.cs | 2 +- .../AcceptableSizeSpecification.cs | 6 +- .../AlreadyImportedSpecification.cs | 3 +- .../Specifications/CutoffSpecification.cs | 14 +- .../DiscographySpecification.cs | 4 +- .../EarlyReleaseSpecification.cs | 7 +- .../Specifications/MinimumAgeSpecification.cs | 1 - .../Specifications/NotSampleSpecification.cs | 14 +- .../QualityAllowedByProfileSpecification.cs | 1 - .../Specifications/QueueSpecification.cs | 3 - .../Specifications/RawDiskSpecification.cs | 10 +- .../Specifications/RepackSpecification.cs | 1 - .../RssSync/DelaySpecification.cs | 4 +- .../RssSync/DeletedTrackFileSpecification.cs | 4 +- .../RssSync/ProperSpecification.cs | 3 +- .../Specifications/SameTracksSpecification.cs | 2 - .../Search/AlbumRequestedSpecification.cs | 2 - .../SingleAlbumSearchMatchSpecification.cs | 3 +- .../TorrentSeedingSpecification.cs | 1 - .../Specifications/UpgradableSpecification.cs | 10 +- .../UpgradeAllowedSpecification.cs | 11 +- .../UpgradeDiskSpecification.cs | 13 +- .../DiskSpace/DiskSpaceService.cs | 10 +- .../RemoteAlbumAggregationService.cs | 1 - .../Download/AlbumGrabbedEvent.cs | 2 +- .../Clients/Blackhole/ScanWatchFolder.cs | 4 +- .../Clients/Blackhole/TorrentBlackhole.cs | 1 - .../Clients/Blackhole/UsenetBlackhole.cs | 2 +- .../Clients/Blackhole/WatchFolderItem.cs | 5 +- .../Download/Clients/Deluge/Deluge.cs | 36 +- .../Clients/Deluge/DelugeException.cs | 2 +- .../Download/Clients/Deluge/DelugePriority.cs | 2 +- .../Download/Clients/Deluge/DelugeProxy.cs | 28 +- .../Download/Clients/Deluge/DelugeTorrent.cs | 4 +- .../DownloadClientAuthenticationException.cs | 3 - .../DownloadStation/DiskStationApiInfo.cs | 7 +- .../DownloadStationSettings.cs | 4 +- .../DownloadStation/DownloadStationTask.cs | 9 +- .../DownloadStationTaskAdditional.cs | 4 +- .../DownloadStationTaskFile.cs | 5 - .../DownloadStation/Proxies/DSMInfoProxy.cs | 8 +- .../Proxies/DiskStationProxyBase.cs | 7 +- .../Proxies/DownloadStationInfoProxy.cs | 10 +- .../Proxies/FileStationProxy.cs | 6 +- .../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 | 14 +- .../DownloadStation/UsenetDownloadStation.cs | 13 +- .../Download/Clients/Hadouken/Hadouken.cs | 11 +- .../Clients/Hadouken/HadoukenProxy.cs | 4 +- .../Download/Clients/NzbVortex/NzbVortex.cs | 36 +- .../NzbVortexAuthenticationException.cs | 14 +- .../NzbVortexNotLoggedInException.cs | 17 +- .../Clients/NzbVortex/NzbVortexPriority.cs | 2 +- .../Clients/NzbVortex/NzbVortexProxy.cs | 7 +- .../Download/Clients/Nzbget/Nzbget.cs | 12 +- .../Download/Clients/Nzbget/NzbgetProxy.cs | 8 +- .../Download/Clients/Nzbget/NzbgetResponse.cs | 1 - .../Download/Clients/Nzbget/NzbgetSettings.cs | 2 +- .../Download/Clients/Pneumatic/Pneumatic.cs | 4 +- .../Clients/QBittorrent/QBittorrent.cs | 42 +- .../Clients/QBittorrent/QBittorrentLabel.cs | 4 +- .../QBittorrent/QBittorrentProxySelector.cs | 7 +- .../Clients/QBittorrent/QBittorrentProxyV1.cs | 11 +- .../Clients/QBittorrent/QBittorrentProxyV2.cs | 7 +- .../Clients/QBittorrent/QBittorrentTorrent.cs | 1 - .../SabnzbdPriorityTypeConverter.cs | 2 +- .../SabnzbdQueueTimeConverter.cs | 4 +- .../Download/Clients/Sabnzbd/Sabnzbd.cs | 14 +- .../Clients/Sabnzbd/SabnzbdFullStatus.cs | 6 +- .../Clients/Sabnzbd/SabnzbdPriority.cs | 2 +- .../Download/Clients/Sabnzbd/SabnzbdProxy.cs | 8 +- .../Clients/Transmission/Transmission.cs | 4 +- .../Clients/Transmission/TransmissionBase.cs | 31 +- .../Transmission/TransmissionConfig.cs | 7 +- .../Transmission/TransmissionException.cs | 1 - .../Transmission/TransmissionPriority.cs | 2 +- .../Clients/Transmission/TransmissionProxy.cs | 26 +- .../Transmission/TransmissionSettings.cs | 2 +- .../Download/Clients/rTorrent/RTorrent.cs | 28 +- .../Clients/rTorrent/RTorrentProxy.cs | 12 +- .../Clients/rTorrent/RTorrentSettings.cs | 2 +- .../Download/Clients/uTorrent/UTorrent.cs | 27 +- .../Clients/uTorrent/UTorrentPriority.cs | 2 +- .../Clients/uTorrent/UTorrentProxy.cs | 2 +- .../Clients/uTorrent/UTorrentTorrent.cs | 11 +- .../Clients/uTorrent/UTorrentTorrentCache.cs | 2 +- .../Download/CompletedDownloadService.cs | 8 +- .../Download/DownloadClientBase.cs | 13 +- .../Download/DownloadClientFactory.cs | 1 - .../Download/DownloadClientProvider.cs | 11 +- .../Download/DownloadClientRepository.cs | 3 +- .../Download/DownloadClientStatus.cs | 1 - .../DownloadClientStatusRepository.cs | 1 - .../Download/DownloadClientStatusService.cs | 1 - .../Download/DownloadClientType.cs | 2 +- .../Download/DownloadEventHub.cs | 3 +- src/NzbDrone.Core/Download/DownloadService.cs | 2 +- .../Download/FailedDownloadService.cs | 2 +- .../Download/InvalidNzbException.cs | 12 +- .../Download/Pending/PendingReleaseService.cs | 17 +- .../Download/ProcessDownloadDecisions.cs | 7 +- .../RedownloadFailedDownloadService.cs | 1 - .../Download/TorrentClientBase.cs | 16 +- .../DownloadMonitoringService.cs | 4 - .../TrackedDownloads/TrackedDownload.cs | 2 +- .../TrackedDownloadService.cs | 18 +- .../TrackedDownloadStatusMessage.cs | 1 - .../Download/UsenetClientBase.cs | 14 +- .../Exceptions/AlbumNotFoundException.cs | 4 - .../Exceptions/ArtistNotFoundException.cs | 4 - .../Exceptions/BadRequestException.cs | 6 +- .../Exceptions/DownstreamException.cs | 3 +- .../Exceptions/NzbDroneClientException.cs | 3 +- .../Exceptions/ReleaseDownloadException.cs | 3 +- src/NzbDrone.Core/Extras/ExtraService.cs | 3 +- .../Extras/Files/ExtraFileManager.cs | 1 - .../Extras/Files/ExtraFileRepository.cs | 3 +- .../Extras/Files/ExtraFileService.cs | 1 - .../Extras/Lyrics/ExistingLyricImporter.cs | 20 +- .../Extras/Lyrics/LyricService.cs | 1 - .../Consumers/Roksbox/RoksboxMetadata.cs | 25 +- .../Roksbox/RoksboxMetadataSettings.cs | 2 +- .../Metadata/Consumers/Wdtv/WdtvMetadata.cs | 20 +- .../Consumers/Wdtv/WdtvMetadataSettings.cs | 2 +- .../Metadata/Consumers/Xbmc/XbmcMetadata.cs | 11 +- .../Consumers/Xbmc/XbmcNfoDetector.cs | 4 - .../Metadata/ExistingMetadataImporter.cs | 12 +- .../Metadata/Files/MetadataFileRepository.cs | 2 +- .../Extras/Metadata/IMetadata.cs | 2 +- .../Extras/Metadata/MetadataBase.cs | 10 +- .../Extras/Metadata/MetadataFactory.cs | 2 +- .../Extras/Metadata/MetadataRepository.cs | 2 +- .../Extras/Metadata/MetadataService.cs | 9 +- .../Others/ExistingOtherExtraImporter.cs | 5 +- .../Extras/Others/OtherExtraFileRenamer.cs | 4 - .../Extras/Others/OtherExtraFileRepository.cs | 2 +- .../Extras/Others/OtherExtraService.cs | 2 - src/NzbDrone.Core/Fluent.cs | 26 +- .../Checks/AppDataLocationCheck.cs | 4 +- .../HealthCheck/Checks/DotnetVersionCheck.cs | 6 +- .../Checks/DownloadClientStatusCheck.cs | 1 - .../HealthCheck/Checks/FpcalcCheck.cs | 6 +- .../Checks/ImportListStatusCheck.cs | 1 - .../Checks/ImportMechanismCheck.cs | 1 - .../HealthCheck/Checks/IndexerRssCheck.cs | 3 +- .../HealthCheck/Checks/IndexerSearchCheck.cs | 1 - .../HealthCheck/Checks/IndexerStatusCheck.cs | 1 - .../HealthCheck/Checks/MonoTlsCheck.cs | 2 - .../HealthCheck/Checks/MonoVersionCheck.cs | 17 +- .../HealthCheck/Checks/ProxyCheck.cs | 6 +- .../Checks/RemotePathMappingCheck.cs | 5 +- .../HealthCheck/Checks/UpdateCheck.cs | 9 +- .../HealthCheck/HealthCheckService.cs | 6 - src/NzbDrone.Core/History/History.cs | 3 +- .../History/HistoryRepository.cs | 9 +- src/NzbDrone.Core/History/HistoryService.cs | 37 +- .../Housekeepers/DeleteBadMediaCovers.cs | 12 +- .../FixFutureProviderStatusTimes.cs | 3 +- .../Housekeepers/UpdateCleanTitleForArtist.cs | 2 +- .../Housekeeping/HousekeepingService.cs | 3 +- .../Housekeeping/IHousekeepingTask.cs | 2 +- .../CloudFlare/CloudFlareHttpInterceptor.cs | 3 +- .../Http/HttpProxySettingsProvider.cs | 2 +- .../ImportListExclusionExistsValidator.cs | 7 +- .../ImportListExclusionRepository.cs | 4 +- .../Exclusions/ImportListExclusionService.cs | 4 +- .../FetchAndParseImportListService.cs | 9 +- .../HeadphonesImport/HeadphonesImport.cs | 3 +- .../HeadphonesImport/HeadphonesImportApi.cs | 1 - .../HeadphonesImportParser.cs | 8 +- .../HeadphonesImportRequestGenerator.cs | 1 - .../ImportLists/HttpImportListBase.cs | 5 +- src/NzbDrone.Core/ImportLists/IImportList.cs | 2 +- .../ImportLists/ImportListBase.cs | 9 +- .../ImportLists/ImportListStatus.cs | 2 +- .../ImportLists/ImportListStatusRepository.cs | 1 - .../ImportLists/ImportListStatusService.cs | 1 - .../ImportLists/ImportListSyncService.cs | 68 ++- .../ImportLists/ImportListType.cs | 6 - .../ImportLists/LastFm/LastFmParser.cs | 6 +- .../ImportLists/LastFm/LastFmTag.cs | 3 +- .../LastFm/LastFmTagRequestGenerator.cs | 1 - .../ImportLists/LastFm/LastFmUser.cs | 3 +- .../LastFm/LastFmUserRequestGenerator.cs | 1 - .../ImportLists/LidarrLists/LidarrLists.cs | 3 +- .../LidarrLists/LidarrListsParser.cs | 8 +- .../ImportLists/Spotify/SpotifyException.cs | 12 +- .../Spotify/SpotifyFollowedArtists.cs | 1 - .../Spotify/SpotifyImportListBase.cs | 16 +- .../ImportLists/Spotify/SpotifyPlaylist.cs | 27 +- .../ImportLists/Spotify/SpotifySavedAlbums.cs | 1 - .../IndexerSearch/AlbumSearchService.cs | 9 +- .../Definitions/ArtistSearchCriteria.cs | 4 +- .../Definitions/SearchCriteriaBase.cs | 3 +- .../IndexerSearch/NzbSearchService.cs | 21 +- .../Indexers/Exceptions/ApiKeyException.cs | 6 +- .../Exceptions/SizeParsingException.cs | 3 +- .../Indexers/FetchAndParseRssService.cs | 4 +- src/NzbDrone.Core/Indexers/Gazelle/Gazelle.cs | 15 +- .../Indexers/Gazelle/GazelleApi.cs | 3 - .../Indexers/Gazelle/GazelleInfo.cs | 4 - .../Indexers/Gazelle/GazelleParser.cs | 12 +- .../Gazelle/GazelleRequestGenerator.cs | 16 +- .../Indexers/Headphones/Headphones.cs | 7 +- .../HeadphonesCapabilitiesProvider.cs | 2 - .../Headphones/HeadphonesRequestGenerator.cs | 13 +- .../Headphones/HeadphonesRssParser.cs | 2 +- .../Indexers/Headphones/HeadphonesSettings.cs | 1 - src/NzbDrone.Core/Indexers/HttpIndexerBase.cs | 6 +- src/NzbDrone.Core/Indexers/IIndexer.cs | 2 +- .../Indexers/IPTorrents/IPTorrents.cs | 5 +- .../IPTorrents/IPTorrentsRequestGenerator.cs | 2 +- src/NzbDrone.Core/Indexers/IndexerBase.cs | 5 +- .../Indexers/IndexerPageableRequestChain.cs | 12 +- .../Indexers/IndexerRepository.cs | 1 - .../Indexers/IndexerSettingUpdatedEvent.cs | 2 +- .../Indexers/IndexerStatusRepository.cs | 2 - .../Indexers/IndexerStatusService.cs | 1 - src/NzbDrone.Core/Indexers/Newznab/Newznab.cs | 28 +- .../Newznab/NewznabCapabilitiesProvider.cs | 2 - .../Newznab/NewznabRequestGenerator.cs | 14 +- .../Indexers/Newznab/NewznabRssParser.cs | 11 +- .../Indexers/Newznab/NewznabSettings.cs | 2 - src/NzbDrone.Core/Indexers/Nyaa/Nyaa.cs | 3 +- .../Indexers/Nyaa/NyaaSettings.cs | 2 +- .../Indexers/Omgwtfnzbs/Omgwtfnzbs.cs | 1 - .../Omgwtfnzbs/OmgwtfnzbsRequestGenerator.cs | 4 - .../Omgwtfnzbs/OmgwtfnzbsRssParser.cs | 17 +- .../Indexers/Omgwtfnzbs/OmgwtfnzbsSettings.cs | 1 - src/NzbDrone.Core/Indexers/Rarbg/Rarbg.cs | 4 +- .../Indexers/Rarbg/RarbgParser.cs | 2 +- .../Indexers/Rarbg/RarbgSettings.cs | 2 +- .../Indexers/Rarbg/RarbgTokenProvider.cs | 6 +- src/NzbDrone.Core/Indexers/RssEnclosure.cs | 5 - .../Indexers/RssIndexerRequestGenerator.cs | 1 - src/NzbDrone.Core/Indexers/RssParser.cs | 3 +- src/NzbDrone.Core/Indexers/RssSyncCommand.cs | 3 +- src/NzbDrone.Core/Indexers/RssSyncService.cs | 1 - .../Indexers/SeedConfigProvider.cs | 3 - .../Indexers/SeedCriteriaSettings.cs | 6 +- .../TorrentRssIndexerRequestGenerator.cs | 2 +- .../TorrentRss/TorrentRssIndexerSettings.cs | 6 +- .../TorrentRss/TorrentRssParserFactory.cs | 2 +- .../TorrentRss/TorrentRssSettingsDetector.cs | 12 +- .../Indexers/Torrentleech/Torrentleech.cs | 5 +- .../TorrentleechRequestGenerator.cs | 2 +- src/NzbDrone.Core/Indexers/Torznab/Torznab.cs | 29 +- .../Indexers/Torznab/TorznabException.cs | 6 +- .../Indexers/Torznab/TorznabRssParser.cs | 11 +- .../Indexers/Torznab/TorznabSettings.cs | 1 - src/NzbDrone.Core/Indexers/Waffles/Waffles.cs | 7 +- .../Waffles/WafflesRequestGenerator.cs | 10 +- .../Indexers/Waffles/WafflesRssParser.cs | 19 +- .../Indexers/Waffles/WafflesSettings.cs | 2 - .../Indexers/XElementExtensions.cs | 5 +- src/NzbDrone.Core/Indexers/XmlCleaner.cs | 4 +- .../Commands/ClearLogCommand.cs | 2 +- .../Commands/DeleteLogFilesCommand.cs | 2 +- .../Commands/DeleteUpdateLogFilesCommand.cs | 2 +- .../Instrumentation/DatabaseTarget.cs | 10 +- src/NzbDrone.Core/Instrumentation/Log.cs | 4 +- .../Instrumentation/LogRepository.cs | 3 +- .../Instrumentation/LogService.cs | 2 +- .../Instrumentation/ReconfigureLogging.cs | 9 +- .../SlowRunningAsyncTargetWrapper.cs | 2 - src/NzbDrone.Core/Jobs/ScheduledTask.cs | 2 +- .../Jobs/ScheduledTaskRepository.cs | 10 +- src/NzbDrone.Core/Jobs/Scheduler.cs | 5 +- src/NzbDrone.Core/Jobs/TaskManager.cs | 18 +- .../Lifecycle/ApplicationShutdownRequested.cs | 2 +- .../Lifecycle/ApplicationStartedEvent.cs | 3 +- .../Lifecycle/LifecycleService.cs | 1 - src/NzbDrone.Core/MediaCover/ImageResizer.cs | 9 +- src/NzbDrone.Core/MediaCover/MediaCover.cs | 3 +- .../MediaCover/MediaCoverService.cs | 5 +- src/NzbDrone.Core/MediaFiles/AudioTag.cs | 91 ++-- .../MediaFiles/AudioTagService.cs | 56 +- .../Commands/BackendCommandAttribute.cs | 2 +- .../Commands/CleanUpRecycleBinCommand.cs | 2 +- .../MediaFiles/DiskScanService.cs | 61 ++- .../DownloadedAlbumsCommandService.cs | 6 +- .../DownloadedTracksImportService.cs | 2 +- .../Events/AlbumImportIncompleteEvent.cs | 2 - .../MediaFiles/Events/AlbumImportedEvent.cs | 1 - .../MediaFiles/Events/ArtistRenamedEvent.cs | 4 - .../Events/ArtistScanSkippedEvent.cs | 4 - .../MediaFiles/Events/ArtistScannedEvent.cs | 4 - .../MediaFiles/Events/TrackFileAddedEvent.cs | 4 - .../Events/TrackFileDeletedEvent.cs | 4 - .../MediaFiles/Events/TrackImportedEvent.cs | 1 - .../MediaFiles/MediaFileAttributeService.cs | 2 - .../MediaFiles/MediaFileDeletionService.cs | 6 +- .../MediaFiles/MediaFileExtensions.cs | 3 +- .../MediaFiles/MediaFileRepository.cs | 5 +- .../MediaFiles/MediaFileService.cs | 15 +- .../MediaFiles/MediaInfoFormatter.cs | 33 +- .../MediaFiles/RecycleBinProvider.cs | 5 - .../MediaFiles/RenameTrackFileService.cs | 6 +- .../MediaFiles/SameFilenameException.cs | 3 +- .../TorrentInfo/TorrentFileInfoReader.cs | 4 +- src/NzbDrone.Core/MediaFiles/TrackFile.cs | 10 +- .../MediaFiles/TrackFileMoveResult.cs | 5 +- .../MediaFiles/TrackFileMovingService.cs | 12 +- .../Aggregation/AggregationFailedException.cs | 12 +- .../Aggregation/AggregationService.cs | 1 - .../Aggregators/AggregateFilenameInfo.cs | 25 +- .../Identification/CandidateAlbumRelease.cs | 5 +- .../TrackImport/Identification/Distance.cs | 49 +- .../Identification/IdentificationService.cs | 133 +++-- .../Identification/IdentificationTestCase.cs | 3 +- .../TrackImport/Identification/Munkres.cs | 57 +- .../Identification/TrackGroupingService.cs | 22 +- .../TrackImport/ImportApprovedTracks.cs | 22 +- .../MediaFiles/TrackImport/ImportDecision.cs | 7 +- .../TrackImport/ImportDecisionMaker.cs | 10 +- .../MediaFiles/TrackImport/ImportResult.cs | 8 +- .../TrackImport/Manual/ManualImportFile.cs | 5 + .../TrackImport/Manual/ManualImportItem.cs | 6 +- .../TrackImport/Manual/ManualImportService.cs | 8 +- .../RootFolderNotFoundException.cs | 9 +- .../AlbumUpgradeSpecification.cs | 3 +- .../CloseAlbumMatchSpecification.cs | 11 +- .../CloseTrackMatchSpecification.cs | 5 +- ...NoMissingOrUnmatchedTracksSpecification.cs | 3 +- .../ReleaseWantedSpecification.cs | 1 - .../Specifications/SameFileSpecification.cs | 1 - .../SameTracksImportSpecification.cs | 4 - .../Specifications/UpgradeSpecification.cs | 3 +- .../MediaFiles/UpdateTrackFileService.cs | 4 - .../MediaFiles/UpgradeMediaFileService.cs | 1 - .../Commands/BackendCommandAttribute.cs | 2 +- .../Commands/CommandEqualityComparer.cs | 9 +- .../Messaging/Commands/CommandExecutor.cs | 8 +- .../Commands/CommandFailedException.cs | 12 +- .../Commands/CommandNotFoundException.cs | 1 - .../Messaging/Commands/CommandQueue.cs | 3 +- .../Messaging/Commands/CommandQueueManager.cs | 16 +- .../Messaging/Commands/IExecute.cs | 5 +- .../Messaging/Commands/TestCommand.cs | 2 +- .../Messaging/Commands/TestCommandExecutor.cs | 2 +- .../Messaging/Events/CommandExecutedEvent.cs | 2 +- .../Messaging/Events/EventAggregator.cs | 10 +- .../Messaging/Events/IEventAggregator.cs | 5 +- src/NzbDrone.Core/Messaging/Events/IHandle.cs | 8 +- .../Messaging/IProcessMessage.cs | 18 +- .../MetadataSource/IMetadataRequestBuilder.cs | 2 +- .../MetadataSource/IProvideAlbumInfo.cs | 2 +- .../MetadataSource/IProvideArtistInfo.cs | 3 - .../MetadataSource/ISearchForNewAlbum.cs | 1 - .../MetadataSource/ISearchForNewArtist.cs | 2 +- .../MetadataSource/ISearchForNewEntity.cs | 2 +- .../MetadataSource/SearchArtistComparer.cs | 22 +- .../SkyHook/Resource/ArtistResource.cs | 1 - .../SkyHook/Resource/EntityResource.cs | 1 - .../SkyHook/Resource/ImageResource.cs | 2 +- .../SkyHook/Resource/MediumResource.cs | 7 - .../SkyHook/Resource/RatingResource.cs | 2 +- .../SkyHook/Resource/TrackResource.cs | 2 - .../SkyHook/SkyHookException.cs | 3 +- .../MetadataSource/SkyHook/SkyHookProxy.cs | 36 +- .../Music/Events/AlbumDeletedEvent.cs | 4 - .../Music/Events/AlbumEditedEvent.cs | 4 - .../Music/Events/AlbumInfoRefreshedEvent.cs | 7 +- .../Music/Events/ArtistDeletedEvent.cs | 4 - .../Music/Events/ArtistEditedEvent.cs | 4 - .../Music/Events/ReleaseDeletedEvent.cs | 4 - .../Music/Model/AddAlbumOptions.cs | 2 +- src/NzbDrone.Core/Music/Model/Album.cs | 13 +- src/NzbDrone.Core/Music/Model/Artist.cs | 19 +- .../Music/Model/ArtistMetadata.cs | 2 +- src/NzbDrone.Core/Music/Model/Entity.cs | 10 +- .../Music/Model/MonitoringOptions.cs | 4 +- .../Music/Model/PrimaryAlbumType.cs | 5 +- src/NzbDrone.Core/Music/Model/Release.cs | 4 +- .../Music/Model/ReleaseStatus.cs | 5 +- .../Music/Model/SecondaryAlbumType.cs | 5 +- src/NzbDrone.Core/Music/Model/Track.cs | 12 +- .../Music/Repositories/AlbumRepository.cs | 15 +- .../Repositories/ArtistMetadataRepository.cs | 12 +- .../Music/Repositories/ArtistRepository.cs | 4 +- .../Music/Repositories/ReleaseRepository.cs | 2 +- .../Music/Repositories/TrackRepository.cs | 2 +- .../Music/Services/AddArtistService.cs | 3 +- .../Music/Services/AlbumEditedService.cs | 2 +- .../Music/Services/AlbumMonitoredService.cs | 2 +- .../Music/Services/AlbumService.cs | 26 +- .../Music/Services/ArtistService.cs | 21 +- .../Music/Services/MoveArtistService.cs | 2 +- .../Services/RefreshAlbumReleaseService.cs | 3 +- .../Music/Services/RefreshAlbumService.cs | 28 +- .../Music/Services/RefreshArtistService.cs | 48 +- .../Services/RefreshEntityServiceBase.cs | 141 ++--- .../Music/Services/RefreshTrackService.cs | 12 +- .../Music/Services/ReleaseService.cs | 3 +- .../Music/Services/TrackService.cs | 4 +- .../Music/Utilities/AddArtistValidator.cs | 3 +- .../Music/Utilities/ShouldRefreshAlbum.cs | 2 +- .../Music/Utilities/ShouldRefreshArtist.cs | 2 +- .../Notifications/Boxcar/BoxcarException.cs | 6 +- .../Notifications/Boxcar/BoxcarProxy.cs | 6 +- .../Notifications/Discord/Discord.cs | 3 +- .../Notifications/Discord/DiscordException.cs | 8 +- .../Notifications/Discord/DiscordProxy.cs | 2 +- .../Notifications/Discord/DiscordSettings.cs | 1 - .../Notifications/DownloadFailedMessage.cs | 2 - .../Notifications/Email/Email.cs | 1 - .../Notifications/Email/EmailService.cs | 6 +- .../Notifications/Gotify/GotifyPriority.cs | 1 - .../Notifications/Gotify/GotifyProxy.cs | 2 +- .../Gotify/InvalidResponseException.cs | 3 +- .../Notifications/GrabMessage.cs | 2 +- .../Notifications/INotification.cs | 2 +- .../Notifications/Join/JoinAuthException.cs | 6 +- .../Notifications/Join/JoinException.cs | 6 +- .../Join/JoinInvalidDeviceException.cs | 6 +- .../Notifications/Join/JoinProxy.cs | 18 +- .../MediaBrowser/MediaBrowser.cs | 1 - .../MediaBrowser/MediaBrowserService.cs | 2 +- .../MediaBrowser/Model/EmbyMediaFolder.cs | 2 - .../MediaBrowser/Model/EmbyMediaUpdateInfo.cs | 2 - .../Notifications/NotificationBase.cs | 19 +- .../Notifications/NotificationDefinition.cs | 1 - .../Notifications/NotificationRepository.cs | 1 - .../Notifications/NotificationService.cs | 17 +- .../Plex/PlexAuthenticationException.cs | 3 +- .../Notifications/Plex/PlexException.cs | 9 +- .../Plex/PlexTv/PlexTvService.cs | 17 +- .../Plex/PlexVersionException.cs | 6 +- .../Notifications/Plex/Server/PlexServer.cs | 2 +- .../Plex/Server/PlexServerProxy.cs | 2 + .../Plex/Server/PlexServerService.cs | 8 +- .../Notifications/PushBullet/PushBullet.cs | 14 +- .../PushBullet/PushBulletException.cs | 6 +- .../PushBullet/PushBulletProxy.cs | 7 +- .../Pushover/InvalidResponseException.cs | 3 +- .../Notifications/Pushover/Pushover.cs | 2 +- .../Notifications/Pushover/PushoverProxy.cs | 5 +- .../Pushover/PushoverSettings.cs | 2 +- .../Notifications/Slack/Slack.cs | 5 +- .../Notifications/Slack/SlackExeption.cs | 8 +- .../Notifications/Subsonic/Subsonic.cs | 1 - .../SubsonicAuthenticationException.cs | 3 +- .../Subsonic/SubsonicException.cs | 6 +- .../Subsonic/SubsonicServerProxy.cs | 7 +- .../Notifications/Subsonic/SubsonicService.cs | 5 +- .../Subsonic/SubsonicSettings.cs | 3 +- .../Synology/SynologyException.cs | 6 +- .../Notifications/Synology/SynologyIndexer.cs | 2 - .../Synology/SynologyIndexerSettings.cs | 1 - .../Telegram/InvalidResponseException.cs | 3 +- .../Notifications/Telegram/TelegramService.cs | 4 +- .../Notifications/Twitter/OAuthToken.cs | 1 - .../Notifications/Twitter/Twitter.cs | 5 +- .../Notifications/Twitter/TwitterException.cs | 12 +- .../Notifications/Twitter/TwitterService.cs | 14 +- .../Notifications/Twitter/TwitterSettings.cs | 1 + .../Notifications/Webhook/Webhook.cs | 27 +- .../Notifications/Webhook/WebhookAlbum.cs | 6 +- .../Notifications/Webhook/WebhookArtist.cs | 4 +- .../Notifications/Webhook/WebhookException.cs | 6 +- .../Notifications/Webhook/WebhookProxy.cs | 2 +- .../Notifications/Webhook/WebhookRelease.cs | 4 +- .../Notifications/Webhook/WebhookTrack.cs | 6 +- .../Notifications/Webhook/WebhookTrackFile.cs | 4 +- .../Notifications/Xbmc/XbmcService.cs | 7 +- src/NzbDrone.Core/Organizer/Exception.cs | 6 +- .../Organizer/FileNameBuilder.cs | 24 +- .../FileNameBuilderTokenEqualityComparer.cs | 1 - .../Organizer/FileNameSampleService.cs | 8 +- .../Organizer/FileNameValidation.cs | 4 +- .../Organizer/FileNameValidationService.cs | 6 - .../Organizer/NamingConfigRepository.cs | 2 - .../Organizer/NamingConfigService.cs | 2 +- .../Parser/FingerprintingService.cs | 167 +++--- .../Parser/InvalidDateException.cs | 6 +- src/NzbDrone.Core/Parser/IsoCountries.cs | 2 +- src/NzbDrone.Core/Parser/IsoLanguage.cs | 1 - src/NzbDrone.Core/Parser/IsoLanguages.cs | 2 + .../Parser/Model/ArtistTitleInfo.cs | 7 +- .../Parser/Model/ImportListItemInfo.cs | 1 - .../Parser/Model/LocalAlbumRelease.cs | 15 +- src/NzbDrone.Core/Parser/Model/LocalTrack.cs | 6 +- .../Parser/Model/ParsedAlbumInfo.cs | 9 +- .../Parser/Model/ParsedTrackInfo.cs | 3 +- src/NzbDrone.Core/Parser/Model/ReleaseInfo.cs | 24 +- src/NzbDrone.Core/Parser/Model/TorrentInfo.cs | 2 +- src/NzbDrone.Core/Parser/Parser.cs | 43 +- src/NzbDrone.Core/Parser/ParsingService.cs | 17 +- src/NzbDrone.Core/Parser/QualityParser.cs | 515 ++++++++++++++---- src/NzbDrone.Core/Parser/RegexReplace.cs | 18 +- src/NzbDrone.Core/Parser/SceneChecker.cs | 11 +- .../Profiles/Delay/DelayProfileRepository.cs | 1 - .../Profiles/Delay/DelayProfileService.cs | 8 +- .../Delay/DelayProfileTagInUseValidator.cs | 10 +- .../Profiles/Metadata/MetadataProfile.cs | 1 - .../Metadata/MetadataProfileInUseException.cs | 1 - .../Metadata/MetadataProfileService.cs | 17 +- .../Qualities/QualityProfileInUseException.cs | 1 - .../Qualities/QualityProfileService.cs | 19 +- .../Profiles/Releases/PreferredWordService.cs | 4 +- .../Profiles/Releases/TermMatcherService.cs | 1 - .../ProgressMessageContext.cs | 4 +- .../ProgressMessageTarget.cs | 17 +- src/NzbDrone.Core/Qualities/Quality.cs | 34 +- .../Qualities/QualityDefinition.cs | 2 - .../Qualities/QualityDefinitionRepository.cs | 3 - .../Qualities/QualityDefinitionService.cs | 7 +- src/NzbDrone.Core/Qualities/QualityModel.cs | 32 +- src/NzbDrone.Core/Qualities/Revision.cs | 85 ++- src/NzbDrone.Core/Queue/Queue.cs | 2 +- src/NzbDrone.Core/Queue/QueueService.cs | 4 +- .../RemotePathMappings/RemotePathMapping.cs | 3 +- .../RemotePathMappingRepository.cs | 2 - .../RemotePathMappingService.cs | 8 +- src/NzbDrone.Core/Rest/JsonNetSerializer.cs | 2 +- src/NzbDrone.Core/Rest/RestClientFactory.cs | 5 +- src/NzbDrone.Core/Rest/RestException.cs | 2 +- src/NzbDrone.Core/Rest/RestSharpExtensions.cs | 20 +- src/NzbDrone.Core/RootFolders/RootFolder.cs | 1 - .../RootFolders/RootFolderRepository.cs | 4 +- .../RootFolders/RootFolderService.cs | 5 +- .../RootFolders/UnmappedFolder.cs | 2 +- .../X509CertificateValidationService.cs | 3 +- src/NzbDrone.Core/Tags/TagDetails.cs | 2 +- src/NzbDrone.Core/Tags/TagService.cs | 24 +- .../ConfigContractNotFoundException.cs | 1 - .../Events/ProviderUpdatedEvent.cs | 2 +- src/NzbDrone.Core/ThingiProvider/IProvider.cs | 2 +- .../ThingiProvider/IProviderConfig.cs | 2 +- .../ThingiProvider/IProviderFactory.cs | 2 +- .../ThingiProvider/IProviderRepository.cs | 7 +- .../ThingiProvider/NullConfig.cs | 2 +- .../ThingiProvider/ProviderRepository.cs | 10 +- .../Status/ProviderStatusBase.cs | 3 - .../Status/ProviderStatusRepository.cs | 4 - .../Status/ProviderStatusServiceBase.cs | 1 - src/NzbDrone.Core/TinyTwitter.cs | 73 +-- .../Update/InstallUpdateService.cs | 2 +- .../Update/UpdateCheckService.cs | 3 +- .../Update/UpdatePackageProvider.cs | 5 +- .../UpdateVerificationFailedException.cs | 2 +- .../Validation/FolderValidator.cs | 8 +- src/NzbDrone.Core/Validation/GuidValidator.cs | 7 +- .../MetadataProfileExistsValidator.cs | 11 +- .../Validation/NzbDroneValidationFailure.cs | 2 - .../Validation/NzbDroneValidationResult.cs | 3 +- .../Paths/ArtistAncestorValidator.cs | 5 +- .../Validation/Paths/ArtistExistsValidator.cs | 11 +- .../Validation/Paths/ArtistPathValidator.cs | 11 +- .../Paths/FolderWritableValidator.cs | 9 +- .../Paths/MappedNetworkDriveValidator.cs | 26 +- .../Validation/Paths/PathExistsValidator.cs | 9 +- .../Validation/Paths/PathValidator.cs | 8 +- .../Validation/Paths/RootFolderValidator.cs | 9 +- .../Paths/StartupFolderValidator.cs | 8 +- .../Validation/ProfileExistsValidator.cs | 5 +- .../Validation/RuleBuilderExtensions.cs | 1 - src/NzbDrone.Core/Validation/UrlValidator.cs | 8 +- src/NzbDrone.Host.Test/ContainerFixture.cs | 16 +- .../NzbDroneProcessServiceFixture.cs | 11 +- src/NzbDrone.Host.Test/RouterTest.cs | 5 - .../AccessControl/FirewallAdapter.cs | 6 +- .../AccessControl/RemoteAccessException.cs | 12 +- src/NzbDrone.Host/Bootstrap.cs | 4 +- src/NzbDrone.Host/BrowserService.cs | 2 +- src/NzbDrone.Host/IUserAlert.cs | 2 +- src/NzbDrone.Host/MainAppContainerBuilder.cs | 3 +- src/NzbDrone.Host/PlatformValidation.cs | 8 +- src/NzbDrone.Host/Router.cs | 7 +- .../TerminateApplicationException.cs | 2 +- .../WebHost/Middleware/SignalRMiddleware.cs | 2 +- .../WebHost/WebHostController.cs | 10 +- .../ApiTests/ArtistEditorFixture.cs | 6 +- .../ApiTests/ArtistFixture.cs | 42 +- .../ApiTests/BlacklistFixture.cs | 4 +- .../ApiTests/CalendarFixture.cs | 8 +- .../ApiTests/DiskSpaceFixture.cs | 2 +- .../ApiTests/DownloadClientFixture.cs | 25 +- .../ApiTests/FileSystemFixture.cs | 18 +- .../ApiTests/HistoryFixture.cs | 2 +- .../ApiTests/NamingConfigFixture.cs | 2 - .../ApiTests/NotificationFixture.cs | 1 - .../ApiTests/ReleaseFixture.cs | 9 +- .../ApiTests/ReleasePushFixture.cs | 10 +- .../ApiTests/RootFolderFixture.cs | 4 +- .../ApiTests/TrackFixture.cs | 10 +- .../ApiTests/WantedFixture.cs | 27 +- .../Client/ArtistClient.cs | 1 - .../Client/ClientBase.cs | 13 +- .../Client/CommandClient.cs | 22 +- .../Client/LogsClient.cs | 2 +- src/NzbDrone.Integration.Test/CorsFixture.cs | 6 +- .../GenericApiFixture.cs | 3 - .../IndexHtmlFixture.cs | 3 +- .../IntegrationTest.cs | 2 +- .../IntegrationTestBase.cs | 41 +- .../DiskProviderTests/DiskProviderFixture.cs | 6 +- .../DiskProviderTests/FreeSpaceFixture.cs | 6 +- .../MonoPlatformInfoFixture.cs | 1 - .../MacOsVersionAdapterFixture.cs | 6 +- .../ReleaseFileVersionAdapterFixture.cs | 2 - src/NzbDrone.Mono/Disk/DiskProvider.cs | 15 +- .../Disk/LinuxPermissionsException.cs | 6 +- src/NzbDrone.Mono/Disk/ProcMount.cs | 1 - src/NzbDrone.Mono/Disk/ProcMountProvider.cs | 8 +- .../Disk/SymbolicLinkResolver.cs | 15 +- .../IssueFileVersionAdapter.cs | 5 +- .../VersionAdapters/MacOsVersionAdapter.cs | 15 +- .../ReleaseFileVersionAdapter.cs | 5 +- .../VersionAdapters/SynologyVersionAdapter.cs | 5 +- src/NzbDrone.SignalR/SignalRMessage.cs | 2 +- src/NzbDrone.Test.Common/AutoMoq/AutoMoqer.cs | 51 +- .../Unity/AutoMockingBuilderStrategy.cs | 8 +- .../Unity/AutoMockingContainerExtension.cs | 14 +- .../Categories/DiskAccessTestAttribute.cs | 3 +- .../Categories/IntegrationTestAttribute.cs | 3 +- .../Categories/ManualTestAttribute.cs | 3 +- .../ConcurrencyCounter.cs | 7 +- .../ExceptionVerification.cs | 11 +- src/NzbDrone.Test.Common/LoggingTest.cs | 4 +- src/NzbDrone.Test.Common/MockerExtensions.cs | 2 +- src/NzbDrone.Test.Common/NzbDroneRunner.cs | 7 +- src/NzbDrone.Test.Common/StringExtensions.cs | 3 +- src/NzbDrone.Test.Common/TestBase.cs | 23 +- src/NzbDrone.Test.Common/TestException.cs | 2 +- src/NzbDrone.Test.Dummy/DummyApp.cs | 2 +- .../InstallUpdateServiceFixture.cs | 2 +- src/NzbDrone.Update.Test/ProgramFixture.cs | 13 +- src/NzbDrone.Update/UpdateApp.cs | 4 +- src/NzbDrone.Update/UpdateContainerBuilder.cs | 2 - .../UpdateEngine/BackupAppData.cs | 1 - .../UpdateEngine/DetectApplicationType.cs | 2 +- .../UpdateEngine/InstallUpdateService.cs | 7 +- .../UpdateEngine/StartNzbDrone.cs | 1 - .../UpdateEngine/TerminateNzbDrone.cs | 2 +- .../DiskProviderTests/DiskProviderFixture.cs | 1 - .../DiskProviderTests/FreeSpaceFixture.cs | 2 + src/NzbDrone.Windows/Disk/DiskProvider.cs | 12 +- .../EnvironmentInfo/WindowsVersionInfo.cs | 2 +- src/NzbDrone/MessageBoxUserAlert.cs | 2 +- src/NzbDrone/SysTray/SysTrayApp.cs | 5 +- src/ServiceHelpers/ServiceInstall/Program.cs | 2 +- .../ServiceInstall/ServiceHelper.cs | 20 +- .../ServiceUninstall/Program.cs | 2 +- .../ServiceUninstall/ServiceHelper.cs | 20 +- src/Stylecop.ruleset | 115 ++++ src/stylecop.json | 21 + 1307 files changed, 8702 insertions(+), 7403 deletions(-) create mode 100644 src/Stylecop.ruleset create mode 100644 src/stylecop.json diff --git a/.editorconfig b/.editorconfig index 5e19cc2d6..624514a98 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 eeab2f98f..9626a75f0 100644 --- a/.gitignore +++ b/.gitignore @@ -84,7 +84,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 2808c082b..c283f0778 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -1,6 +1,7 @@ + $(SolutionDir)Stylecop.ruleset true AnyCPU @@ -92,6 +93,16 @@ + + + + + all + runtime; build; native; contentfiles; analyzers + + + + diff --git a/src/Lidarr.Api.V1/AlbumStudio/AlbumStudioModule.cs b/src/Lidarr.Api.V1/AlbumStudio/AlbumStudioModule.cs index 0be3cf3fc..6f55d4d1a 100644 --- a/src/Lidarr.Api.V1/AlbumStudio/AlbumStudioModule.cs +++ b/src/Lidarr.Api.V1/AlbumStudio/AlbumStudioModule.cs @@ -1,7 +1,7 @@ using System.Linq; +using Lidarr.Http.Extensions; using Nancy; using NzbDrone.Core.Music; -using Lidarr.Http.Extensions; namespace Lidarr.Api.V1.AlbumStudio { @@ -15,7 +15,7 @@ namespace Lidarr.Api.V1.AlbumStudio { _artistService = artistService; _albumMonitoredService = albumMonitoredService; - Post("/", artist => UpdateAll()); + Post("/", artist => UpdateAll()); } private object UpdateAll() diff --git a/src/Lidarr.Api.V1/Albums/AlbumLookupModule.cs b/src/Lidarr.Api.V1/Albums/AlbumLookupModule.cs index 2a2965aa3..46d489836 100644 --- a/src/Lidarr.Api.V1/Albums/AlbumLookupModule.cs +++ b/src/Lidarr.Api.V1/Albums/AlbumLookupModule.cs @@ -1,11 +1,9 @@ -using System; using System.Collections.Generic; using System.Linq; +using Lidarr.Http; using Nancy; using NzbDrone.Core.MediaCover; using NzbDrone.Core.MetadataSource; -using Lidarr.Http; -using Lidarr.Http.Extensions; namespace Lidarr.Api.V1.Albums { @@ -17,7 +15,7 @@ namespace Lidarr.Api.V1.Albums : base("/album/lookup") { _searchProxy = searchProxy; - Get("/", x => Search()); + Get("/", x => Search()); } private object Search() diff --git a/src/Lidarr.Api.V1/Albums/AlbumModule.cs b/src/Lidarr.Api.V1/Albums/AlbumModule.cs index 997c0d5ae..9fb2d9d70 100644 --- a/src/Lidarr.Api.V1/Albums/AlbumModule.cs +++ b/src/Lidarr.Api.V1/Albums/AlbumModule.cs @@ -1,23 +1,23 @@ using System; using System.Collections.Generic; using System.Linq; +using FluentValidation; +using Lidarr.Http.Extensions; using Nancy; +using NzbDrone.Common.Extensions; +using NzbDrone.Core.ArtistStats; using NzbDrone.Core.Datastore.Events; using NzbDrone.Core.DecisionEngine.Specifications; -using NzbDrone.Core.Music; -using NzbDrone.SignalR; -using Lidarr.Http.Extensions; -using NzbDrone.Core.ArtistStats; -using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Download; -using NzbDrone.Core.Music.Events; -using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.MediaCover; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Validation.Paths; -using FluentValidation; -using NzbDrone.Common.Extensions; +using NzbDrone.Core.MediaFiles.Events; +using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Music; +using NzbDrone.Core.Music.Events; using NzbDrone.Core.Validation; +using NzbDrone.Core.Validation.Paths; +using NzbDrone.SignalR; namespace Lidarr.Api.V1.Albums { @@ -28,7 +28,6 @@ namespace Lidarr.Api.V1.Albums IHandle, IHandle, IHandle - { protected readonly IReleaseService _releaseService; protected readonly IAddAlbumService _addAlbumService; @@ -52,7 +51,7 @@ namespace Lidarr.Api.V1.Albums CreateResource = AddAlbum; UpdateResource = UpdateAlbum; DeleteResource = DeleteAlbum; - Put("/monitor", x => SetAlbumsMonitored()); + Put("/monitor", x => SetAlbumsMonitored()); PostValidator.RuleFor(s => s.ForeignAlbumId).NotEmpty(); PostValidator.RuleFor(s => s.Artist.QualityProfileId).SetValidator(profileExistsValidator); @@ -156,7 +155,7 @@ namespace Lidarr.Api.V1.Albums BroadcastResourceChange(ModelAction.Updated, resource); } } - + public void Handle(AlbumEditedEvent message) { BroadcastResourceChange(ModelAction.Updated, MapToResource(message.Album, true)); @@ -184,7 +183,10 @@ namespace Lidarr.Api.V1.Albums public void Handle(TrackFileDeletedEvent message) { - if (message.Reason == DeleteMediaFileReason.Upgrade) return; + if (message.Reason == DeleteMediaFileReason.Upgrade) + { + return; + } BroadcastResourceChange(ModelAction.Updated, MapToResource(message.TrackFile.Album.Value, true)); } diff --git a/src/Lidarr.Api.V1/Albums/AlbumModuleWithSignalR.cs b/src/Lidarr.Api.V1/Albums/AlbumModuleWithSignalR.cs index 48f3721a7..fa6d98859 100644 --- a/src/Lidarr.Api.V1/Albums/AlbumModuleWithSignalR.cs +++ b/src/Lidarr.Api.V1/Albums/AlbumModuleWithSignalR.cs @@ -1,13 +1,13 @@ using System.Collections.Generic; using System.Linq; -using NzbDrone.Common.Extensions; using Lidarr.Api.V1.Artist; -using NzbDrone.Core.DecisionEngine.Specifications; -using NzbDrone.Core.Music; -using NzbDrone.Core.ArtistStats; -using NzbDrone.SignalR; using Lidarr.Http; +using NzbDrone.Common.Extensions; +using NzbDrone.Core.ArtistStats; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.MediaCover; +using NzbDrone.Core.Music; +using NzbDrone.SignalR; namespace Lidarr.Api.V1.Albums { @@ -90,7 +90,7 @@ namespace Lidarr.Api.V1.Albums resource.Artist = artist.ToResource(); } } - + var artistStats = _artistStatisticsService.ArtistStatistics(); LinkArtistStatistics(result, artistStats); MapCoversToLocal(result.ToArray()); @@ -119,7 +119,6 @@ namespace Lidarr.Api.V1.Albums var dictAlbumStats = artistStatistics.AlbumStatistics.ToDictionary(v => v.AlbumId); resource.Statistics = dictAlbumStats.GetValueOrDefault(resource.Id).ToResource(); - } } diff --git a/src/Lidarr.Api.V1/Albums/AlbumReleaseResource.cs b/src/Lidarr.Api.V1/Albums/AlbumReleaseResource.cs index df2b4f769..ce94efd5a 100644 --- a/src/Lidarr.Api.V1/Albums/AlbumReleaseResource.cs +++ b/src/Lidarr.Api.V1/Albums/AlbumReleaseResource.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using NzbDrone.Core.Music; @@ -27,6 +26,7 @@ namespace Lidarr.Api.V1.Albums return Media.Where(s => s.MediumNumber > 0).Count(); } } + public string Disambiguation { get; set; } public List Country { get; set; } public List Label { get; set; } @@ -62,7 +62,6 @@ namespace Lidarr.Api.V1.Albums .GroupBy(x => x.Format) .Select(g => MediaFormatHelper(g.Key, g.Count())) .ToList()) - }; } @@ -92,7 +91,7 @@ namespace Lidarr.Api.V1.Albums private static string MediaFormatHelper(string name, int count) { - return count == 1 ? name : string.Join("x", new List {count.ToString(), name}); + return count == 1 ? name : string.Join("x", new List { count.ToString(), name }); } public static List ToResource(this IEnumerable models) diff --git a/src/Lidarr.Api.V1/Albums/AlbumResource.cs b/src/Lidarr.Api.V1/Albums/AlbumResource.cs index 26b0c00f5..92ced5726 100644 --- a/src/Lidarr.Api.V1/Albums/AlbumResource.cs +++ b/src/Lidarr.Api.V1/Albums/AlbumResource.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; using System.Linq; -using Newtonsoft.Json; -using NzbDrone.Core.Music; using Lidarr.Api.V1.Artist; using Lidarr.Http.REST; +using Newtonsoft.Json; using NzbDrone.Core.MediaCover; +using NzbDrone.Core.Music; namespace Lidarr.Api.V1.Albums { @@ -34,6 +34,7 @@ namespace Lidarr.Api.V1.Albums return Media.Where(s => s.MediumNumber > 0).Count(); } } + public Ratings Ratings { get; set; } public DateTime? ReleaseDate { get; set; } public List Releases { get; set; } @@ -55,7 +56,10 @@ namespace Lidarr.Api.V1.Albums { public static AlbumResource ToResource(this Album model) { - if (model == null) return null; + if (model == null) + { + return null; + } var selectedRelease = model.AlbumReleases?.Value.Where(x => x.Monitored).SingleOrDefault(); @@ -86,7 +90,10 @@ namespace Lidarr.Api.V1.Albums public static Album ToModel(this AlbumResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } var artist = resource.Artist?.ToModel() ?? new NzbDrone.Core.Music.Artist(); diff --git a/src/Lidarr.Api.V1/Albums/AlbumStatisticsResource.cs b/src/Lidarr.Api.V1/Albums/AlbumStatisticsResource.cs index c87993444..a6173fabe 100644 --- a/src/Lidarr.Api.V1/Albums/AlbumStatisticsResource.cs +++ b/src/Lidarr.Api.V1/Albums/AlbumStatisticsResource.cs @@ -1,4 +1,3 @@ -using System; using NzbDrone.Core.ArtistStats; namespace Lidarr.Api.V1.Albums @@ -14,9 +13,12 @@ namespace Lidarr.Api.V1.Albums { get { - if (TrackCount == 0) return 0; + if (TrackCount == 0) + { + return 0; + } - return (decimal)TrackFileCount / (decimal)TrackCount * 100; + return TrackFileCount / (decimal)TrackCount * 100; } } } @@ -25,7 +27,10 @@ namespace Lidarr.Api.V1.Albums { public static AlbumStatisticsResource ToResource(this AlbumStatistics model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new AlbumStatisticsResource { diff --git a/src/Lidarr.Api.V1/Albums/AlbumsMonitoredResource.cs b/src/Lidarr.Api.V1/Albums/AlbumsMonitoredResource.cs index 8ccd7efea..bfefef856 100644 --- a/src/Lidarr.Api.V1/Albums/AlbumsMonitoredResource.cs +++ b/src/Lidarr.Api.V1/Albums/AlbumsMonitoredResource.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Lidarr.Api.V1.Albums diff --git a/src/Lidarr.Api.V1/Artist/ArtistEditorModule.cs b/src/Lidarr.Api.V1/Artist/ArtistEditorModule.cs index 8bb07c446..e20761675 100644 --- a/src/Lidarr.Api.V1/Artist/ArtistEditorModule.cs +++ b/src/Lidarr.Api.V1/Artist/ArtistEditorModule.cs @@ -1,11 +1,11 @@ using System.Collections.Generic; using System.Linq; +using Lidarr.Http.Extensions; using Nancy; using NzbDrone.Common.Extensions; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Music; using NzbDrone.Core.Music.Commands; -using Lidarr.Http.Extensions; namespace Lidarr.Api.V1.Artist { @@ -19,8 +19,8 @@ namespace Lidarr.Api.V1.Artist { _artistService = artistService; _commandQueueManager = commandQueueManager; - Put("/", artist => SaveAll()); - Delete("/", artist => DeleteArtist()); + Put("/", artist => SaveAll()); + Delete("/", artist => DeleteArtist()); } private object SaveAll() @@ -59,7 +59,6 @@ namespace Lidarr.Api.V1.Artist ArtistId = artist.Id, SourcePath = artist.Path }); - } if (resource.Tags != null) @@ -92,8 +91,8 @@ namespace Lidarr.Api.V1.Artist } return ResponseWithCode(_artistService.UpdateArtists(artistToUpdate, !resource.MoveFiles) - .ToResource() - , HttpStatusCode.Accepted); + .ToResource(), + HttpStatusCode.Accepted); } private object DeleteArtist() diff --git a/src/Lidarr.Api.V1/Artist/ArtistEditorResource.cs b/src/Lidarr.Api.V1/Artist/ArtistEditorResource.cs index cdeb7ec29..0aaa5ca84 100644 --- a/src/Lidarr.Api.V1/Artist/ArtistEditorResource.cs +++ b/src/Lidarr.Api.V1/Artist/ArtistEditorResource.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; -using NzbDrone.Core.Music; namespace Lidarr.Api.V1.Artist { diff --git a/src/Lidarr.Api.V1/Artist/ArtistImportModule.cs b/src/Lidarr.Api.V1/Artist/ArtistImportModule.cs index c444f7d67..b2a50a0a7 100644 --- a/src/Lidarr.Api.V1/Artist/ArtistImportModule.cs +++ b/src/Lidarr.Api.V1/Artist/ArtistImportModule.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; -using Nancy; -using NzbDrone.Core.Music; using Lidarr.Http; using Lidarr.Http.Extensions; +using Nancy; +using NzbDrone.Core.Music; namespace Lidarr.Api.V1.Artist { @@ -14,10 +14,9 @@ namespace Lidarr.Api.V1.Artist : base("/artist/import") { _addArtistService = addArtistService; - Post("/", x => Import()); + Post("/", x => Import()); } - private object Import() { var resource = Request.Body.FromJson>(); diff --git a/src/Lidarr.Api.V1/Artist/ArtistLookupModule.cs b/src/Lidarr.Api.V1/Artist/ArtistLookupModule.cs index 3c78a7502..d435bb983 100644 --- a/src/Lidarr.Api.V1/Artist/ArtistLookupModule.cs +++ b/src/Lidarr.Api.V1/Artist/ArtistLookupModule.cs @@ -1,10 +1,9 @@ using System.Collections.Generic; using System.Linq; +using Lidarr.Http; using Nancy; using NzbDrone.Core.MediaCover; using NzbDrone.Core.MetadataSource; -using Lidarr.Http; -using Lidarr.Http.Extensions; namespace Lidarr.Api.V1.Artist { @@ -16,7 +15,7 @@ namespace Lidarr.Api.V1.Artist : base("/artist/lookup") { _searchProxy = searchProxy; - Get("/", x => Search()); + Get("/", x => Search()); } private object Search() diff --git a/src/Lidarr.Api.V1/Artist/ArtistModule.cs b/src/Lidarr.Api.V1/Artist/ArtistModule.cs index 7dbfbfeeb..830d66262 100644 --- a/src/Lidarr.Api.V1/Artist/ArtistModule.cs +++ b/src/Lidarr.Api.V1/Artist/ArtistModule.cs @@ -1,38 +1,35 @@ -using System; using System.Collections.Generic; using System.Linq; using FluentValidation; +using Lidarr.Http; +using Lidarr.Http.Extensions; using NzbDrone.Common.Extensions; +using NzbDrone.Core.ArtistStats; using NzbDrone.Core.Datastore.Events; using NzbDrone.Core.MediaCover; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.RootFolders; -using NzbDrone.Core.ArtistStats; using NzbDrone.Core.Music; using NzbDrone.Core.Music.Commands; using NzbDrone.Core.Music.Events; +using NzbDrone.Core.RootFolders; using NzbDrone.Core.Validation; using NzbDrone.Core.Validation.Paths; -using Lidarr.Api.V1.Albums; using NzbDrone.SignalR; -using Lidarr.Http; -using Lidarr.Http.Extensions; namespace Lidarr.Api.V1.Artist { - public class ArtistModule : LidarrRestModuleWithSignalR, + public class ArtistModule : LidarrRestModuleWithSignalR, IHandle, IHandle, IHandle, - IHandle, - IHandle, + IHandle, + IHandle, IHandle, IHandle, IHandle - { private readonly IArtistService _artistService; private readonly IAlbumService _albumService; @@ -57,8 +54,7 @@ namespace Lidarr.Api.V1.Artist ArtistAncestorValidator artistAncestorValidator, SystemFolderValidator systemFolderValidator, ProfileExistsValidator profileExistsValidator, - MetadataProfileExistsValidator metadataProfileExistsValidator - ) + MetadataProfileExistsValidator metadataProfileExistsValidator) : base(signalRBroadcaster) { _artistService = artistService; @@ -108,12 +104,16 @@ namespace Lidarr.Api.V1.Artist private ArtistResource GetArtistResource(NzbDrone.Core.Music.Artist artist) { - if (artist == null) return null; + if (artist == null) + { + return null; + } var resource = artist.ToResource(); MapCoversToLocal(resource); FetchAndLinkArtistStatistics(resource); LinkNextPreviousAlbums(resource); + //PopulateAlternateTitles(resource); LinkRootFolderPath(resource); @@ -128,8 +128,8 @@ namespace Lidarr.Api.V1.Artist MapCoversToLocal(artistsResources.ToArray()); LinkNextPreviousAlbums(artistsResources.ToArray()); LinkArtistStatistics(artistsResources, artistStats); - //PopulateAlternateTitles(seriesResources); + //PopulateAlternateTitles(seriesResources); return artistsResources; } @@ -204,7 +204,10 @@ namespace Lidarr.Api.V1.Artist foreach (var artist in resources) { var stats = artistStatistics.SingleOrDefault(ss => ss.ArtistId == artist.Id); - if (stats == null) continue; + if (stats == null) + { + continue; + } LinkArtistStatistics(artist, stats); } @@ -231,7 +234,6 @@ namespace Lidarr.Api.V1.Artist // resource.AlternateTitles = mappings.Select(v => new AlternateTitleResource { Title = v.Title, SeasonNumber = v.SeasonNumber, SceneSeasonNumber = v.SceneSeasonNumber }).ToList(); //} - private void LinkRootFolderPath(ArtistResource resource) { resource.RootFolderPath = _rootFolderService.GetBestRootFolderPath(resource.Path); @@ -249,7 +251,10 @@ namespace Lidarr.Api.V1.Artist public void Handle(TrackFileDeletedEvent message) { - if (message.Reason == DeleteMediaFileReason.Upgrade) return; + if (message.Reason == DeleteMediaFileReason.Upgrade) + { + return; + } BroadcastResourceChange(ModelAction.Updated, GetArtistResource(message.TrackFile.Artist.Value)); } diff --git a/src/Lidarr.Api.V1/Artist/ArtistResource.cs b/src/Lidarr.Api.V1/Artist/ArtistResource.cs index 8b4981f20..d80ffd6b0 100644 --- a/src/Lidarr.Api.V1/Artist/ArtistResource.cs +++ b/src/Lidarr.Api.V1/Artist/ArtistResource.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; using System.Linq; +using Lidarr.Http.REST; +using Newtonsoft.Json; using NzbDrone.Common.Extensions; using NzbDrone.Core.MediaCover; using NzbDrone.Core.Music; -using Lidarr.Http.REST; -using Newtonsoft.Json; namespace Lidarr.Api.V1.Artist { @@ -14,7 +14,6 @@ namespace Lidarr.Api.V1.Artist //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 - [JsonIgnore] public int ArtistMetadataId { get; set; } public ArtistStatusType Status { get; set; } @@ -33,7 +32,7 @@ namespace Lidarr.Api.V1.Artist public string ArtistType { get; set; } public string Disambiguation { get; set; } public List Links { get; set; } - + public Album NextAlbum { get; set; } public Album LastAlbum { get; set; } @@ -42,7 +41,6 @@ namespace Lidarr.Api.V1.Artist public string RemotePoster { get; set; } - //View & Edit public string Path { get; set; } public int QualityProfileId { get; set; } @@ -68,7 +66,10 @@ namespace Lidarr.Api.V1.Artist { public static ArtistResource ToResource(this NzbDrone.Core.Music.Artist model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ArtistResource { @@ -76,6 +77,7 @@ namespace Lidarr.Api.V1.Artist ArtistMetadataId = model.ArtistMetadataId, ArtistName = model.Name, + //AlternateTitles SortName = model.SortName, @@ -98,6 +100,7 @@ namespace Lidarr.Api.V1.Artist CleanName = model.CleanName, ForeignArtistId = model.Metadata.Value.ForeignArtistId, + // Root folder path is now calculated from the artist path // RootFolderPath = model.RootFolderPath, Genres = model.Metadata.Value.Genres, @@ -112,7 +115,10 @@ namespace Lidarr.Api.V1.Artist public static NzbDrone.Core.Music.Artist ToModel(this ArtistResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new NzbDrone.Core.Music.Artist { @@ -130,14 +136,13 @@ namespace Lidarr.Api.V1.Artist Ratings = resource.Ratings, Type = resource.ArtistType }, - + //AlternateTitles SortName = resource.SortName, Path = resource.Path, QualityProfileId = resource.QualityProfileId, MetadataProfileId = resource.MetadataProfileId, - AlbumFolder = resource.AlbumFolder, Monitored = resource.Monitored, @@ -148,7 +153,6 @@ namespace Lidarr.Api.V1.Artist Tags = resource.Tags, Added = resource.Added, AddOptions = resource.AddOptions, - }; } diff --git a/src/Lidarr.Api.V1/Artist/ArtistStatisticsResource.cs b/src/Lidarr.Api.V1/Artist/ArtistStatisticsResource.cs index 6759ff839..b514f1d29 100644 --- a/src/Lidarr.Api.V1/Artist/ArtistStatisticsResource.cs +++ b/src/Lidarr.Api.V1/Artist/ArtistStatisticsResource.cs @@ -1,4 +1,3 @@ -using System; using NzbDrone.Core.ArtistStats; namespace Lidarr.Api.V1.Artist @@ -15,9 +14,12 @@ namespace Lidarr.Api.V1.Artist { get { - if (TrackCount == 0) return 0; + if (TrackCount == 0) + { + return 0; + } - return (decimal)TrackFileCount / (decimal)TrackCount * 100; + return TrackFileCount / (decimal)TrackCount * 100; } } } @@ -26,7 +28,10 @@ namespace Lidarr.Api.V1.Artist { public static ArtistStatisticsResource ToResource(this ArtistStatistics model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ArtistStatisticsResource { diff --git a/src/Lidarr.Api.V1/Blacklist/BlacklistModule.cs b/src/Lidarr.Api.V1/Blacklist/BlacklistModule.cs index 358c72b36..8df232b72 100644 --- a/src/Lidarr.Api.V1/Blacklist/BlacklistModule.cs +++ b/src/Lidarr.Api.V1/Blacklist/BlacklistModule.cs @@ -1,6 +1,6 @@ +using Lidarr.Http; using NzbDrone.Core.Blacklisting; using NzbDrone.Core.Datastore; -using Lidarr.Http; namespace Lidarr.Api.V1.Blacklist { diff --git a/src/Lidarr.Api.V1/Blacklist/BlacklistResource.cs b/src/Lidarr.Api.V1/Blacklist/BlacklistResource.cs index e01254c63..ecf780313 100644 --- a/src/Lidarr.Api.V1/Blacklist/BlacklistResource.cs +++ b/src/Lidarr.Api.V1/Blacklist/BlacklistResource.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; -using NzbDrone.Core.Indexers; -using NzbDrone.Core.Qualities; using Lidarr.Api.V1.Artist; using Lidarr.Http.REST; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.Qualities; namespace Lidarr.Api.V1.Blacklist { @@ -25,7 +25,10 @@ namespace Lidarr.Api.V1.Blacklist { 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/Lidarr.Api.V1/Calendar/CalendarFeedModule.cs b/src/Lidarr.Api.V1/Calendar/CalendarFeedModule.cs index f9fb21a2d..3ee421434 100644 --- a/src/Lidarr.Api.V1/Calendar/CalendarFeedModule.cs +++ b/src/Lidarr.Api.V1/Calendar/CalendarFeedModule.cs @@ -2,15 +2,15 @@ using System; using System.Collections.Generic; using System.Linq; using Ical.Net; +using Ical.Net.CalendarComponents; using Ical.Net.DataTypes; using Ical.Net.Serialization; +using Lidarr.Http.Extensions; using Nancy; using Nancy.Responses; using NzbDrone.Common.Extensions; -using NzbDrone.Core.Tags; using NzbDrone.Core.Music; -using Lidarr.Http.Extensions; -using Ical.Net.CalendarComponents; +using NzbDrone.Core.Tags; namespace Lidarr.Api.V1.Calendar { @@ -27,13 +27,13 @@ namespace Lidarr.Api.V1.Calendar _artistService = artistService; _tagService = tagService; - Get("/Lidarr.ics", options => GetCalendarFeed()); + Get("/Lidarr.ics", options => GetCalendarFeed()); } private object GetCalendarFeed() { var pastDays = 7; - var futureDays = 28; + var futureDays = 28; var start = DateTime.Today.AddDays(-pastDays); var end = DateTime.Today.AddDays(futureDays); var unmonitored = Request.GetBooleanQueryParameter("unmonitored"); @@ -82,6 +82,7 @@ namespace Lidarr.Api.V1.Calendar var occurrence = calendar.Create(); occurrence.Uid = "Lidarr_album_" + album.Id; + //occurrence.Status = album.HasFile ? EventStatus.Confirmed : EventStatus.Tentative; occurrence.Description = album.Overview; occurrence.Categories = album.Genres; diff --git a/src/Lidarr.Api.V1/Calendar/CalendarModule.cs b/src/Lidarr.Api.V1/Calendar/CalendarModule.cs index cea1a7589..410e38e82 100644 --- a/src/Lidarr.Api.V1/Calendar/CalendarModule.cs +++ b/src/Lidarr.Api.V1/Calendar/CalendarModule.cs @@ -1,13 +1,13 @@ using System; using System.Collections.Generic; using System.Linq; -using NzbDrone.Core.DecisionEngine.Specifications; -using NzbDrone.Core.Music; -using NzbDrone.Core.ArtistStats; -using NzbDrone.SignalR; using Lidarr.Api.V1.Albums; using Lidarr.Http.Extensions; +using NzbDrone.Core.ArtistStats; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.MediaCover; +using NzbDrone.Core.Music; +using NzbDrone.SignalR; namespace Lidarr.Api.V1.Calendar { @@ -36,8 +36,15 @@ namespace Lidarr.Api.V1.Calendar var queryStart = Request.Query.Start; var queryEnd = Request.Query.End; - 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); + } var resources = MapToResource(_albumService.AlbumsBetweenDates(start, end, includeUnmonitored), includeArtist); diff --git a/src/Lidarr.Api.V1/Commands/CommandModule.cs b/src/Lidarr.Api.V1/Commands/CommandModule.cs index 22c794332..bd7401f8b 100644 --- a/src/Lidarr.Api.V1/Commands/CommandModule.cs +++ b/src/Lidarr.Api.V1/Commands/CommandModule.cs @@ -1,6 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; +using Lidarr.Http; +using Lidarr.Http.Extensions; +using Lidarr.Http.Validation; using NzbDrone.Common; using NzbDrone.Common.TPL; using NzbDrone.Core.Datastore.Events; @@ -8,9 +11,6 @@ using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.ProgressMessaging; using NzbDrone.SignalR; -using Lidarr.Http; -using Lidarr.Http.Extensions; -using Lidarr.Http.Validation; namespace Lidarr.Api.V1.Commands { @@ -48,7 +48,7 @@ namespace Lidarr.Api.V1.Commands 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/Lidarr.Api.V1/Commands/CommandResource.cs b/src/Lidarr.Api.V1/Commands/CommandResource.cs index dff2bf782..c56c56d4c 100644 --- a/src/Lidarr.Api.V1/Commands/CommandResource.cs +++ b/src/Lidarr.Api.V1/Commands/CommandResource.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; +using Lidarr.Http.REST; using Newtonsoft.Json; using NzbDrone.Common.Extensions; using NzbDrone.Core.Messaging.Commands; -using Lidarr.Http.REST; namespace Lidarr.Api.V1.Commands { @@ -30,37 +30,51 @@ namespace Lidarr.Api.V1.Commands { 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 @@ namespace Lidarr.Api.V1.Commands { public static CommandResource ToResource(this CommandModel model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new CommandResource { diff --git a/src/Lidarr.Api.V1/Config/DownloadClientConfigResource.cs b/src/Lidarr.Api.V1/Config/DownloadClientConfigResource.cs index 50bdaefc9..9af1c0a6f 100644 --- a/src/Lidarr.Api.V1/Config/DownloadClientConfigResource.cs +++ b/src/Lidarr.Api.V1/Config/DownloadClientConfigResource.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Configuration; -using Lidarr.Http.REST; +using Lidarr.Http.REST; +using NzbDrone.Core.Configuration; namespace Lidarr.Api.V1.Config { diff --git a/src/Lidarr.Api.V1/Config/HostConfigModule.cs b/src/Lidarr.Api.V1/Config/HostConfigModule.cs index 84855faa4..494ebaf13 100644 --- a/src/Lidarr.Api.V1/Config/HostConfigModule.cs +++ b/src/Lidarr.Api.V1/Config/HostConfigModule.cs @@ -2,13 +2,13 @@ using System.IO; using System.Linq; using System.Reflection; using FluentValidation; +using Lidarr.Http; using NzbDrone.Common.Extensions; using NzbDrone.Core.Authentication; using NzbDrone.Core.Configuration; using NzbDrone.Core.Update; using NzbDrone.Core.Validation; using NzbDrone.Core.Validation.Paths; -using Lidarr.Http; namespace Lidarr.Api.V1.Config { @@ -51,7 +51,6 @@ namespace Lidarr.Api.V1.Config 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/Lidarr.Api.V1/Config/HostConfigResource.cs b/src/Lidarr.Api.V1/Config/HostConfigResource.cs index 1b330bbc7..b6f022976 100644 --- a/src/Lidarr.Api.V1/Config/HostConfigResource.cs +++ b/src/Lidarr.Api.V1/Config/HostConfigResource.cs @@ -1,9 +1,9 @@ +using Lidarr.Http.REST; using NzbDrone.Common.Http.Proxy; using NzbDrone.Core.Authentication; using NzbDrone.Core.Configuration; using NzbDrone.Core.Security; using NzbDrone.Core.Update; -using Lidarr.Http.REST; namespace Lidarr.Api.V1.Config { @@ -56,6 +56,7 @@ namespace Lidarr.Api.V1.Config LaunchBrowser = model.LaunchBrowser, AuthenticationMethod = model.AuthenticationMethod, AnalyticsEnabled = model.AnalyticsEnabled, + //Username //Password LogLevel = model.LogLevel, diff --git a/src/Lidarr.Api.V1/Config/IndexerConfigModule.cs b/src/Lidarr.Api.V1/Config/IndexerConfigModule.cs index 5b21994fb..7b0ed8d97 100644 --- a/src/Lidarr.Api.V1/Config/IndexerConfigModule.cs +++ b/src/Lidarr.Api.V1/Config/IndexerConfigModule.cs @@ -1,12 +1,11 @@ using FluentValidation; -using NzbDrone.Core.Configuration; using Lidarr.Http.Validation; +using NzbDrone.Core.Configuration; namespace Lidarr.Api.V1.Config { public class IndexerConfigModule : LidarrConfigModule { - public IndexerConfigModule(IConfigService configService) : base(configService) { diff --git a/src/Lidarr.Api.V1/Config/IndexerConfigResource.cs b/src/Lidarr.Api.V1/Config/IndexerConfigResource.cs index f354dac64..5a5c5035f 100644 --- a/src/Lidarr.Api.V1/Config/IndexerConfigResource.cs +++ b/src/Lidarr.Api.V1/Config/IndexerConfigResource.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Configuration; using Lidarr.Http.REST; +using NzbDrone.Core.Configuration; namespace Lidarr.Api.V1.Config { diff --git a/src/Lidarr.Api.V1/Config/LidarrConfigModule.cs b/src/Lidarr.Api.V1/Config/LidarrConfigModule.cs index 220b96198..cf2798215 100644 --- a/src/Lidarr.Api.V1/Config/LidarrConfigModule.cs +++ b/src/Lidarr.Api.V1/Config/LidarrConfigModule.cs @@ -1,12 +1,13 @@ using System.Linq; using System.Reflection; -using NzbDrone.Core.Configuration; using Lidarr.Http; using Lidarr.Http.REST; +using NzbDrone.Core.Configuration; namespace Lidarr.Api.V1.Config { - public abstract class LidarrConfigModule : LidarrRestModule where TResource : RestResource, new() + public abstract class LidarrConfigModule : LidarrRestModule + where TResource : RestResource, new() { private readonly IConfigService _configService; @@ -15,8 +16,8 @@ namespace Lidarr.Api.V1.Config { } - protected LidarrConfigModule(string resource, IConfigService configService) : - base("config/" + resource.Trim('/')) + protected LidarrConfigModule(string resource, IConfigService configService) + : base("config/" + resource.Trim('/')) { _configService = configService; diff --git a/src/Lidarr.Api.V1/Config/MediaManagementConfigModule.cs b/src/Lidarr.Api.V1/Config/MediaManagementConfigModule.cs index 1fc30163b..e9730ad57 100644 --- a/src/Lidarr.Api.V1/Config/MediaManagementConfigModule.cs +++ b/src/Lidarr.Api.V1/Config/MediaManagementConfigModule.cs @@ -21,4 +21,4 @@ namespace Lidarr.Api.V1.Config return MediaManagementConfigResourceMapper.ToResource(model); } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Api.V1/Config/MediaManagementConfigResource.cs b/src/Lidarr.Api.V1/Config/MediaManagementConfigResource.cs index f4ef5574e..9c2a516e2 100644 --- a/src/Lidarr.Api.V1/Config/MediaManagementConfigResource.cs +++ b/src/Lidarr.Api.V1/Config/MediaManagementConfigResource.cs @@ -1,6 +1,6 @@ +using Lidarr.Http.REST; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles; -using Lidarr.Http.REST; using NzbDrone.Core.Qualities; namespace Lidarr.Api.V1.Config diff --git a/src/Lidarr.Api.V1/Config/MetadataProviderConfigModule.cs b/src/Lidarr.Api.V1/Config/MetadataProviderConfigModule.cs index 5286c87c5..e4c0db6d2 100644 --- a/src/Lidarr.Api.V1/Config/MetadataProviderConfigModule.cs +++ b/src/Lidarr.Api.V1/Config/MetadataProviderConfigModule.cs @@ -1,10 +1,6 @@ -using System; -using System.Linq; -using System.Reflection; using FluentValidation; -using NzbDrone.Core.Configuration; -using Lidarr.Http; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Configuration; using NzbDrone.Core.Validation; namespace Lidarr.Api.V1.Config diff --git a/src/Lidarr.Api.V1/Config/MetadataProviderConfigResource.cs b/src/Lidarr.Api.V1/Config/MetadataProviderConfigResource.cs index 3e356eedb..8d29a2356 100644 --- a/src/Lidarr.Api.V1/Config/MetadataProviderConfigResource.cs +++ b/src/Lidarr.Api.V1/Config/MetadataProviderConfigResource.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Configuration; using Lidarr.Http.REST; +using NzbDrone.Core.Configuration; namespace Lidarr.Api.V1.Config { diff --git a/src/Lidarr.Api.V1/Config/NamingConfigModule.cs b/src/Lidarr.Api.V1/Config/NamingConfigModule.cs index 1861e470c..79ea6e4fc 100644 --- a/src/Lidarr.Api.V1/Config/NamingConfigModule.cs +++ b/src/Lidarr.Api.V1/Config/NamingConfigModule.cs @@ -2,13 +2,10 @@ using System.Collections.Generic; using System.Linq; using FluentValidation; using FluentValidation.Results; +using Lidarr.Http; using Nancy.ModelBinding; -using Nancy.Responses; using NzbDrone.Common.Extensions; using NzbDrone.Core.Organizer; -using Lidarr.Http; -using Lidarr.Http.Extensions; -using Lidarr.Http.Mapping; namespace Lidarr.Api.V1.Config { @@ -33,8 +30,7 @@ namespace Lidarr.Api.V1.Config GetResourceById = GetNamingConfig; UpdateResource = UpdateNamingConfig; - Get("/examples", x => GetExamples(this.Bind())); - + Get("/examples", x => GetExamples(this.Bind())); SharedValidator.RuleFor(c => c.StandardTrackFormat).ValidTrackFormat(); SharedValidator.RuleFor(c => c.MultiDiscTrackFormat).ValidTrackFormat(); @@ -84,7 +80,7 @@ namespace Lidarr.Api.V1.Config var nameSpec = config.ToModel(); var sampleResource = new NamingExampleResource(); - + var singleTrackSampleResult = _filenameSampleService.GetStandardTrackSample(nameSpec); var multiDiscTrackSampleResult = _filenameSampleService.GetMultiDiscTrackSample(nameSpec); diff --git a/src/Lidarr.Api.V1/Config/UiConfigModule.cs b/src/Lidarr.Api.V1/Config/UiConfigModule.cs index 4e7910974..f25ba424d 100644 --- a/src/Lidarr.Api.V1/Config/UiConfigModule.cs +++ b/src/Lidarr.Api.V1/Config/UiConfigModule.cs @@ -1,7 +1,4 @@ -using System.Linq; -using System.Reflection; -using NzbDrone.Core.Configuration; -using Lidarr.Http; +using NzbDrone.Core.Configuration; namespace Lidarr.Api.V1.Config { @@ -10,7 +7,6 @@ namespace Lidarr.Api.V1.Config public UiConfigModule(IConfigService configService) : base(configService) { - } protected override UiConfigResource ToResource(IConfigService model) @@ -18,4 +14,4 @@ namespace Lidarr.Api.V1.Config return UiConfigResourceMapper.ToResource(model); } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Api.V1/Config/UiConfigResource.cs b/src/Lidarr.Api.V1/Config/UiConfigResource.cs index e04ab7c6a..4593a94cc 100644 --- a/src/Lidarr.Api.V1/Config/UiConfigResource.cs +++ b/src/Lidarr.Api.V1/Config/UiConfigResource.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Configuration; -using Lidarr.Http.REST; +using Lidarr.Http.REST; +using NzbDrone.Core.Configuration; namespace Lidarr.Api.V1.Config { diff --git a/src/Lidarr.Api.V1/CustomFilters/CustomFilterModule.cs b/src/Lidarr.Api.V1/CustomFilters/CustomFilterModule.cs index 9620ef48b..a483b8d9c 100644 --- a/src/Lidarr.Api.V1/CustomFilters/CustomFilterModule.cs +++ b/src/Lidarr.Api.V1/CustomFilters/CustomFilterModule.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -using NzbDrone.Core.CustomFilters; using Lidarr.Http; +using NzbDrone.Core.CustomFilters; namespace Lidarr.Api.V1.CustomFilters { diff --git a/src/Lidarr.Api.V1/CustomFilters/CustomFilterResource.cs b/src/Lidarr.Api.V1/CustomFilters/CustomFilterResource.cs index ee3cc9ea0..6f5dfaf0e 100644 --- a/src/Lidarr.Api.V1/CustomFilters/CustomFilterResource.cs +++ b/src/Lidarr.Api.V1/CustomFilters/CustomFilterResource.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; +using Lidarr.Http.REST; using NzbDrone.Common.Serializer; using NzbDrone.Core.CustomFilters; -using Lidarr.Http.REST; namespace Lidarr.Api.V1.CustomFilters { @@ -17,28 +17,34 @@ namespace Lidarr.Api.V1.CustomFilters { 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>(model.Filters) - }; + { + Id = model.Id, + Type = model.Type, + Label = model.Label, + Filters = Json.Deserialize>(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 ToResource(this IEnumerable filters) diff --git a/src/Lidarr.Api.V1/DiskSpace/DiskSpaceModule.cs b/src/Lidarr.Api.V1/DiskSpace/DiskSpaceModule.cs index 7d57cefd1..50a7539d4 100644 --- a/src/Lidarr.Api.V1/DiskSpace/DiskSpaceModule.cs +++ b/src/Lidarr.Api.V1/DiskSpace/DiskSpaceModule.cs @@ -1,15 +1,15 @@ using System.Collections.Generic; -using NzbDrone.Core.DiskSpace; using Lidarr.Http; +using NzbDrone.Core.DiskSpace; namespace Lidarr.Api.V1.DiskSpace { - public class DiskSpaceModule :LidarrRestModule + public class DiskSpaceModule : LidarrRestModule { private readonly IDiskSpaceService _diskSpaceService; public DiskSpaceModule(IDiskSpaceService diskSpaceService) - :base("diskspace") + : base("diskspace") { _diskSpaceService = diskSpaceService; GetResourceAll = GetFreeSpace; diff --git a/src/Lidarr.Api.V1/DiskSpace/DiskSpaceResource.cs b/src/Lidarr.Api.V1/DiskSpace/DiskSpaceResource.cs index 9adcfaf50..a668f37a8 100644 --- a/src/Lidarr.Api.V1/DiskSpace/DiskSpaceResource.cs +++ b/src/Lidarr.Api.V1/DiskSpace/DiskSpaceResource.cs @@ -14,7 +14,10 @@ namespace Lidarr.Api.V1.DiskSpace { 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/Lidarr.Api.V1/DownloadClient/DownloadClientModule.cs b/src/Lidarr.Api.V1/DownloadClient/DownloadClientModule.cs index 789932dfd..e251e124b 100644 --- a/src/Lidarr.Api.V1/DownloadClient/DownloadClientModule.cs +++ b/src/Lidarr.Api.V1/DownloadClient/DownloadClientModule.cs @@ -13,8 +13,12 @@ namespace Lidarr.Api.V1.DownloadClient protected override void Validate(DownloadClientDefinition definition, bool includeWarnings) { - if (!definition.Enable) return; + if (!definition.Enable) + { + return; + } + base.Validate(definition, includeWarnings); } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Api.V1/DownloadClient/DownloadClientResource.cs b/src/Lidarr.Api.V1/DownloadClient/DownloadClientResource.cs index aa2d79a49..b1514e956 100644 --- a/src/Lidarr.Api.V1/DownloadClient/DownloadClientResource.cs +++ b/src/Lidarr.Api.V1/DownloadClient/DownloadClientResource.cs @@ -14,7 +14,10 @@ namespace Lidarr.Api.V1.DownloadClient { 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 @@ namespace Lidarr.Api.V1.DownloadClient public override DownloadClientDefinition ToModel(DownloadClientResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } var definition = base.ToModel(resource); @@ -38,4 +44,4 @@ namespace Lidarr.Api.V1.DownloadClient return definition; } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Api.V1/FileSystem/FileSystemModule.cs b/src/Lidarr.Api.V1/FileSystem/FileSystemModule.cs index 748f2dad6..67da221d6 100644 --- a/src/Lidarr.Api.V1/FileSystem/FileSystemModule.cs +++ b/src/Lidarr.Api.V1/FileSystem/FileSystemModule.cs @@ -1,12 +1,9 @@ -using System; -using System.IO; -using System.IO.Abstractions; using System.Linq; +using Lidarr.Http.Extensions; using Nancy; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Core.MediaFiles; -using Lidarr.Http.Extensions; namespace Lidarr.Api.V1.FileSystem { @@ -24,9 +21,9 @@ namespace Lidarr.Api.V1.FileSystem _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() @@ -62,7 +59,8 @@ namespace Lidarr.Api.V1.FileSystem return new string[0]; } - return _diskScanService.GetAudioFiles(path).Select(f => new { + return _diskScanService.GetAudioFiles(path).Select(f => new + { Path = f.FullName, RelativePath = path.GetRelativePath(f.FullName), Name = f.Name diff --git a/src/Lidarr.Api.V1/Health/HealthModule.cs b/src/Lidarr.Api.V1/Health/HealthModule.cs index 6fa7f2efd..e75058004 100644 --- a/src/Lidarr.Api.V1/Health/HealthModule.cs +++ b/src/Lidarr.Api.V1/Health/HealthModule.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; +using Lidarr.Http; using NzbDrone.Core.Datastore.Events; using NzbDrone.Core.HealthCheck; using NzbDrone.Core.Messaging.Events; using NzbDrone.SignalR; -using Lidarr.Http; namespace Lidarr.Api.V1.Health { @@ -29,4 +29,4 @@ namespace Lidarr.Api.V1.Health BroadcastResourceChange(ModelAction.Sync); } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Api.V1/Health/HealthResource.cs b/src/Lidarr.Api.V1/Health/HealthResource.cs index b7f176630..9de525009 100644 --- a/src/Lidarr.Api.V1/Health/HealthResource.cs +++ b/src/Lidarr.Api.V1/Health/HealthResource.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; +using Lidarr.Http.REST; using NzbDrone.Common.Http; using NzbDrone.Core.HealthCheck; -using Lidarr.Http.REST; namespace Lidarr.Api.V1.Health { @@ -18,7 +18,10 @@ namespace Lidarr.Api.V1.Health { public static HealthResource ToResource(this HealthCheck model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new HealthResource { diff --git a/src/Lidarr.Api.V1/History/HistoryModule.cs b/src/Lidarr.Api.V1/History/HistoryModule.cs index b8452266f..6ec0e31cf 100644 --- a/src/Lidarr.Api.V1/History/HistoryModule.cs +++ b/src/Lidarr.Api.V1/History/HistoryModule.cs @@ -1,17 +1,17 @@ using System; using System.Collections.Generic; using System.Linq; -using Nancy; -using NzbDrone.Core.Datastore; -using NzbDrone.Core.DecisionEngine.Specifications; -using NzbDrone.Core.Download; -using NzbDrone.Core.History; using Lidarr.Api.V1.Albums; using Lidarr.Api.V1.Artist; using Lidarr.Api.V1.Tracks; using Lidarr.Http; using Lidarr.Http.Extensions; using Lidarr.Http.REST; +using Nancy; +using NzbDrone.Core.Datastore; +using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.Download; +using NzbDrone.Core.History; namespace Lidarr.Api.V1.History { @@ -30,9 +30,9 @@ namespace Lidarr.Api.V1.History _failedDownloadService = failedDownloadService; GetResourcePaged = GetHistory; - Get("/since", x => GetHistorySince()); - Get("/artist", x => GetArtistHistory()); - Post("/failed", x => MarkAsFailed()); + Get("/since", x => GetHistorySince()); + Get("/artist", x => GetArtistHistory()); + Post("/failed", x => MarkAsFailed()); } protected HistoryResource MapToResource(NzbDrone.Core.History.History model, bool includeArtist, bool includeAlbum, bool includeTrack) @@ -43,15 +43,16 @@ namespace Lidarr.Api.V1.History { resource.Artist = model.Artist.ToResource(); } + if (includeAlbum) { resource.Album = model.Album.ToResource(); } + if (includeTrack) { resource.Track = model.Track.ToResource(); } - if (model.Artist != null) { @@ -90,7 +91,6 @@ namespace Lidarr.Api.V1.History pagingSpec.FilterExpressions.Add(h => h.DownloadId == downloadId); } - return ApplyToPage(_historyService.Paged, pagingSpec, h => MapToResource(h, includeArtist, includeAlbum, includeTrack)); } diff --git a/src/Lidarr.Api.V1/History/HistoryResource.cs b/src/Lidarr.Api.V1/History/HistoryResource.cs index 398230864..6f450ebdb 100644 --- a/src/Lidarr.Api.V1/History/HistoryResource.cs +++ b/src/Lidarr.Api.V1/History/HistoryResource.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; -using NzbDrone.Core.History; -using NzbDrone.Core.Qualities; using Lidarr.Api.V1.Albums; using Lidarr.Api.V1.Artist; using Lidarr.Api.V1.Tracks; using Lidarr.Http.REST; +using NzbDrone.Core.History; +using NzbDrone.Core.Qualities; namespace Lidarr.Api.V1.History { @@ -33,7 +33,10 @@ namespace Lidarr.Api.V1.History { public static HistoryResource ToResource(this NzbDrone.Core.History.History model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new HistoryResource { @@ -44,6 +47,7 @@ namespace Lidarr.Api.V1.History TrackId = model.TrackId, SourceTitle = model.SourceTitle, Quality = model.Quality, + //QualityCutoffNotMet Date = model.Date, DownloadId = model.DownloadId, @@ -51,6 +55,7 @@ namespace Lidarr.Api.V1.History EventType = model.EventType, Data = model.Data + //Episode //Series }; diff --git a/src/Lidarr.Api.V1/ImportLists/ImportListExclusionModule.cs b/src/Lidarr.Api.V1/ImportLists/ImportListExclusionModule.cs index c5fdd0bbe..51ea2307d 100644 --- a/src/Lidarr.Api.V1/ImportLists/ImportListExclusionModule.cs +++ b/src/Lidarr.Api.V1/ImportLists/ImportListExclusionModule.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; -using NzbDrone.Core.ImportLists.Exclusions; -using Lidarr.Http; using FluentValidation; +using Lidarr.Http; +using NzbDrone.Core.ImportLists.Exclusions; using NzbDrone.Core.Validation; namespace Lidarr.Api.V1.ImportLists diff --git a/src/Lidarr.Api.V1/ImportLists/ImportListExclusionResource.cs b/src/Lidarr.Api.V1/ImportLists/ImportListExclusionResource.cs index 91d7f52d3..43d9d409e 100644 --- a/src/Lidarr.Api.V1/ImportLists/ImportListExclusionResource.cs +++ b/src/Lidarr.Api.V1/ImportLists/ImportListExclusionResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using NzbDrone.Core.ImportLists.Exclusions; using Lidarr.Http.REST; +using NzbDrone.Core.ImportLists.Exclusions; namespace Lidarr.Api.V1.ImportLists { @@ -15,7 +15,10 @@ namespace Lidarr.Api.V1.ImportLists { public static ImportListExclusionResource ToResource(this ImportListExclusion model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ImportListExclusionResource { @@ -27,7 +30,10 @@ namespace Lidarr.Api.V1.ImportLists public static ImportListExclusion ToModel(this ImportListExclusionResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new ImportListExclusion { diff --git a/src/Lidarr.Api.V1/ImportLists/ImportListModule.cs b/src/Lidarr.Api.V1/ImportLists/ImportListModule.cs index b3d3965e8..4cb75fbae 100644 --- a/src/Lidarr.Api.V1/ImportLists/ImportListModule.cs +++ b/src/Lidarr.Api.V1/ImportLists/ImportListModule.cs @@ -10,8 +10,7 @@ namespace Lidarr.Api.V1.ImportLists public ImportListModule(ImportListFactory importListFactory, ProfileExistsValidator profileExistsValidator, - MetadataProfileExistsValidator metadataProfileExistsValidator - ) + MetadataProfileExistsValidator metadataProfileExistsValidator) : base(importListFactory, "importlist", ResourceMapper) { Http.Validation.RuleBuilderExtensions.ValidId(SharedValidator.RuleFor(s => s.QualityProfileId)); @@ -28,6 +27,7 @@ namespace Lidarr.Api.V1.ImportLists { return; } + base.Validate(definition, includeWarnings); } } diff --git a/src/Lidarr.Api.V1/ImportLists/ImportListResource.cs b/src/Lidarr.Api.V1/ImportLists/ImportListResource.cs index d23551e18..dedc5e706 100644 --- a/src/Lidarr.Api.V1/ImportLists/ImportListResource.cs +++ b/src/Lidarr.Api.V1/ImportLists/ImportListResource.cs @@ -23,14 +23,14 @@ namespace Lidarr.Api.V1.ImportLists } var resource = base.ToResource(definition); - + resource.EnableAutomaticAdd = definition.EnableAutomaticAdd; resource.ShouldMonitor = definition.ShouldMonitor; resource.RootFolderPath = definition.RootFolderPath; resource.QualityProfileId = definition.ProfileId; resource.MetadataProfileId = definition.MetadataProfileId; resource.ListType = definition.ListType; - resource.ListOrder = (int) definition.ListType; + resource.ListOrder = (int)definition.ListType; return resource; } @@ -43,7 +43,7 @@ namespace Lidarr.Api.V1.ImportLists } var definition = base.ToModel(resource); - + definition.EnableAutomaticAdd = resource.EnableAutomaticAdd; definition.ShouldMonitor = resource.ShouldMonitor; definition.RootFolderPath = resource.RootFolderPath; diff --git a/src/Lidarr.Api.V1/Indexers/IndexerModule.cs b/src/Lidarr.Api.V1/Indexers/IndexerModule.cs index 9156f03c0..5fb1168e9 100644 --- a/src/Lidarr.Api.V1/Indexers/IndexerModule.cs +++ b/src/Lidarr.Api.V1/Indexers/IndexerModule.cs @@ -13,8 +13,12 @@ namespace Lidarr.Api.V1.Indexers protected override void Validate(IndexerDefinition definition, bool includeWarnings) { - if (!definition.Enable) return; + if (!definition.Enable) + { + return; + } + base.Validate(definition, includeWarnings); } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Api.V1/Indexers/IndexerResource.cs b/src/Lidarr.Api.V1/Indexers/IndexerResource.cs index 2b63db913..b87ecfaf6 100644 --- a/src/Lidarr.Api.V1/Indexers/IndexerResource.cs +++ b/src/Lidarr.Api.V1/Indexers/IndexerResource.cs @@ -16,7 +16,10 @@ namespace Lidarr.Api.V1.Indexers { 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 @@ namespace Lidarr.Api.V1.Indexers 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/Lidarr.Api.V1/Indexers/ReleaseModule.cs b/src/Lidarr.Api.V1/Indexers/ReleaseModule.cs index 1b849d057..0783a3359 100644 --- a/src/Lidarr.Api.V1/Indexers/ReleaseModule.cs +++ b/src/Lidarr.Api.V1/Indexers/ReleaseModule.cs @@ -11,7 +11,6 @@ using NzbDrone.Core.Indexers; using NzbDrone.Core.IndexerSearch; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Validation; -using Lidarr.Http.Extensions; using HttpStatusCode = System.Net.HttpStatusCode; namespace Lidarr.Api.V1.Indexers @@ -43,7 +42,7 @@ namespace Lidarr.Api.V1.Indexers _logger = logger; GetResourceAll = GetReleases; - Post("/", x => DownloadRelease(ReadResourceFromRequest())); + Post("/", x => DownloadRelease(ReadResourceFromRequest())); PostValidator.RuleFor(s => s.IndexerId).ValidId(); PostValidator.RuleFor(s => s.Guid).NotEmpty(); diff --git a/src/Lidarr.Api.V1/Indexers/ReleaseModuleBase.cs b/src/Lidarr.Api.V1/Indexers/ReleaseModuleBase.cs index b506855e6..7f685664c 100644 --- a/src/Lidarr.Api.V1/Indexers/ReleaseModuleBase.cs +++ b/src/Lidarr.Api.V1/Indexers/ReleaseModuleBase.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -using NzbDrone.Core.DecisionEngine; using Lidarr.Http; +using NzbDrone.Core.DecisionEngine; namespace Lidarr.Api.V1.Indexers { diff --git a/src/Lidarr.Api.V1/Indexers/ReleasePushModule.cs b/src/Lidarr.Api.V1/Indexers/ReleasePushModule.cs index 8f22c2c3a..e8c2ade8f 100644 --- a/src/Lidarr.Api.V1/Indexers/ReleasePushModule.cs +++ b/src/Lidarr.Api.V1/Indexers/ReleasePushModule.cs @@ -2,19 +2,17 @@ using System.Collections.Generic; using System.Linq; using FluentValidation; using FluentValidation.Results; -using Nancy; using NLog; -using NzbDrone.Core.DecisionEngine; -using NzbDrone.Core.Download; -using NzbDrone.Core.Parser.Model; -using Lidarr.Http.Extensions; 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 Lidarr.Api.V1.Indexers { - class ReleasePushModule : ReleaseModuleBase + internal class ReleasePushModule : ReleaseModuleBase { private readonly IMakeDownloadDecision _downloadDecisionMaker; private readonly IProcessDownloadDecisions _downloadDecisionProcessor; @@ -31,7 +29,7 @@ namespace Lidarr.Api.V1.Indexers _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/Lidarr.Api.V1/Indexers/ReleaseResource.cs b/src/Lidarr.Api.V1/Indexers/ReleaseResource.cs index bc10523cb..b1cf31804 100644 --- a/src/Lidarr.Api.V1/Indexers/ReleaseResource.cs +++ b/src/Lidarr.Api.V1/Indexers/ReleaseResource.cs @@ -1,12 +1,12 @@ using System; using System.Collections.Generic; using System.Linq; +using Lidarr.Http.REST; using Newtonsoft.Json; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Indexers; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; -using Lidarr.Http.REST; namespace Lidarr.Api.V1.Indexers { @@ -49,12 +49,13 @@ namespace Lidarr.Api.V1.Indexers public DownloadProtocol Protocol { get; set; } // Sent when queuing an unknown release - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + // [JsonIgnore] public int? ArtistId { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + // [JsonIgnore] public int? AlbumId { get; set; } } @@ -73,6 +74,7 @@ namespace Lidarr.Api.V1.Indexers { Guid = releaseInfo.Guid, Quality = parsedAlbumInfo.Quality, + //QualityWeight Age = releaseInfo.Age, AgeHours = releaseInfo.AgeHours, @@ -95,17 +97,16 @@ namespace Lidarr.Api.V1.Indexers DownloadUrl = releaseInfo.DownloadUrl, InfoUrl = releaseInfo.InfoUrl, DownloadAllowed = remoteAlbum.DownloadAllowed, + //ReleaseWeight PreferredWordScore = remoteAlbum.PreferredWordScore, - 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/Lidarr.Api.V1/Logs/LogFileModule.cs b/src/Lidarr.Api.V1/Logs/LogFileModule.cs index fadd69ad1..a217a58d5 100644 --- a/src/Lidarr.Api.V1/Logs/LogFileModule.cs +++ b/src/Lidarr.Api.V1/Logs/LogFileModule.cs @@ -38,6 +38,5 @@ namespace Lidarr.Api.V1.Logs return "logfile"; } } - } -} \ No newline at end of file +} diff --git a/src/Lidarr.Api.V1/Logs/LogFileModuleBase.cs b/src/Lidarr.Api.V1/Logs/LogFileModuleBase.cs index c28ba6df7..c308cf2b3 100644 --- a/src/Lidarr.Api.V1/Logs/LogFileModuleBase.cs +++ b/src/Lidarr.Api.V1/Logs/LogFileModuleBase.cs @@ -1,12 +1,12 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using Lidarr.Http; using Nancy; using Nancy.Responses; +using NLog; using NzbDrone.Common.Disk; using NzbDrone.Core.Configuration; -using Lidarr.Http; -using NLog; namespace Lidarr.Api.V1.Logs { @@ -26,7 +26,7 @@ namespace Lidarr.Api.V1.Logs _configFileProvider = configFileProvider; GetResourceAll = GetLogFilesResponse; - Get(LOGFILE_ROUTE, options => GetLogFileResponse(options.filename)); + Get(LOGFILE_ROUTE, options => GetLogFileResponse(options.filename)); } private List GetLogFilesResponse() @@ -39,7 +39,7 @@ namespace Lidarr.Api.V1.Logs { var file = files[i]; var filename = Path.GetFileName(file); - + result.Add(new LogFileResource { Id = i + 1, @@ -60,10 +60,12 @@ namespace Lidarr.Api.V1.Logs var filePath = GetLogFilePath(filename); if (!_diskProvider.FileExists(filePath)) + { return new NotFoundResponse(); + } var data = _diskProvider.ReadAllText(filePath); - + return new TextResponse(data); } diff --git a/src/Lidarr.Api.V1/Logs/LogModule.cs b/src/Lidarr.Api.V1/Logs/LogModule.cs index 1316e9024..ba9c61312 100644 --- a/src/Lidarr.Api.V1/Logs/LogModule.cs +++ b/src/Lidarr.Api.V1/Logs/LogModule.cs @@ -1,6 +1,6 @@ using System.Linq; -using NzbDrone.Core.Instrumentation; using Lidarr.Http; +using NzbDrone.Core.Instrumentation; namespace Lidarr.Api.V1.Logs { diff --git a/src/Lidarr.Api.V1/Logs/LogResource.cs b/src/Lidarr.Api.V1/Logs/LogResource.cs index bd2503bf2..d8d0f5f20 100644 --- a/src/Lidarr.Api.V1/Logs/LogResource.cs +++ b/src/Lidarr.Api.V1/Logs/LogResource.cs @@ -1,6 +1,6 @@ using System; -using NzbDrone.Core.Instrumentation; using Lidarr.Http.REST; +using NzbDrone.Core.Instrumentation; namespace Lidarr.Api.V1.Logs { @@ -19,7 +19,10 @@ namespace Lidarr.Api.V1.Logs { public static LogResource ToResource(this Log model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new LogResource { diff --git a/src/Lidarr.Api.V1/Logs/UpdateLogFileModule.cs b/src/Lidarr.Api.V1/Logs/UpdateLogFileModule.cs index 441ee9e36..83680b94c 100644 --- a/src/Lidarr.Api.V1/Logs/UpdateLogFileModule.cs +++ b/src/Lidarr.Api.V1/Logs/UpdateLogFileModule.cs @@ -25,7 +25,10 @@ namespace Lidarr.Api.V1.Logs 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)) @@ -45,4 +48,4 @@ namespace Lidarr.Api.V1.Logs } } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Api.V1/ManualImport/ManualImportModule.cs b/src/Lidarr.Api.V1/ManualImport/ManualImportModule.cs index f01c313b8..c9c7017b4 100644 --- a/src/Lidarr.Api.V1/ManualImport/ManualImportModule.cs +++ b/src/Lidarr.Api.V1/ManualImport/ManualImportModule.cs @@ -1,13 +1,13 @@ using System.Collections.Generic; using System.Linq; -using NzbDrone.Core.MediaFiles.TrackImport.Manual; -using NzbDrone.Core.Qualities; -using Lidarr.Http.Extensions; -using NzbDrone.Core.Music; -using NLog; -using Nancy; using Lidarr.Http; +using Lidarr.Http.Extensions; +using Nancy; +using NLog; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.MediaFiles.TrackImport.Manual; +using NzbDrone.Core.Music; +using NzbDrone.Core.Qualities; namespace Lidarr.Api.V1.ManualImport { @@ -32,7 +32,7 @@ namespace Lidarr.Api.V1.ManualImport _logger = logger; GetResourceAll = GetMediaFiles; - + Put("/", options => { var resource = Request.Body.FromJson>(); @@ -58,7 +58,7 @@ namespace Lidarr.Api.V1.ManualImport item.QualityWeight += item.Quality.Revision.Real * 10; item.QualityWeight += item.Quality.Revision.Version; } - + return item; } @@ -67,23 +67,24 @@ namespace Lidarr.Api.V1.ManualImport var items = new List(); foreach (var resource in resources) { - items.Add(new ManualImportItem { - Id = resource.Id, - Path = resource.Path, - RelativePath = resource.RelativePath, - Name = resource.Name, - Size = resource.Size, - Artist = resource.Artist == null ? null : _artistService.GetArtist(resource.Artist.Id), - Album = resource.Album == null ? null : _albumService.GetAlbum(resource.Album.Id), - Release = resource.AlbumReleaseId == 0 ? null : _releaseService.GetRelease(resource.AlbumReleaseId), - Quality = resource.Quality, - DownloadId = resource.DownloadId, - AdditionalFile = resource.AdditionalFile, - ReplaceExistingFiles = resource.ReplaceExistingFiles, - DisableReleaseSwitching = resource.DisableReleaseSwitching - }); + items.Add(new ManualImportItem + { + Id = resource.Id, + Path = resource.Path, + RelativePath = resource.RelativePath, + Name = resource.Name, + Size = resource.Size, + Artist = resource.Artist == null ? null : _artistService.GetArtist(resource.Artist.Id), + Album = resource.Album == null ? null : _albumService.GetAlbum(resource.Album.Id), + Release = resource.AlbumReleaseId == 0 ? null : _releaseService.GetRelease(resource.AlbumReleaseId), + Quality = resource.Quality, + DownloadId = resource.DownloadId, + AdditionalFile = resource.AdditionalFile, + ReplaceExistingFiles = resource.ReplaceExistingFiles, + DisableReleaseSwitching = resource.DisableReleaseSwitching + }); } - + return _manualImportService.UpdateItems(items).Select(x => x.ToResource()).ToList(); } } diff --git a/src/Lidarr.Api.V1/ManualImport/ManualImportResource.cs b/src/Lidarr.Api.V1/ManualImport/ManualImportResource.cs index cce255260..4d9c2653a 100644 --- a/src/Lidarr.Api.V1/ManualImport/ManualImportResource.cs +++ b/src/Lidarr.Api.V1/ManualImport/ManualImportResource.cs @@ -1,13 +1,13 @@ -using NzbDrone.Core.DecisionEngine; -using NzbDrone.Core.MediaFiles.TrackImport.Manual; -using NzbDrone.Core.Qualities; -using Lidarr.Api.V1.Artist; -using Lidarr.Api.V1.Albums; -using Lidarr.Api.V1.Tracks; -using Lidarr.Http.REST; using System.Collections.Generic; using System.Linq; +using Lidarr.Api.V1.Albums; +using Lidarr.Api.V1.Artist; +using Lidarr.Api.V1.Tracks; +using Lidarr.Http.REST; +using NzbDrone.Core.DecisionEngine; +using NzbDrone.Core.MediaFiles.TrackImport.Manual; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Qualities; namespace Lidarr.Api.V1.ManualImport { @@ -35,7 +35,10 @@ namespace Lidarr.Api.V1.ManualImport { public static ManualImportResource ToResource(this ManualImportItem model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ManualImportResource { @@ -49,6 +52,7 @@ namespace Lidarr.Api.V1.ManualImport AlbumReleaseId = model.Release?.Id ?? 0, Tracks = model.Tracks.ToResource(), Quality = model.Quality, + //QualityWeight DownloadId = model.DownloadId, Rejections = model.Rejections, diff --git a/src/Lidarr.Api.V1/MediaCovers/MediaCoverModule.cs b/src/Lidarr.Api.V1/MediaCovers/MediaCoverModule.cs index c5dd99baf..d383019d4 100644 --- a/src/Lidarr.Api.V1/MediaCovers/MediaCoverModule.cs +++ b/src/Lidarr.Api.V1/MediaCovers/MediaCoverModule.cs @@ -10,21 +10,22 @@ namespace Lidarr.Api.V1.MediaCovers { public class MediaCoverModule : LidarrV1Module { - private static readonly Regex RegexResizedImage = new Regex(@"-\d+(?=\.(jpg|png|gif)$)", RegexOptions.Compiled | RegexOptions.IgnoreCase); - private const string MEDIA_COVER_ARTIST_ROUTE = @"/Artist/(?\d+)/(?(.+)\.(jpg|png|gif))"; private const string MEDIA_COVER_ALBUM_ROUTE = @"/Album/(?\d+)/(?(.+)\.(jpg|png|gif))"; + private static readonly Regex RegexResizedImage = new Regex(@"-\d+(?=\.(jpg|png|gif)$)", RegexOptions.Compiled | RegexOptions.IgnoreCase); + 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_ARTIST_ROUTE, options => GetArtistMediaCover(options.artistId, options.filename)); - Get(MEDIA_COVER_ALBUM_ROUTE, options => GetAlbumMediaCover(options.artistId, options.filename)); + Get(MEDIA_COVER_ARTIST_ROUTE, options => GetArtistMediaCover(options.artistId, options.filename)); + Get(MEDIA_COVER_ALBUM_ROUTE, options => GetAlbumMediaCover(options.artistId, options.filename)); } private object GetArtistMediaCover(int artistId, string filename) @@ -40,6 +41,7 @@ namespace Lidarr.Api.V1.MediaCovers { return new NotFoundResponse(); } + filePath = basefilePath; } @@ -59,6 +61,7 @@ namespace Lidarr.Api.V1.MediaCovers { return new NotFoundResponse(); } + filePath = basefilePath; } diff --git a/src/Lidarr.Api.V1/Metadata/MetadataModule.cs b/src/Lidarr.Api.V1/Metadata/MetadataModule.cs index 1006c47b7..f3f452fcc 100644 --- a/src/Lidarr.Api.V1/Metadata/MetadataModule.cs +++ b/src/Lidarr.Api.V1/Metadata/MetadataModule.cs @@ -13,8 +13,12 @@ namespace Lidarr.Api.V1.Metadata protected override void Validate(MetadataDefinition definition, bool includeWarnings) { - if (!definition.Enable) return; + if (!definition.Enable) + { + return; + } + base.Validate(definition, includeWarnings); } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Api.V1/Metadata/MetadataResource.cs b/src/Lidarr.Api.V1/Metadata/MetadataResource.cs index 5921b7fcb..864d4cec0 100644 --- a/src/Lidarr.Api.V1/Metadata/MetadataResource.cs +++ b/src/Lidarr.Api.V1/Metadata/MetadataResource.cs @@ -11,7 +11,10 @@ namespace Lidarr.Api.V1.Metadata { 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 @@ namespace Lidarr.Api.V1.Metadata public override MetadataDefinition ToModel(MetadataResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } var definition = base.ToModel(resource); @@ -31,4 +37,4 @@ namespace Lidarr.Api.V1.Metadata return definition; } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Api.V1/Notifications/NotificationModule.cs b/src/Lidarr.Api.V1/Notifications/NotificationModule.cs index 10e67e3de..49825e513 100644 --- a/src/Lidarr.Api.V1/Notifications/NotificationModule.cs +++ b/src/Lidarr.Api.V1/Notifications/NotificationModule.cs @@ -13,7 +13,11 @@ namespace Lidarr.Api.V1.Notifications protected override void Validate(NotificationDefinition definition, bool includeWarnings) { - if (!definition.Enable) return; + if (!definition.Enable) + { + return; + } + base.Validate(definition, includeWarnings); } } diff --git a/src/Lidarr.Api.V1/Notifications/NotificationResource.cs b/src/Lidarr.Api.V1/Notifications/NotificationResource.cs index 95fc55b6c..bc8e784b1 100644 --- a/src/Lidarr.Api.V1/Notifications/NotificationResource.cs +++ b/src/Lidarr.Api.V1/Notifications/NotificationResource.cs @@ -29,7 +29,10 @@ namespace Lidarr.Api.V1.Notifications { public override NotificationResource ToResource(NotificationDefinition definition) { - if (definition == null) return default(NotificationResource); + if (definition == null) + { + return default(NotificationResource); + } var resource = base.ToResource(definition); @@ -56,7 +59,10 @@ namespace Lidarr.Api.V1.Notifications 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/Lidarr.Api.V1/Parse/ParseModule.cs b/src/Lidarr.Api.V1/Parse/ParseModule.cs index c3afb268d..d1cf0d49a 100644 --- a/src/Lidarr.Api.V1/Parse/ParseModule.cs +++ b/src/Lidarr.Api.V1/Parse/ParseModule.cs @@ -1,8 +1,7 @@ -using NzbDrone.Common.Extensions; -using NzbDrone.Core.Parser; using Lidarr.Api.V1.Albums; using Lidarr.Api.V1.Artist; using Lidarr.Http; +using NzbDrone.Core.Parser; namespace Lidarr.Api.V1.Parse { diff --git a/src/Lidarr.Api.V1/Parse/ParseResource.cs b/src/Lidarr.Api.V1/Parse/ParseResource.cs index 785777a56..b7b22de3c 100644 --- a/src/Lidarr.Api.V1/Parse/ParseResource.cs +++ b/src/Lidarr.Api.V1/Parse/ParseResource.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; -using NzbDrone.Core.Parser.Model; using Lidarr.Api.V1.Albums; using Lidarr.Api.V1.Artist; using Lidarr.Http.REST; +using NzbDrone.Core.Parser.Model; namespace Lidarr.Api.V1.Parse { diff --git a/src/Lidarr.Api.V1/Profiles/Delay/DelayProfileModule.cs b/src/Lidarr.Api.V1/Profiles/Delay/DelayProfileModule.cs index c00f7ed26..80035815c 100644 --- a/src/Lidarr.Api.V1/Profiles/Delay/DelayProfileModule.cs +++ b/src/Lidarr.Api.V1/Profiles/Delay/DelayProfileModule.cs @@ -1,13 +1,11 @@ using System; using System.Collections.Generic; using FluentValidation; -using FluentValidation.Results; -using Nancy; -using NzbDrone.Core.Profiles.Delay; using Lidarr.Http; -using Lidarr.Http.Extensions; using Lidarr.Http.REST; using Lidarr.Http.Validation; +using Nancy; +using NzbDrone.Core.Profiles.Delay; namespace Lidarr.Api.V1.Profiles.Delay { @@ -24,7 +22,7 @@ namespace Lidarr.Api.V1.Profiles.Delay UpdateResource = Update; CreateResource = Create; DeleteResource = DeleteProfile; - Put(@"/reorder/(?[\d]{1,10})", options => Reorder(options.Id)); + Put(@"/reorder/(?[\d]{1,10})", options => Reorder(options.Id)); SharedValidator.RuleFor(d => d.Tags).NotEmpty().When(d => d.Id != 1); SharedValidator.RuleFor(d => d.Tags).EmptyCollection().When(d => d.Id == 1); @@ -85,4 +83,4 @@ namespace Lidarr.Api.V1.Profiles.Delay return _delayProfileService.Reorder(id, afterId).ToResource(); } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Api.V1/Profiles/Delay/DelayProfileResource.cs b/src/Lidarr.Api.V1/Profiles/Delay/DelayProfileResource.cs index bcdd83c65..23c483c21 100644 --- a/src/Lidarr.Api.V1/Profiles/Delay/DelayProfileResource.cs +++ b/src/Lidarr.Api.V1/Profiles/Delay/DelayProfileResource.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; +using Lidarr.Http.REST; using NzbDrone.Core.Indexers; using NzbDrone.Core.Profiles.Delay; -using Lidarr.Http.REST; namespace Lidarr.Api.V1.Profiles.Delay { @@ -21,7 +21,10 @@ namespace Lidarr.Api.V1.Profiles.Delay { public static DelayProfileResource ToResource(this DelayProfile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new DelayProfileResource { @@ -39,7 +42,10 @@ namespace Lidarr.Api.V1.Profiles.Delay public static DelayProfile ToModel(this DelayProfileResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new DelayProfile { diff --git a/src/Lidarr.Api.V1/Profiles/Metadata/MetadataProfileModule.cs b/src/Lidarr.Api.V1/Profiles/Metadata/MetadataProfileModule.cs index 59648b120..1006a4185 100644 --- a/src/Lidarr.Api.V1/Profiles/Metadata/MetadataProfileModule.cs +++ b/src/Lidarr.Api.V1/Profiles/Metadata/MetadataProfileModule.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using FluentValidation; -using NzbDrone.Core.Profiles.Metadata; using Lidarr.Http; +using NzbDrone.Core.Profiles.Metadata; namespace Lidarr.Api.V1.Profiles.Metadata { diff --git a/src/Lidarr.Api.V1/Profiles/Metadata/MetadataProfileResource.cs b/src/Lidarr.Api.V1/Profiles/Metadata/MetadataProfileResource.cs index 0f6dd8bb4..fcc07a68c 100644 --- a/src/Lidarr.Api.V1/Profiles/Metadata/MetadataProfileResource.cs +++ b/src/Lidarr.Api.V1/Profiles/Metadata/MetadataProfileResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using NzbDrone.Core.Profiles.Metadata; using Lidarr.Http.REST; +using NzbDrone.Core.Profiles.Metadata; namespace Lidarr.Api.V1.Profiles.Metadata { @@ -35,7 +35,10 @@ namespace Lidarr.Api.V1.Profiles.Metadata { public static MetadataProfileResource ToResource(this MetadataProfile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new MetadataProfileResource { @@ -49,7 +52,10 @@ namespace Lidarr.Api.V1.Profiles.Metadata public static ProfilePrimaryAlbumTypeItemResource ToResource(this ProfilePrimaryAlbumTypeItem model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ProfilePrimaryAlbumTypeItemResource { @@ -105,7 +111,10 @@ namespace Lidarr.Api.V1.Profiles.Metadata public static ProfilePrimaryAlbumTypeItem ToModel(this ProfilePrimaryAlbumTypeItemResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new ProfilePrimaryAlbumTypeItem { @@ -116,10 +125,13 @@ namespace Lidarr.Api.V1.Profiles.Metadata public static ProfileSecondaryAlbumTypeItem ToModel(this ProfileSecondaryAlbumTypeItemResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new ProfileSecondaryAlbumTypeItem - { + { SecondaryAlbumType = (NzbDrone.Core.Music.SecondaryAlbumType)resource.AlbumType.Id, Allowed = resource.Allowed }; @@ -127,7 +139,10 @@ namespace Lidarr.Api.V1.Profiles.Metadata public static ProfileReleaseStatusItem ToModel(this ProfileReleaseStatusItemResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new ProfileReleaseStatusItem { @@ -136,7 +151,7 @@ namespace Lidarr.Api.V1.Profiles.Metadata }; } - public static List ToResource(this IEnumerable models) + public static List ToResource(this IEnumerable models) { return models.Select(ToResource).ToList(); } diff --git a/src/Lidarr.Api.V1/Profiles/Metadata/MetadataProfileSchemaModule.cs b/src/Lidarr.Api.V1/Profiles/Metadata/MetadataProfileSchemaModule.cs index 1e7fb7650..6a4619e03 100644 --- a/src/Lidarr.Api.V1/Profiles/Metadata/MetadataProfileSchemaModule.cs +++ b/src/Lidarr.Api.V1/Profiles/Metadata/MetadataProfileSchemaModule.cs @@ -1,12 +1,11 @@ using System.Linq; -using NzbDrone.Core.Profiles.Metadata; using Lidarr.Http; +using NzbDrone.Core.Profiles.Metadata; namespace Lidarr.Api.V1.Profiles.Metadata { public class MetadataProfileSchemaModule : LidarrRestModule { - public MetadataProfileSchemaModule() : base("/metadataprofile/schema") { @@ -28,23 +27,23 @@ namespace Lidarr.Api.V1.Profiles.Metadata .ToList(); var primTypes = orderedPrimTypes - .Select(v => new ProfilePrimaryAlbumTypeItem {PrimaryAlbumType = v, Allowed = false}) + .Select(v => new ProfilePrimaryAlbumTypeItem { PrimaryAlbumType = v, Allowed = false }) .ToList(); var secTypes = orderedSecTypes - .Select(v => new ProfileSecondaryAlbumTypeItem {SecondaryAlbumType = v, Allowed = false}) + .Select(v => new ProfileSecondaryAlbumTypeItem { SecondaryAlbumType = v, Allowed = false }) .ToList(); var relStatuses = orderedRelStatuses - .Select(v => new ProfileReleaseStatusItem {ReleaseStatus = v, Allowed = false}) + .Select(v => new ProfileReleaseStatusItem { ReleaseStatus = v, Allowed = false }) .ToList(); var profile = new MetadataProfile - { - PrimaryAlbumTypes = primTypes, - SecondaryAlbumTypes = secTypes, - ReleaseStatuses = relStatuses - }; + { + PrimaryAlbumTypes = primTypes, + SecondaryAlbumTypes = secTypes, + ReleaseStatuses = relStatuses + }; return profile.ToResource(); } diff --git a/src/Lidarr.Api.V1/Profiles/Metadata/MetadataValidator.cs b/src/Lidarr.Api.V1/Profiles/Metadata/MetadataValidator.cs index 596176fbb..303af1c24 100644 --- a/src/Lidarr.Api.V1/Profiles/Metadata/MetadataValidator.cs +++ b/src/Lidarr.Api.V1/Profiles/Metadata/MetadataValidator.cs @@ -29,7 +29,6 @@ namespace Lidarr.Api.V1.Profiles.Metadata } } - public class PrimaryTypeValidator : PropertyValidator { public PrimaryTypeValidator() diff --git a/src/Lidarr.Api.V1/Profiles/Quality/QualityCutoffValidator.cs b/src/Lidarr.Api.V1/Profiles/Quality/QualityCutoffValidator.cs index 037620f4e..f3c333e32 100644 --- a/src/Lidarr.Api.V1/Profiles/Quality/QualityCutoffValidator.cs +++ b/src/Lidarr.Api.V1/Profiles/Quality/QualityCutoffValidator.cs @@ -18,7 +18,6 @@ namespace Lidarr.Api.V1.Profiles.Quality public ValidCutoffValidator() : base("Cutoff must be an allowed quality or group") { - } protected override bool IsValid(PropertyValidatorContext context) diff --git a/src/Lidarr.Api.V1/Profiles/Quality/QualityItemsValidator.cs b/src/Lidarr.Api.V1/Profiles/Quality/QualityItemsValidator.cs index 24b765218..7e0ee12d1 100644 --- a/src/Lidarr.Api.V1/Profiles/Quality/QualityItemsValidator.cs +++ b/src/Lidarr.Api.V1/Profiles/Quality/QualityItemsValidator.cs @@ -26,7 +26,6 @@ namespace Lidarr.Api.V1.Profiles.Quality public AllowedValidator() : base("Must contain at least one allowed quality") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -52,7 +51,6 @@ namespace Lidarr.Api.V1.Profiles.Quality public GroupItemValidator() : base("Groups must contain multiple qualities") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -73,7 +71,6 @@ namespace Lidarr.Api.V1.Profiles.Quality public QualityNameValidator() : base("Individual qualities should not be named") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -94,7 +91,6 @@ namespace Lidarr.Api.V1.Profiles.Quality public ItemGroupNameValidator() : base("Groups must have a name") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -115,7 +111,6 @@ namespace Lidarr.Api.V1.Profiles.Quality public ItemGroupIdValidator() : base("Groups must have an ID") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -136,7 +131,6 @@ namespace Lidarr.Api.V1.Profiles.Quality public UniqueIdValidator() : base("Groups must have a unique ID") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -157,7 +151,6 @@ namespace Lidarr.Api.V1.Profiles.Quality public UniqueQualityIdValidator() : base("Qualities can only be used once") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -179,7 +172,6 @@ namespace Lidarr.Api.V1.Profiles.Quality qualityIds.Add(quality.Quality.Id); } } - else { if (qualityIds.Contains(item.Quality.Id)) diff --git a/src/Lidarr.Api.V1/Profiles/Quality/QualityProfileModule.cs b/src/Lidarr.Api.V1/Profiles/Quality/QualityProfileModule.cs index dbb8b5b63..9146d9000 100644 --- a/src/Lidarr.Api.V1/Profiles/Quality/QualityProfileModule.cs +++ b/src/Lidarr.Api.V1/Profiles/Quality/QualityProfileModule.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using FluentValidation; -using NzbDrone.Core.Profiles.Qualities; using Lidarr.Http; +using NzbDrone.Core.Profiles.Qualities; namespace Lidarr.Api.V1.Profiles.Quality { diff --git a/src/Lidarr.Api.V1/Profiles/Quality/QualityProfileResource.cs b/src/Lidarr.Api.V1/Profiles/Quality/QualityProfileResource.cs index a50bc0fd8..381bb17c7 100644 --- a/src/Lidarr.Api.V1/Profiles/Quality/QualityProfileResource.cs +++ b/src/Lidarr.Api.V1/Profiles/Quality/QualityProfileResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using NzbDrone.Core.Profiles.Qualities; using Lidarr.Http.REST; +using NzbDrone.Core.Profiles.Qualities; namespace Lidarr.Api.V1.Profiles.Quality { @@ -30,7 +30,10 @@ namespace Lidarr.Api.V1.Profiles.Quality { public static QualityProfileResource ToResource(this QualityProfile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new QualityProfileResource { @@ -44,7 +47,10 @@ namespace Lidarr.Api.V1.Profiles.Quality public static QualityProfileQualityItemResource ToResource(this QualityProfileQualityItem model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new QualityProfileQualityItemResource { @@ -58,7 +64,10 @@ namespace Lidarr.Api.V1.Profiles.Quality public static QualityProfile ToModel(this QualityProfileResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new QualityProfile { @@ -72,7 +81,10 @@ namespace Lidarr.Api.V1.Profiles.Quality public static QualityProfileQualityItem ToModel(this QualityProfileQualityItemResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new QualityProfileQualityItem { diff --git a/src/Lidarr.Api.V1/Profiles/Quality/QualityProfileSchemaModule.cs b/src/Lidarr.Api.V1/Profiles/Quality/QualityProfileSchemaModule.cs index 3436d935b..d3a1dd3c9 100644 --- a/src/Lidarr.Api.V1/Profiles/Quality/QualityProfileSchemaModule.cs +++ b/src/Lidarr.Api.V1/Profiles/Quality/QualityProfileSchemaModule.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Profiles.Qualities; using Lidarr.Http; +using NzbDrone.Core.Profiles.Qualities; namespace Lidarr.Api.V1.Profiles.Quality { @@ -18,7 +18,6 @@ namespace Lidarr.Api.V1.Profiles.Quality { QualityProfile qualityProfile = _profileService.GetDefaultProfile(string.Empty); - return qualityProfile.ToResource(); } } diff --git a/src/Lidarr.Api.V1/Profiles/Release/ReleaseProfileModule.cs b/src/Lidarr.Api.V1/Profiles/Release/ReleaseProfileModule.cs index 3ce7a3d40..7ef4424db 100644 --- a/src/Lidarr.Api.V1/Profiles/Release/ReleaseProfileModule.cs +++ b/src/Lidarr.Api.V1/Profiles/Release/ReleaseProfileModule.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using FluentValidation; +using Lidarr.Http; using NzbDrone.Common.Extensions; using NzbDrone.Core.Profiles.Releases; -using Lidarr.Http; namespace Lidarr.Api.V1.Profiles.Release { @@ -10,7 +10,6 @@ namespace Lidarr.Api.V1.Profiles.Release { private readonly IReleaseProfileService _releaseProfileService; - public ReleaseProfileModule(IReleaseProfileService releaseProfileService) { _releaseProfileService = releaseProfileService; diff --git a/src/Lidarr.Api.V1/Profiles/Release/ReleaseProfileResource.cs b/src/Lidarr.Api.V1/Profiles/Release/ReleaseProfileResource.cs index e7af27941..c57c0d07f 100644 --- a/src/Lidarr.Api.V1/Profiles/Release/ReleaseProfileResource.cs +++ b/src/Lidarr.Api.V1/Profiles/Release/ReleaseProfileResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using NzbDrone.Core.Profiles.Releases; using Lidarr.Http.REST; +using NzbDrone.Core.Profiles.Releases; namespace Lidarr.Api.V1.Profiles.Release { @@ -23,7 +23,10 @@ namespace Lidarr.Api.V1.Profiles.Release { public static ReleaseProfileResource ToResource(this ReleaseProfile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ReleaseProfileResource { @@ -39,7 +42,10 @@ namespace Lidarr.Api.V1.Profiles.Release public static ReleaseProfile ToModel(this ReleaseProfileResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new ReleaseProfile { diff --git a/src/Lidarr.Api.V1/ProviderModuleBase.cs b/src/Lidarr.Api.V1/ProviderModuleBase.cs index 5c68cef83..c56c9e4f7 100644 --- a/src/Lidarr.Api.V1/ProviderModuleBase.cs +++ b/src/Lidarr.Api.V1/ProviderModuleBase.cs @@ -2,13 +2,11 @@ using System.Collections.Generic; using System.Linq; using FluentValidation; using FluentValidation.Results; +using Lidarr.Http; using Nancy; -using Newtonsoft.Json; using NzbDrone.Common.Serializer; using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; -using Lidarr.Http; -using Lidarr.Http.Extensions; namespace Lidarr.Api.V1 { @@ -26,10 +24,10 @@ namespace Lidarr.Api.V1 _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; @@ -38,7 +36,7 @@ namespace Lidarr.Api.V1 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(); diff --git a/src/Lidarr.Api.V1/ProviderResource.cs b/src/Lidarr.Api.V1/ProviderResource.cs index 428b3717e..b64d1b031 100644 --- a/src/Lidarr.Api.V1/ProviderResource.cs +++ b/src/Lidarr.Api.V1/ProviderResource.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; -using NzbDrone.Common.Reflection; -using NzbDrone.Core.ThingiProvider; using Lidarr.Http.ClientSchema; using Lidarr.Http.REST; +using NzbDrone.Common.Reflection; +using NzbDrone.Core.ThingiProvider; namespace Lidarr.Api.V1 { @@ -25,7 +25,6 @@ namespace Lidarr.Api.V1 where TProviderDefinition : ProviderDefinition, new() { public virtual TProviderResource ToResource(TProviderDefinition definition) - { return new TProviderResource { @@ -47,7 +46,10 @@ namespace Lidarr.Api.V1 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/Lidarr.Api.V1/Qualities/QualityDefinitionModule.cs b/src/Lidarr.Api.V1/Qualities/QualityDefinitionModule.cs index c040a9442..39b740d0a 100644 --- a/src/Lidarr.Api.V1/Qualities/QualityDefinitionModule.cs +++ b/src/Lidarr.Api.V1/Qualities/QualityDefinitionModule.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; using System.Linq; -using Nancy; -using NzbDrone.Core.Qualities; using Lidarr.Http; using Lidarr.Http.Extensions; +using Nancy; +using NzbDrone.Core.Qualities; namespace Lidarr.Api.V1.Qualities { @@ -18,7 +18,7 @@ namespace Lidarr.Api.V1.Qualities GetResourceAll = GetAll; GetResourceById = GetById; UpdateResource = Update; - Put("/update", d => UpdateMany()); + Put("/update", d => UpdateMany()); } private void Update(QualityDefinitionResource resource) @@ -47,8 +47,8 @@ namespace Lidarr.Api.V1.Qualities _qualityDefinitionService.UpdateMany(qualityDefinitions); return ResponseWithCode(_qualityDefinitionService.All() - .ToResource() - , HttpStatusCode.Accepted); + .ToResource(), + HttpStatusCode.Accepted); } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Api.V1/Qualities/QualityDefinitionResource.cs b/src/Lidarr.Api.V1/Qualities/QualityDefinitionResource.cs index 67c7b0822..daedc62c3 100644 --- a/src/Lidarr.Api.V1/Qualities/QualityDefinitionResource.cs +++ b/src/Lidarr.Api.V1/Qualities/QualityDefinitionResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using NzbDrone.Core.Qualities; using Lidarr.Http.REST; +using NzbDrone.Core.Qualities; namespace Lidarr.Api.V1.Qualities { @@ -21,7 +21,10 @@ namespace Lidarr.Api.V1.Qualities { public static QualityDefinitionResource ToResource(this QualityDefinition model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new QualityDefinitionResource { @@ -36,7 +39,10 @@ namespace Lidarr.Api.V1.Qualities public static QualityDefinition ToModel(this QualityDefinitionResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new QualityDefinition { @@ -59,4 +65,4 @@ namespace Lidarr.Api.V1.Qualities return resources.Select(ToModel).ToList(); } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Api.V1/Queue/QueueActionModule.cs b/src/Lidarr.Api.V1/Queue/QueueActionModule.cs index 2af9881d9..de1c546df 100644 --- a/src/Lidarr.Api.V1/Queue/QueueActionModule.cs +++ b/src/Lidarr.Api.V1/Queue/QueueActionModule.cs @@ -1,13 +1,12 @@ -using System; using System.Collections.Generic; +using Lidarr.Http; +using Lidarr.Http.Extensions; +using Lidarr.Http.REST; using Nancy; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Pending; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.Queue; -using Lidarr.Http; -using Lidarr.Http.Extensions; -using Lidarr.Http.REST; namespace Lidarr.Api.V1.Queue { @@ -34,11 +33,11 @@ namespace Lidarr.Api.V1.Queue _pendingReleaseService = pendingReleaseService; _downloadService = downloadService; - Post(@"/grab/(?[\d]{1,10})", x => Grab((int)x.Id)); - Post("/grab/bulk", x => Grab()); + Post(@"/grab/(?[\d]{1,10})", x => Grab((int)x.Id)); + Post("/grab/bulk", x => Grab()); - Delete(@"/(?[\d]{1,10})", x => Remove((int)x.Id)); - Delete("/bulk", x => Remove()); + Delete(@"/(?[\d]{1,10})", x => Remove((int)x.Id)); + Delete("/bulk", x => Remove()); } private object Grab(int id) diff --git a/src/Lidarr.Api.V1/Queue/QueueDetailsModule.cs b/src/Lidarr.Api.V1/Queue/QueueDetailsModule.cs index 72c90f1f5..569b1ec26 100644 --- a/src/Lidarr.Api.V1/Queue/QueueDetailsModule.cs +++ b/src/Lidarr.Api.V1/Queue/QueueDetailsModule.cs @@ -1,13 +1,13 @@ using System; using System.Collections.Generic; using System.Linq; +using Lidarr.Http; +using Lidarr.Http.Extensions; using NzbDrone.Core.Datastore.Events; using NzbDrone.Core.Download.Pending; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Queue; using NzbDrone.SignalR; -using Lidarr.Http; -using Lidarr.Http.Extensions; namespace Lidarr.Api.V1.Queue { diff --git a/src/Lidarr.Api.V1/Queue/QueueModule.cs b/src/Lidarr.Api.V1/Queue/QueueModule.cs index 94c25ecea..854ffc494 100644 --- a/src/Lidarr.Api.V1/Queue/QueueModule.cs +++ b/src/Lidarr.Api.V1/Queue/QueueModule.cs @@ -1,7 +1,8 @@ using System; using System.Linq; +using Lidarr.Http; +using Lidarr.Http.Extensions; using NzbDrone.Common.Extensions; -using NzbDrone.Core.Configuration; using NzbDrone.Core.Datastore; using NzbDrone.Core.Datastore.Events; using NzbDrone.Core.Download.Pending; @@ -10,8 +11,6 @@ using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; using NzbDrone.Core.Queue; using NzbDrone.SignalR; -using Lidarr.Http; -using Lidarr.Http.Extensions; namespace Lidarr.Api.V1.Queue { @@ -21,7 +20,7 @@ namespace Lidarr.Api.V1.Queue private readonly IQueueService _queueService; private readonly IPendingReleaseService _pendingReleaseService; - private readonly QualityModelComparer QUALITY_COMPARER; + private readonly QualityModelComparer _qualityComparer; public QueueModule(IBroadcastSignalRMessage broadcastSignalRMessage, IQueueService queueService, @@ -33,7 +32,7 @@ namespace Lidarr.Api.V1.Queue _pendingReleaseService = pendingReleaseService; GetResourcePaged = GetQueue; - QUALITY_COMPARER = new QualityModelComparer(qualityProfileService.GetDefaultProfile(string.Empty)); + _qualityComparer = new QualityModelComparer(qualityProfileService.GetDefaultProfile(string.Empty)); } private PagingResource GetQueue(PagingResource pagingResource) @@ -63,7 +62,6 @@ namespace Lidarr.Api.V1.Queue ? fullQueue.OrderBy(q => q.Timeleft, new TimeleftComparer()) : fullQueue.OrderByDescending(q => q.Timeleft, new TimeleftComparer()); } - else if (pagingSpec.SortKey == "estimatedCompletionTime") { ordered = ascending @@ -71,41 +69,36 @@ namespace Lidarr.Api.V1.Queue : 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; @@ -119,7 +112,7 @@ namespace Lidarr.Api.V1.Queue return pagingSpec; } - private Func GetOrderByFunc(PagingSpec pagingSpec) + private Func GetOrderByFunc(PagingSpec pagingSpec) { switch (pagingSpec.SortKey) { @@ -139,7 +132,7 @@ namespace Lidarr.Api.V1.Queue 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/Lidarr.Api.V1/Queue/QueueResource.cs b/src/Lidarr.Api.V1/Queue/QueueResource.cs index c9913d7f6..d5b11dde3 100644 --- a/src/Lidarr.Api.V1/Queue/QueueResource.cs +++ b/src/Lidarr.Api.V1/Queue/QueueResource.cs @@ -1,12 +1,12 @@ using System; using System.Collections.Generic; using System.Linq; -using NzbDrone.Core.Download.TrackedDownloads; -using NzbDrone.Core.Indexers; -using NzbDrone.Core.Qualities; using Lidarr.Api.V1.Albums; using Lidarr.Api.V1.Artist; using Lidarr.Http.REST; +using NzbDrone.Core.Download.TrackedDownloads; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.Qualities; namespace Lidarr.Api.V1.Queue { @@ -38,7 +38,10 @@ namespace Lidarr.Api.V1.Queue { public static QueueResource ToResource(this NzbDrone.Core.Queue.Queue model, bool includeArtist, bool includeAlbum) { - if (model == null) return null; + if (model == null) + { + return null; + } return new QueueResource { diff --git a/src/Lidarr.Api.V1/Queue/QueueStatusModule.cs b/src/Lidarr.Api.V1/Queue/QueueStatusModule.cs index b96134438..34a2040f6 100644 --- a/src/Lidarr.Api.V1/Queue/QueueStatusModule.cs +++ b/src/Lidarr.Api.V1/Queue/QueueStatusModule.cs @@ -1,12 +1,12 @@ using System; using System.Linq; +using Lidarr.Http; using NzbDrone.Common.TPL; using NzbDrone.Core.Datastore.Events; using NzbDrone.Core.Download.Pending; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Queue; using NzbDrone.SignalR; -using Lidarr.Http; namespace Lidarr.Api.V1.Queue { @@ -17,7 +17,6 @@ namespace Lidarr.Api.V1.Queue private readonly IPendingReleaseService _pendingReleaseService; private readonly Debouncer _broadcastDebounce; - public QueueStatusModule(IBroadcastSignalRMessage broadcastSignalRMessage, IQueueService queueService, IPendingReleaseService pendingReleaseService) : base(broadcastSignalRMessage, "queue/status") { @@ -26,8 +25,7 @@ namespace Lidarr.Api.V1.Queue _broadcastDebounce = new Debouncer(BroadcastChange, TimeSpan.FromSeconds(5)); - - Get("/", x => GetQueueStatusResponse()); + Get("/", x => GetQueueStatusResponse()); } private object GetQueueStatusResponse() @@ -67,12 +65,10 @@ namespace Lidarr.Api.V1.Queue { _broadcastDebounce.Execute(); } - + public void Handle(PendingReleasesUpdatedEvent message) { _broadcastDebounce.Execute(); } - - } } diff --git a/src/Lidarr.Api.V1/RemotePathMappings/RemotePathMappingModule.cs b/src/Lidarr.Api.V1/RemotePathMappings/RemotePathMappingModule.cs index 542e90d5b..e167bc9dc 100644 --- a/src/Lidarr.Api.V1/RemotePathMappings/RemotePathMappingModule.cs +++ b/src/Lidarr.Api.V1/RemotePathMappings/RemotePathMappingModule.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using FluentValidation; +using Lidarr.Http; using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.Validation.Paths; -using Lidarr.Http; namespace Lidarr.Api.V1.RemotePathMappings { @@ -65,4 +65,4 @@ namespace Lidarr.Api.V1.RemotePathMappings _remotePathMappingService.Update(mapping); } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Api.V1/RemotePathMappings/RemotePathMappingResource.cs b/src/Lidarr.Api.V1/RemotePathMappings/RemotePathMappingResource.cs index 1f4050274..80c8e04bf 100644 --- a/src/Lidarr.Api.V1/RemotePathMappings/RemotePathMappingResource.cs +++ b/src/Lidarr.Api.V1/RemotePathMappings/RemotePathMappingResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using NzbDrone.Core.RemotePathMappings; using Lidarr.Http.REST; +using NzbDrone.Core.RemotePathMappings; namespace Lidarr.Api.V1.RemotePathMappings { @@ -16,7 +16,10 @@ namespace Lidarr.Api.V1.RemotePathMappings { public static RemotePathMappingResource ToResource(this RemotePathMapping model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new RemotePathMappingResource { @@ -30,7 +33,10 @@ namespace Lidarr.Api.V1.RemotePathMappings public static RemotePathMapping ToModel(this RemotePathMappingResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new RemotePathMapping { diff --git a/src/Lidarr.Api.V1/RootFolders/RootFolderModule.cs b/src/Lidarr.Api.V1/RootFolders/RootFolderModule.cs index 0ee85e2b6..cba25a230 100644 --- a/src/Lidarr.Api.V1/RootFolders/RootFolderModule.cs +++ b/src/Lidarr.Api.V1/RootFolders/RootFolderModule.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; using FluentValidation; +using Lidarr.Http; using NzbDrone.Core.RootFolders; using NzbDrone.Core.Validation.Paths; using NzbDrone.SignalR; -using Lidarr.Http; namespace Lidarr.Api.V1.RootFolders { @@ -18,8 +18,7 @@ namespace Lidarr.Api.V1.RootFolders MappedNetworkDriveValidator mappedNetworkDriveValidator, StartupFolderValidator startupFolderValidator, SystemFolderValidator systemFolderValidator, - FolderWritableValidator folderWritableValidator - ) + FolderWritableValidator folderWritableValidator) : base(signalRBroadcaster) { _rootFolderService = rootFolderService; diff --git a/src/Lidarr.Api.V1/RootFolders/RootFolderResource.cs b/src/Lidarr.Api.V1/RootFolders/RootFolderResource.cs index 167c97058..2d19ef40e 100644 --- a/src/Lidarr.Api.V1/RootFolders/RootFolderResource.cs +++ b/src/Lidarr.Api.V1/RootFolders/RootFolderResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using NzbDrone.Core.RootFolders; using Lidarr.Http.REST; +using NzbDrone.Core.RootFolders; namespace Lidarr.Api.V1.RootFolders { @@ -19,7 +19,10 @@ namespace Lidarr.Api.V1.RootFolders { public static RootFolderResource ToResource(this RootFolder model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new RootFolderResource { @@ -35,13 +38,17 @@ namespace Lidarr.Api.V1.RootFolders 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/Lidarr.Api.V1/Search/SearchModule.cs b/src/Lidarr.Api.V1/Search/SearchModule.cs index 537acdbec..cb291e42c 100644 --- a/src/Lidarr.Api.V1/Search/SearchModule.cs +++ b/src/Lidarr.Api.V1/Search/SearchModule.cs @@ -1,12 +1,12 @@ +using System; using System.Collections.Generic; using System.Linq; +using Lidarr.Api.V1.Albums; +using Lidarr.Api.V1.Artist; +using Lidarr.Http; using Nancy; using NzbDrone.Core.MediaCover; using NzbDrone.Core.MetadataSource; -using Lidarr.Http; -using Lidarr.Api.V1.Artist; -using Lidarr.Api.V1.Albums; -using System; namespace Lidarr.Api.V1.Search { @@ -27,7 +27,7 @@ namespace Lidarr.Api.V1.Search return MapToResource(searchResults).ToList(); } - private static IEnumerable MapToResource(IEnumerable results) + private static IEnumerable MapToResource(IEnumerable results) { int id = 1; foreach (var result in results) @@ -37,7 +37,7 @@ namespace Lidarr.Api.V1.Search if (result is NzbDrone.Core.Music.Artist) { - var artist = (NzbDrone.Core.Music.Artist) result; + var artist = (NzbDrone.Core.Music.Artist)result; resource.Artist = artist.ToResource(); resource.ForeignId = artist.ForeignArtistId; @@ -49,7 +49,7 @@ namespace Lidarr.Api.V1.Search } else if (result is NzbDrone.Core.Music.Album) { - var album = (NzbDrone.Core.Music.Album) result; + var album = (NzbDrone.Core.Music.Album)result; resource.Album = album.ToResource(); resource.ForeignId = album.ForeignAlbumId; diff --git a/src/Lidarr.Api.V1/Search/SearchResource.cs b/src/Lidarr.Api.V1/Search/SearchResource.cs index bdcff3784..8f136b61d 100644 --- a/src/Lidarr.Api.V1/Search/SearchResource.cs +++ b/src/Lidarr.Api.V1/Search/SearchResource.cs @@ -1,6 +1,6 @@ -using Lidarr.Http.REST; -using Lidarr.Api.V1.Artist; using Lidarr.Api.V1.Albums; +using Lidarr.Api.V1.Artist; +using Lidarr.Http.REST; namespace Lidarr.Api.V1.Search { diff --git a/src/Lidarr.Api.V1/System/Backup/BackupModule.cs b/src/Lidarr.Api.V1/System/Backup/BackupModule.cs index dfedb1807..61d9a6fe6 100644 --- a/src/Lidarr.Api.V1/System/Backup/BackupModule.cs +++ b/src/Lidarr.Api.V1/System/Backup/BackupModule.cs @@ -1,15 +1,13 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using Nancy; +using Lidarr.Http; +using Lidarr.Http.REST; using NzbDrone.Common.Crypto; using NzbDrone.Common.Disk; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Common.Extensions; using NzbDrone.Core.Backup; -using Lidarr.Http; -using Lidarr.Http.Extensions; -using Lidarr.Http.REST; namespace Lidarr.Api.V1.System.Backup { @@ -32,8 +30,8 @@ namespace Lidarr.Api.V1.System.Backup GetResourceAll = GetBackupFiles; DeleteResource = DeleteBackup; - Post(@"/restore/(?[\d]{1,10})", x => Restore((int)x.Id)); - Post("/restore/upload", x => UploadAndRestore()); + Post(@"/restore/(?[\d]{1,10})", x => Restore((int)x.Id)); + Post("/restore/upload", x => UploadAndRestore()); } public List GetBackupFiles() @@ -118,7 +116,6 @@ namespace Lidarr.Api.V1.System.Backup private string GetBackupPath(NzbDrone.Core.Backup.Backup backup) { return Path.Combine(_backupService.GetBackupFolder(backup.Type), backup.Name); - } private int GetBackupId(NzbDrone.Core.Backup.Backup backup) diff --git a/src/Lidarr.Api.V1/System/Backup/BackupResource.cs b/src/Lidarr.Api.V1/System/Backup/BackupResource.cs index cf5d895b1..1f8c71d4f 100644 --- a/src/Lidarr.Api.V1/System/Backup/BackupResource.cs +++ b/src/Lidarr.Api.V1/System/Backup/BackupResource.cs @@ -1,6 +1,6 @@ using System; -using NzbDrone.Core.Backup; using Lidarr.Http.REST; +using NzbDrone.Core.Backup; namespace Lidarr.Api.V1.System.Backup { diff --git a/src/Lidarr.Api.V1/System/SystemModule.cs b/src/Lidarr.Api.V1/System/SystemModule.cs index dfa625b08..e157063b1 100644 --- a/src/Lidarr.Api.V1/System/SystemModule.cs +++ b/src/Lidarr.Api.V1/System/SystemModule.cs @@ -1,12 +1,10 @@ using System.Threading.Tasks; -using Nancy; using Nancy.Routing; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Common.Extensions; using NzbDrone.Core.Configuration; using NzbDrone.Core.Datastore; using NzbDrone.Core.Lifecycle; -using Lidarr.Http.Extensions; namespace Lidarr.Api.V1.System { @@ -39,10 +37,10 @@ namespace Lidarr.Api.V1.System _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/Lidarr.Api.V1/System/Tasks/TaskModule.cs b/src/Lidarr.Api.V1/System/Tasks/TaskModule.cs index 819d341fc..924f1aef6 100644 --- a/src/Lidarr.Api.V1/System/Tasks/TaskModule.cs +++ b/src/Lidarr.Api.V1/System/Tasks/TaskModule.cs @@ -1,12 +1,11 @@ using System.Collections.Generic; using System.Linq; -using System.Text.RegularExpressions; +using Lidarr.Http; using NzbDrone.Common.Extensions; using NzbDrone.Core.Datastore.Events; using NzbDrone.Core.Jobs; using NzbDrone.Core.Messaging.Events; using NzbDrone.SignalR; -using Lidarr.Http; namespace Lidarr.Api.V1.System.Tasks { @@ -48,14 +47,14 @@ namespace Lidarr.Api.V1.System.Tasks 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, - NextExecution = scheduledTask.LastExecution.AddMinutes(scheduledTask.Interval) - }; + { + Id = scheduledTask.Id, + Name = taskName.SplitCamelCase(), + TaskName = taskName, + Interval = scheduledTask.Interval, + LastExecution = scheduledTask.LastExecution, + NextExecution = scheduledTask.LastExecution.AddMinutes(scheduledTask.Interval) + }; } public void Handle(CommandExecutedEvent message) diff --git a/src/Lidarr.Api.V1/Tags/TagDetailsModule.cs b/src/Lidarr.Api.V1/Tags/TagDetailsModule.cs index e89cd1815..e8a50d8aa 100644 --- a/src/Lidarr.Api.V1/Tags/TagDetailsModule.cs +++ b/src/Lidarr.Api.V1/Tags/TagDetailsModule.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -using NzbDrone.Core.Tags; using Lidarr.Http; +using NzbDrone.Core.Tags; namespace Lidarr.Api.V1.Tags { @@ -24,7 +24,7 @@ namespace Lidarr.Api.V1.Tags private List GetAll() { - var tags = _tagService.Details().ToResource(); + var tags = _tagService.Details().ToResource(); return tags; } diff --git a/src/Lidarr.Api.V1/Tags/TagDetailsResource.cs b/src/Lidarr.Api.V1/Tags/TagDetailsResource.cs index 4bd6b6619..c22b4e07e 100644 --- a/src/Lidarr.Api.V1/Tags/TagDetailsResource.cs +++ b/src/Lidarr.Api.V1/Tags/TagDetailsResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using NzbDrone.Core.Tags; using Lidarr.Http.REST; +using NzbDrone.Core.Tags; namespace Lidarr.Api.V1.Tags { @@ -19,7 +19,10 @@ namespace Lidarr.Api.V1.Tags { public static TagDetailsResource ToResource(this TagDetails model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new TagDetailsResource { diff --git a/src/Lidarr.Api.V1/Tags/TagModule.cs b/src/Lidarr.Api.V1/Tags/TagModule.cs index 43ab04b64..c0690c1ca 100644 --- a/src/Lidarr.Api.V1/Tags/TagModule.cs +++ b/src/Lidarr.Api.V1/Tags/TagModule.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; +using Lidarr.Http; using NzbDrone.Core.Datastore.Events; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Tags; using NzbDrone.SignalR; -using Lidarr.Http; namespace Lidarr.Api.V1.Tags { diff --git a/src/Lidarr.Api.V1/Tags/TagResource.cs b/src/Lidarr.Api.V1/Tags/TagResource.cs index 681453622..a1cf9f4b5 100644 --- a/src/Lidarr.Api.V1/Tags/TagResource.cs +++ b/src/Lidarr.Api.V1/Tags/TagResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using NzbDrone.Core.Tags; using Lidarr.Http.REST; +using NzbDrone.Core.Tags; namespace Lidarr.Api.V1.Tags { @@ -14,7 +14,10 @@ namespace Lidarr.Api.V1.Tags { public static TagResource ToResource(this Tag model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new TagResource { @@ -25,7 +28,10 @@ namespace Lidarr.Api.V1.Tags public static Tag ToModel(this TagResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new Tag { diff --git a/src/Lidarr.Api.V1/TrackFiles/MediaInfoResource.cs b/src/Lidarr.Api.V1/TrackFiles/MediaInfoResource.cs index 5ce4d42e3..bbbc29eb3 100644 --- a/src/Lidarr.Api.V1/TrackFiles/MediaInfoResource.cs +++ b/src/Lidarr.Api.V1/TrackFiles/MediaInfoResource.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.MediaFiles; using Lidarr.Http.REST; +using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Parser.Model; namespace Lidarr.Api.V1.TrackFiles @@ -23,13 +23,13 @@ namespace Lidarr.Api.V1.TrackFiles } return new MediaInfoResource - { - AudioChannels = MediaInfoFormatter.FormatAudioChannels(model), - AudioCodec = MediaInfoFormatter.FormatAudioCodec(model), - AudioBitRate = MediaInfoFormatter.FormatAudioBitrate(model), - AudioBits = MediaInfoFormatter.FormatAudioBitsPerSample(model), - AudioSampleRate = MediaInfoFormatter.FormatAudioSampleRate(model) - }; + { + AudioChannels = MediaInfoFormatter.FormatAudioChannels(model), + AudioCodec = MediaInfoFormatter.FormatAudioCodec(model), + AudioBitRate = MediaInfoFormatter.FormatAudioBitrate(model), + AudioBits = MediaInfoFormatter.FormatAudioBitsPerSample(model), + AudioSampleRate = MediaInfoFormatter.FormatAudioSampleRate(model) + }; } } } diff --git a/src/Lidarr.Api.V1/TrackFiles/TrackFileModule.cs b/src/Lidarr.Api.V1/TrackFiles/TrackFileModule.cs index c1810c644..e924744e2 100644 --- a/src/Lidarr.Api.V1/TrackFiles/TrackFileModule.cs +++ b/src/Lidarr.Api.V1/TrackFiles/TrackFileModule.cs @@ -1,17 +1,17 @@ using System; using System.Collections.Generic; using System.Linq; +using Lidarr.Http; +using Lidarr.Http.Extensions; using Nancy; using NzbDrone.Core.Datastore.Events; using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.Exceptions; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Music; using NzbDrone.SignalR; -using Lidarr.Http; -using Lidarr.Http.Extensions; -using NzbDrone.Core.Exceptions; using HttpStatusCode = System.Net.HttpStatusCode; namespace Lidarr.Api.V1.TrackFiles @@ -48,8 +48,8 @@ namespace Lidarr.Api.V1.TrackFiles UpdateResource = SetQuality; DeleteResource = DeleteTrackFile; - Put("/editor", trackFiles => SetQuality()); - Delete("/bulk", trackFiles => DeleteTrackFiles()); + Put("/editor", trackFiles => SetQuality()); + Delete("/bulk", trackFiles => DeleteTrackFiles()); } private TrackFileResource MapToResource(TrackFile trackFile) @@ -78,7 +78,7 @@ namespace Lidarr.Api.V1.TrackFiles var albumIdQuery = Request.Query.AlbumId; var unmappedQuery = Request.Query.Unmapped; - if (!artistIdQuery.HasValue && !trackFileIdsQuery.HasValue && !albumIdQuery.HasValue && !unmappedQuery.HasValue) + if (!artistIdQuery.HasValue && !trackFileIdsQuery.HasValue && !albumIdQuery.HasValue && !unmappedQuery.HasValue) { throw new Lidarr.Http.REST.BadRequestException("artistId, albumId, trackFileIds or unmapped must be provided"); } @@ -112,10 +112,9 @@ namespace Lidarr.Api.V1.TrackFiles var albumArtist = _artistService.GetArtist(album.ArtistId); result.AddRange(_mediaFileService.GetFilesByAlbum(album.Id).ConvertAll(f => f.ToResource(albumArtist, _upgradableSpecification))); } - + return result; } - else { string trackFileIdsValue = trackFileIdsQuery.Value.ToString(); @@ -152,8 +151,8 @@ namespace Lidarr.Api.V1.TrackFiles _mediaFileService.Update(trackFiles); - return ResponseWithCode(trackFiles.ConvertAll(f => f.ToResource(trackFiles.First().Artist.Value, _upgradableSpecification)) - , Nancy.HttpStatusCode.Accepted); + return ResponseWithCode(trackFiles.ConvertAll(f => f.ToResource(trackFiles.First().Artist.Value, _upgradableSpecification)), + Nancy.HttpStatusCode.Accepted); } private void DeleteTrackFile(int id) diff --git a/src/Lidarr.Api.V1/TrackFiles/TrackFileResource.cs b/src/Lidarr.Api.V1/TrackFiles/TrackFileResource.cs index 481980f75..fb3f3523d 100644 --- a/src/Lidarr.Api.V1/TrackFiles/TrackFileResource.cs +++ b/src/Lidarr.Api.V1/TrackFiles/TrackFileResource.cs @@ -1,11 +1,11 @@ using System; -using NzbDrone.Core.DecisionEngine.Specifications; -using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Qualities; +using System.Linq; using Lidarr.Http.REST; using NzbDrone.Common.Extensions; +using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Parser.Model; -using System.Linq; +using NzbDrone.Core.Qualities; namespace Lidarr.Api.V1.TrackFiles { @@ -42,7 +42,10 @@ namespace Lidarr.Api.V1.TrackFiles public static TrackFileResource ToResource(this TrackFile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new TrackFileResource { @@ -59,7 +62,10 @@ namespace Lidarr.Api.V1.TrackFiles public static TrackFileResource ToResource(this TrackFile model, NzbDrone.Core.Music.Artist artist, IUpgradableSpecification upgradableSpecification) { - if (model == null) return null; + if (model == null) + { + return null; + } return new TrackFileResource { diff --git a/src/Lidarr.Api.V1/Tracks/RenameTrackModule.cs b/src/Lidarr.Api.V1/Tracks/RenameTrackModule.cs index 2bf4cc538..5ecaa239f 100644 --- a/src/Lidarr.Api.V1/Tracks/RenameTrackModule.cs +++ b/src/Lidarr.Api.V1/Tracks/RenameTrackModule.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; -using NzbDrone.Core.MediaFiles; using Lidarr.Http; using Lidarr.Http.REST; +using NzbDrone.Core.MediaFiles; namespace Lidarr.Api.V1.Tracks { @@ -25,7 +25,6 @@ namespace Lidarr.Api.V1.Tracks { artistId = (int)Request.Query.ArtistId; } - else { throw new BadRequestException("artistId is missing"); diff --git a/src/Lidarr.Api.V1/Tracks/RenameTrackResource.cs b/src/Lidarr.Api.V1/Tracks/RenameTrackResource.cs index 9b76b8998..504d75426 100644 --- a/src/Lidarr.Api.V1/Tracks/RenameTrackResource.cs +++ b/src/Lidarr.Api.V1/Tracks/RenameTrackResource.cs @@ -18,7 +18,10 @@ namespace Lidarr.Api.V1.Tracks { public static RenameTrackResource ToResource(this NzbDrone.Core.MediaFiles.RenameTrackFilePreview model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new RenameTrackResource { diff --git a/src/Lidarr.Api.V1/Tracks/RetagTrackModule.cs b/src/Lidarr.Api.V1/Tracks/RetagTrackModule.cs index 1248d4215..6f1c00d27 100644 --- a/src/Lidarr.Api.V1/Tracks/RetagTrackModule.cs +++ b/src/Lidarr.Api.V1/Tracks/RetagTrackModule.cs @@ -34,7 +34,6 @@ namespace Lidarr.Api.V1.Tracks { throw new BadRequestException("One of artistId or albumId must be specified"); } - } } } diff --git a/src/Lidarr.Api.V1/Tracks/RetagTrackResource.cs b/src/Lidarr.Api.V1/Tracks/RetagTrackResource.cs index 62c5c9085..34766eb7c 100644 --- a/src/Lidarr.Api.V1/Tracks/RetagTrackResource.cs +++ b/src/Lidarr.Api.V1/Tracks/RetagTrackResource.cs @@ -10,7 +10,7 @@ namespace Lidarr.Api.V1.Tracks public string OldValue { get; set; } public string NewValue { get; set; } } - + public class RetagTrackResource : RestResource { public int ArtistId { get; set; } @@ -37,11 +37,12 @@ namespace Lidarr.Api.V1.Tracks TrackNumbers = model.TrackNumbers.ToList(), TrackFileId = model.TrackFileId, RelativePath = model.RelativePath, - Changes = model.Changes.Select(x => new TagDifference { - Field = x.Key, - OldValue = x.Value.Item1, - NewValue = x.Value.Item2 - }).ToList() + Changes = model.Changes.Select(x => new TagDifference + { + Field = x.Key, + OldValue = x.Value.Item1, + NewValue = x.Value.Item2 + }).ToList() }; } diff --git a/src/Lidarr.Api.V1/Tracks/TrackModule.cs b/src/Lidarr.Api.V1/Tracks/TrackModule.cs index c216c718b..911a25738 100644 --- a/src/Lidarr.Api.V1/Tracks/TrackModule.cs +++ b/src/Lidarr.Api.V1/Tracks/TrackModule.cs @@ -1,12 +1,11 @@ using System; using System.Collections.Generic; using System.Linq; +using Lidarr.Http.REST; using Nancy; using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Music; using NzbDrone.SignalR; -using Lidarr.Http.Extensions; -using Lidarr.Http.REST; namespace Lidarr.Api.V1.Tracks { diff --git a/src/Lidarr.Api.V1/Tracks/TrackModuleWithSignalR.cs b/src/Lidarr.Api.V1/Tracks/TrackModuleWithSignalR.cs index 014aa4027..906835231 100644 --- a/src/Lidarr.Api.V1/Tracks/TrackModuleWithSignalR.cs +++ b/src/Lidarr.Api.V1/Tracks/TrackModuleWithSignalR.cs @@ -1,15 +1,13 @@ using System.Collections.Generic; -using NzbDrone.Common.Extensions; +using Lidarr.Api.V1.Artist; +using Lidarr.Api.V1.TrackFiles; +using Lidarr.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.Music; using NzbDrone.SignalR; -using Lidarr.Api.V1.TrackFiles; -using Lidarr.Api.V1.Artist; -using Lidarr.Http; -using NzbDrone.Core.MediaFiles.Events; namespace Lidarr.Api.V1.Tracks { @@ -67,6 +65,7 @@ namespace Lidarr.Api.V1.Tracks { resource.Artist = artist.ToResource(); } + if (includeTrackFile && track.TrackFileId != 0) { resource.TrackFile = track.TrackFile.Value.ToResource(artist, _upgradableSpecification); @@ -93,6 +92,7 @@ namespace Lidarr.Api.V1.Tracks { resource.Artist = artist.ToResource(); } + if (includeTrackFile && tracks[i].TrackFileId != 0) { resource.TrackFile = tracks[i].TrackFile.Value.ToResource(artist, _upgradableSpecification); @@ -120,6 +120,5 @@ namespace Lidarr.Api.V1.Tracks BroadcastResourceChange(ModelAction.Updated, MapToResource(track, true, true)); } } - } } diff --git a/src/Lidarr.Api.V1/Tracks/TrackResource.cs b/src/Lidarr.Api.V1/Tracks/TrackResource.cs index d1ebac96e..a44f22b3f 100644 --- a/src/Lidarr.Api.V1/Tracks/TrackResource.cs +++ b/src/Lidarr.Api.V1/Tracks/TrackResource.cs @@ -1,11 +1,10 @@ -using System; using System.Collections.Generic; using System.Linq; +using Lidarr.Api.V1.Artist; +using Lidarr.Api.V1.TrackFiles; +using Lidarr.Http.REST; using Newtonsoft.Json; using NzbDrone.Core.Music; -using Lidarr.Api.V1.TrackFiles; -using Lidarr.Api.V1.Artist; -using Lidarr.Http.REST; namespace Lidarr.Api.V1.Tracks { @@ -35,7 +34,10 @@ namespace Lidarr.Api.V1.Tracks { public static TrackResource ToResource(this Track model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new TrackResource { @@ -57,7 +59,10 @@ namespace Lidarr.Api.V1.Tracks public static List ToResource(this IEnumerable models) { - if (models == null) return null; + if (models == null) + { + return null; + } return models.Select(ToResource).ToList(); } diff --git a/src/Lidarr.Api.V1/Update/UpdateModule.cs b/src/Lidarr.Api.V1/Update/UpdateModule.cs index 460559291..a878ae0d9 100644 --- a/src/Lidarr.Api.V1/Update/UpdateModule.cs +++ b/src/Lidarr.Api.V1/Update/UpdateModule.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; +using Lidarr.Http; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Core.Update; -using Lidarr.Http; namespace Lidarr.Api.V1.Update { @@ -43,4 +43,4 @@ namespace Lidarr.Api.V1.Update return resources; } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Api.V1/Update/UpdateResource.cs b/src/Lidarr.Api.V1/Update/UpdateResource.cs index e79a183f3..489ad1a74 100644 --- a/src/Lidarr.Api.V1/Update/UpdateResource.cs +++ b/src/Lidarr.Api.V1/Update/UpdateResource.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; +using Lidarr.Http.REST; using Newtonsoft.Json; using NzbDrone.Core.Update; -using Lidarr.Http.REST; namespace Lidarr.Api.V1.Update { @@ -27,7 +27,10 @@ namespace Lidarr.Api.V1.Update { public static UpdateResource ToResource(this UpdatePackage model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new UpdateResource { @@ -37,6 +40,7 @@ namespace Lidarr.Api.V1.Update ReleaseDate = model.ReleaseDate, FileName = model.FileName, Url = model.Url, + //Installed //Installable //Latest diff --git a/src/Lidarr.Api.V1/Wanted/CutoffModule.cs b/src/Lidarr.Api.V1/Wanted/CutoffModule.cs index a0a181969..4ea2d2146 100644 --- a/src/Lidarr.Api.V1/Wanted/CutoffModule.cs +++ b/src/Lidarr.Api.V1/Wanted/CutoffModule.cs @@ -1,13 +1,13 @@ using System.Linq; -using NzbDrone.Core.Datastore; -using NzbDrone.Core.DecisionEngine.Specifications; -using NzbDrone.Core.Music; -using NzbDrone.Core.ArtistStats; -using NzbDrone.SignalR; using Lidarr.Api.V1.Albums; using Lidarr.Http; using Lidarr.Http.Extensions; +using NzbDrone.Core.ArtistStats; +using NzbDrone.Core.Datastore; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.MediaCover; +using NzbDrone.Core.Music; +using NzbDrone.SignalR; namespace Lidarr.Api.V1.Wanted { diff --git a/src/Lidarr.Api.V1/Wanted/MissingModule.cs b/src/Lidarr.Api.V1/Wanted/MissingModule.cs index 1a6eb53df..5574c58dd 100644 --- a/src/Lidarr.Api.V1/Wanted/MissingModule.cs +++ b/src/Lidarr.Api.V1/Wanted/MissingModule.cs @@ -1,13 +1,13 @@ using System.Linq; -using NzbDrone.Core.Datastore; -using NzbDrone.Core.DecisionEngine.Specifications; -using NzbDrone.Core.Music; -using NzbDrone.Core.ArtistStats; -using NzbDrone.SignalR; using Lidarr.Api.V1.Albums; using Lidarr.Http; using Lidarr.Http.Extensions; +using NzbDrone.Core.ArtistStats; +using NzbDrone.Core.Datastore; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.MediaCover; +using NzbDrone.Core.Music; +using NzbDrone.SignalR; namespace Lidarr.Api.V1.Wanted { diff --git a/src/Lidarr.Http/Authentication/AuthenticationService.cs b/src/Lidarr.Http/Authentication/AuthenticationService.cs index a8945b717..5cdb756d2 100644 --- a/src/Lidarr.Http/Authentication/AuthenticationService.cs +++ b/src/Lidarr.Http/Authentication/AuthenticationService.cs @@ -2,6 +2,7 @@ using System.Linq; using System.Security.Claims; using System.Security.Principal; +using Lidarr.Http.Extensions; using Nancy; using Nancy.Authentication.Basic; using Nancy.Authentication.Forms; @@ -9,7 +10,6 @@ using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Core.Authentication; using NzbDrone.Core.Configuration; -using Lidarr.Http.Extensions; namespace Lidarr.Http.Authentication { @@ -25,15 +25,15 @@ namespace Lidarr.Http.Authentication 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; private static AuthenticationType AUTH_METHOD; [ThreadStatic] - private static NancyContext _context; + private static NancyContext _context; public AuthenticationService(IConfigFileProvider configFileProvider, IUserService userService) { @@ -170,14 +170,20 @@ namespace Lidarr.Http.Authentication 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/Lidarr.Http/Authentication/EnableAuthInNancy.cs b/src/Lidarr.Http/Authentication/EnableAuthInNancy.cs index 9e30f4ac6..632526406 100644 --- a/src/Lidarr.Http/Authentication/EnableAuthInNancy.cs +++ b/src/Lidarr.Http/Authentication/EnableAuthInNancy.cs @@ -1,17 +1,17 @@ using System; using System.Text; +using Lidarr.Http.Extensions; +using Lidarr.Http.Extensions.Pipelines; using Nancy; using Nancy.Authentication.Basic; using Nancy.Authentication.Forms; using Nancy.Bootstrapper; using Nancy.Cookies; using Nancy.Cryptography; +using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Common.Extensions; using NzbDrone.Core.Authentication; using NzbDrone.Core.Configuration; -using Lidarr.Http.Extensions; -using Lidarr.Http.Extensions.Pipelines; -using NzbDrone.Common.EnvironmentInfo; namespace Lidarr.Http.Authentication { @@ -20,7 +20,7 @@ namespace Lidarr.Http.Authentication private readonly IAuthenticationService _authenticationService; private readonly IConfigService _configService; private readonly IConfigFileProvider _configFileProvider; - private FormsAuthenticationConfiguration FormsAuthConfig; + private FormsAuthenticationConfiguration _formsAuthConfig; public EnableAuthInNancy(IAuthenticationService authenticationService, IConfigService configService, @@ -38,17 +38,16 @@ namespace Lidarr.Http.Authentication if (_configFileProvider.AuthenticationMethod == AuthenticationType.Forms) { RegisterFormsAuth(pipelines); - pipelines.AfterRequest.AddItemToEndOfPipeline((Action)SlidingAuthenticationForFormsAuth); + pipelines.AfterRequest.AddItemToEndOfPipeline(SlidingAuthenticationForFormsAuth); } - else if (_configFileProvider.AuthenticationMethod == AuthenticationType.Basic) { pipelines.EnableBasicAuthentication(new BasicAuthenticationConfiguration(_authenticationService, BuildInfo.AppName)); pipelines.BeforeRequest.AddItemToStartOfPipeline(CaptureContext); } - pipelines.BeforeRequest.AddItemToEndOfPipeline((Func)RequiresAuthentication); - pipelines.AfterRequest.AddItemToEndOfPipeline((Action)RemoveLoginHooksForApiCalls); + pipelines.BeforeRequest.AddItemToEndOfPipeline(RequiresAuthentication); + pipelines.AfterRequest.AddItemToEndOfPipeline(RemoveLoginHooksForApiCalls); } private Response CaptureContext(NancyContext context) @@ -58,7 +57,6 @@ namespace Lidarr.Http.Authentication return null; } - private Response RequiresAuthentication(NancyContext context) { Response response = null; @@ -78,10 +76,9 @@ namespace Lidarr.Http.Authentication 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, @@ -89,7 +86,7 @@ namespace Lidarr.Http.Authentication CryptographyConfiguration = cryptographyConfiguration }; - FormsAuthentication.Enable(pipelines, FormsAuthConfig); + FormsAuthentication.Enable(pipelines, _formsAuthConfig); } private void RemoveLoginHooksForApiCalls(NancyContext context) @@ -119,7 +116,7 @@ namespace Lidarr.Http.Authentication { 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/Lidarr.Http/ClientSchema/FieldMapping.cs b/src/Lidarr.Http/ClientSchema/FieldMapping.cs index e8ce91824..f3684f32d 100644 --- a/src/Lidarr.Http/ClientSchema/FieldMapping.cs +++ b/src/Lidarr.Http/ClientSchema/FieldMapping.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace Lidarr.Http.ClientSchema { diff --git a/src/Lidarr.Http/ClientSchema/SchemaBuilder.cs b/src/Lidarr.Http/ClientSchema/SchemaBuilder.cs index 771d5635c..98a7d04ef 100644 --- a/src/Lidarr.Http/ClientSchema/SchemaBuilder.cs +++ b/src/Lidarr.Http/ClientSchema/SchemaBuilder.cs @@ -49,7 +49,6 @@ namespace Lidarr.Http.ClientSchema } return target; - } public static T ReadFromSchema(List fields) @@ -57,7 +56,6 @@ namespace Lidarr.Http.ClientSchema 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) @@ -77,6 +75,7 @@ namespace Lidarr.Http.ClientSchema _mappings[type] = result; } + return result; } } @@ -155,32 +154,26 @@ namespace Lidarr.Http.ClientSchema { 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)) { return fieldValue => @@ -195,7 +188,6 @@ namespace Lidarr.Http.ClientSchema } }; } - else if (propertyType == typeof(IEnumerable)) { return fieldValue => @@ -210,7 +202,6 @@ namespace Lidarr.Http.ClientSchema } }; } - else { return fieldValue => fieldValue; @@ -219,7 +210,7 @@ namespace Lidarr.Http.ClientSchema 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/Lidarr.Http/ErrorManagement/ErrorHandler.cs b/src/Lidarr.Http/ErrorManagement/ErrorHandler.cs index df119a09b..ea371975d 100644 --- a/src/Lidarr.Http/ErrorManagement/ErrorHandler.cs +++ b/src/Lidarr.Http/ErrorManagement/ErrorHandler.cs @@ -1,6 +1,6 @@ -using Nancy; +using Lidarr.Http.Extensions; +using Nancy; using Nancy.ErrorHandling; -using Lidarr.Http.Extensions; namespace Lidarr.Http.ErrorManagement { diff --git a/src/Lidarr.Http/ErrorManagement/ErrorModel.cs b/src/Lidarr.Http/ErrorManagement/ErrorModel.cs index cc2b95562..04284f2a5 100644 --- a/src/Lidarr.Http/ErrorManagement/ErrorModel.cs +++ b/src/Lidarr.Http/ErrorManagement/ErrorModel.cs @@ -18,4 +18,4 @@ namespace Lidarr.Http.ErrorManagement { } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Http/ErrorManagement/LidarrErrorPipeline.cs b/src/Lidarr.Http/ErrorManagement/LidarrErrorPipeline.cs index e166559ef..abb06f842 100644 --- a/src/Lidarr.Http/ErrorManagement/LidarrErrorPipeline.cs +++ b/src/Lidarr.Http/ErrorManagement/LidarrErrorPipeline.cs @@ -1,12 +1,12 @@ using System; using System.Data.SQLite; using FluentValidation; +using Lidarr.Http.Exceptions; +using Lidarr.Http.Extensions; using Nancy; using NLog; using NzbDrone.Core.Datastore; using NzbDrone.Core.Exceptions; -using Lidarr.Http.Exceptions; -using Lidarr.Http.Extensions; using HttpStatusCode = Nancy.HttpStatusCode; namespace Lidarr.Http.ErrorManagement @@ -69,10 +69,12 @@ namespace Lidarr.Http.ErrorManagement 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/Lidarr.Http/Exceptions/ApiException.cs b/src/Lidarr.Http/Exceptions/ApiException.cs index 37537c34d..9b7f56f95 100644 --- a/src/Lidarr.Http/Exceptions/ApiException.cs +++ b/src/Lidarr.Http/Exceptions/ApiException.cs @@ -1,9 +1,8 @@ using System; -using Nancy; -using Nancy.Responses; using Lidarr.Http.ErrorManagement; using Lidarr.Http.Extensions; -using Nancy.Configuration; +using Nancy; +using Nancy.Responses; namespace Lidarr.Http.Exceptions { diff --git a/src/Lidarr.Http/Exceptions/InvalidApiKeyException.cs b/src/Lidarr.Http/Exceptions/InvalidApiKeyException.cs index 067f0ccc4..6bc2e8afa 100644 --- a/src/Lidarr.Http/Exceptions/InvalidApiKeyException.cs +++ b/src/Lidarr.Http/Exceptions/InvalidApiKeyException.cs @@ -8,7 +8,8 @@ namespace Lidarr.Http.Exceptions { } - public InvalidApiKeyException(string message) : base(message) + public InvalidApiKeyException(string message) + : base(message) { } } diff --git a/src/Lidarr.Http/Extensions/Pipelines/CacheHeaderPipeline.cs b/src/Lidarr.Http/Extensions/Pipelines/CacheHeaderPipeline.cs index 13a1e824e..96068e149 100644 --- a/src/Lidarr.Http/Extensions/Pipelines/CacheHeaderPipeline.cs +++ b/src/Lidarr.Http/Extensions/Pipelines/CacheHeaderPipeline.cs @@ -1,7 +1,7 @@ using System; +using Lidarr.Http.Frontend; using Nancy; using Nancy.Bootstrapper; -using Lidarr.Http.Frontend; namespace Lidarr.Http.Extensions.Pipelines { @@ -18,12 +18,15 @@ namespace Lidarr.Http.Extensions.Pipelines public void Register(IPipelines pipelines) { - pipelines.AfterRequest.AddItemToStartOfPipeline((Action) Handle); + pipelines.AfterRequest.AddItemToStartOfPipeline(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/Lidarr.Http/Extensions/Pipelines/CorsPipeline.cs b/src/Lidarr.Http/Extensions/Pipelines/CorsPipeline.cs index 3e21c3221..10d47e738 100644 --- a/src/Lidarr.Http/Extensions/Pipelines/CorsPipeline.cs +++ b/src/Lidarr.Http/Extensions/Pipelines/CorsPipeline.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using Nancy; using Nancy.Bootstrapper; diff --git a/src/Lidarr.Http/Extensions/Pipelines/GZipPipeline.cs b/src/Lidarr.Http/Extensions/Pipelines/GZipPipeline.cs index a26c368c3..5e19f9c7d 100644 --- a/src/Lidarr.Http/Extensions/Pipelines/GZipPipeline.cs +++ b/src/Lidarr.Http/Extensions/Pipelines/GZipPipeline.cs @@ -51,7 +51,6 @@ namespace Lidarr.Http.Extensions.Pipelines response.Contents = responseStream => _writeGZipStream(contents, responseStream); } } - catch (Exception ex) { _logger.Error(ex, "Unable to gzip response"); diff --git a/src/Lidarr.Http/Extensions/Pipelines/IRegisterNancyPipeline.cs b/src/Lidarr.Http/Extensions/Pipelines/IRegisterNancyPipeline.cs index 84105c46b..4177699a3 100644 --- a/src/Lidarr.Http/Extensions/Pipelines/IRegisterNancyPipeline.cs +++ b/src/Lidarr.Http/Extensions/Pipelines/IRegisterNancyPipeline.cs @@ -8,4 +8,4 @@ namespace Lidarr.Http.Extensions.Pipelines void Register(IPipelines pipelines); } -} \ No newline at end of file +} diff --git a/src/Lidarr.Http/Extensions/Pipelines/IfModifiedPipeline.cs b/src/Lidarr.Http/Extensions/Pipelines/IfModifiedPipeline.cs index cf619745d..98a26c128 100644 --- a/src/Lidarr.Http/Extensions/Pipelines/IfModifiedPipeline.cs +++ b/src/Lidarr.Http/Extensions/Pipelines/IfModifiedPipeline.cs @@ -1,7 +1,7 @@ using System; +using Lidarr.Http.Frontend; using Nancy; using Nancy.Bootstrapper; -using Lidarr.Http.Frontend; namespace Lidarr.Http.Extensions.Pipelines { @@ -18,7 +18,7 @@ namespace Lidarr.Http.Extensions.Pipelines public void Register(IPipelines pipelines) { - pipelines.BeforeRequest.AddItemToStartOfPipeline((Func) Handle); + pipelines.BeforeRequest.AddItemToStartOfPipeline(Handle); } private Response Handle(NancyContext context) @@ -33,4 +33,4 @@ namespace Lidarr.Http.Extensions.Pipelines return null; } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Http/Extensions/Pipelines/LidarrVersionPipeline.cs b/src/Lidarr.Http/Extensions/Pipelines/LidarrVersionPipeline.cs index 1a425031d..4a647325a 100644 --- a/src/Lidarr.Http/Extensions/Pipelines/LidarrVersionPipeline.cs +++ b/src/Lidarr.Http/Extensions/Pipelines/LidarrVersionPipeline.cs @@ -11,7 +11,7 @@ namespace Lidarr.Http.Extensions.Pipelines public void Register(IPipelines pipelines) { - pipelines.AfterRequest.AddItemToStartOfPipeline((Action) Handle); + pipelines.AfterRequest.AddItemToStartOfPipeline(Handle); } private void Handle(NancyContext context) diff --git a/src/Lidarr.Http/Extensions/Pipelines/RequestLoggingPipeline.cs b/src/Lidarr.Http/Extensions/Pipelines/RequestLoggingPipeline.cs index 34d40cd5a..53353b6d4 100644 --- a/src/Lidarr.Http/Extensions/Pipelines/RequestLoggingPipeline.cs +++ b/src/Lidarr.Http/Extensions/Pipelines/RequestLoggingPipeline.cs @@ -1,12 +1,12 @@ using System; using System.Threading; +using Lidarr.Http.ErrorManagement; +using Lidarr.Http.Extensions; +using Lidarr.Http.Extensions.Pipelines; using Nancy; using Nancy.Bootstrapper; using NLog; using NzbDrone.Common.Extensions; -using Lidarr.Http.ErrorManagement; -using Lidarr.Http.Extensions; -using Lidarr.Http.Extensions.Pipelines; namespace NzbDrone.Api.Extensions.Pipelines { diff --git a/src/Lidarr.Http/Extensions/Pipelines/UrlBasePipeline.cs b/src/Lidarr.Http/Extensions/Pipelines/UrlBasePipeline.cs index 85793213f..71ed358af 100644 --- a/src/Lidarr.Http/Extensions/Pipelines/UrlBasePipeline.cs +++ b/src/Lidarr.Http/Extensions/Pipelines/UrlBasePipeline.cs @@ -22,7 +22,7 @@ namespace Lidarr.Http.Extensions.Pipelines { if (_urlBase.IsNotNullOrWhiteSpace()) { - pipelines.BeforeRequest.AddItemToStartOfPipeline((Func) Handle); + pipelines.BeforeRequest.AddItemToStartOfPipeline(Handle); } } diff --git a/src/Lidarr.Http/Extensions/ReqResExtensions.cs b/src/Lidarr.Http/Extensions/ReqResExtensions.cs index 3f387d95f..6c12b3cbd 100644 --- a/src/Lidarr.Http/Extensions/ReqResExtensions.cs +++ b/src/Lidarr.Http/Extensions/ReqResExtensions.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using System.IO; using Nancy; -using Nancy.Configuration; using Nancy.Responses; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Common.Serializer; @@ -15,7 +14,8 @@ namespace Lidarr.Http.Extensions public static readonly string LastModified = BuildInfo.BuildDateTime.ToString("r"); - public static T FromJson(this Stream body) where T : class, new() + public static T FromJson(this Stream body) + where T : class, new() { return FromJson(body, typeof(T)); } diff --git a/src/Lidarr.Http/Extensions/RequestExtensions.cs b/src/Lidarr.Http/Extensions/RequestExtensions.cs index 08ac6867c..e0da3fb80 100644 --- a/src/Lidarr.Http/Extensions/RequestExtensions.cs +++ b/src/Lidarr.Http/Extensions/RequestExtensions.cs @@ -22,9 +22,9 @@ namespace Lidarr.Http.Extensions 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/Lidarr.Http/Frontend/CacheableSpecification.cs b/src/Lidarr.Http/Frontend/CacheableSpecification.cs index 0d85374d2..b5a4d74df 100644 --- a/src/Lidarr.Http/Frontend/CacheableSpecification.cs +++ b/src/Lidarr.Http/Frontend/CacheableSpecification.cs @@ -19,19 +19,40 @@ namespace Lidarr.Http.Frontend 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 @@ namespace Lidarr.Http.Frontend 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/Lidarr.Http/Frontend/InitializeJsModule.cs b/src/Lidarr.Http/Frontend/InitializeJsModule.cs index 6a9710b45..4231a20fe 100644 --- a/src/Lidarr.Http/Frontend/InitializeJsModule.cs +++ b/src/Lidarr.Http/Frontend/InitializeJsModule.cs @@ -18,7 +18,6 @@ namespace Lidarr.Http.Frontend private static string _urlBase; private string _generatedContent; - public InitializeJsModule(IConfigFileProvider configFileProvider, IAnalyticsService analyticsService) { @@ -44,7 +43,6 @@ namespace Lidarr.Http.Frontend var stream = new MemoryStream(); var writer = new StreamWriter(stream); - writer.Write(text); writer.Flush(); stream.Position = 0; diff --git a/src/Lidarr.Http/Frontend/Mappers/BrowserConfig.cs b/src/Lidarr.Http/Frontend/Mappers/BrowserConfig.cs index 4d7bb0808..25d07037a 100644 --- a/src/Lidarr.Http/Frontend/Mappers/BrowserConfig.cs +++ b/src/Lidarr.Http/Frontend/Mappers/BrowserConfig.cs @@ -31,4 +31,4 @@ namespace Lidarr.Http.Frontend.Mappers return resourceUrl.StartsWith("/Content/Images/Icons/browserconfig"); } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Http/Frontend/Mappers/CacheBreakerProvider.cs b/src/Lidarr.Http/Frontend/Mappers/CacheBreakerProvider.cs index f165594a8..bb925b77e 100644 --- a/src/Lidarr.Http/Frontend/Mappers/CacheBreakerProvider.cs +++ b/src/Lidarr.Http/Frontend/Mappers/CacheBreakerProvider.cs @@ -40,4 +40,4 @@ namespace Lidarr.Http.Frontend.Mappers return !path.EndsWith(".ics") && !path.EndsWith("main"); } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Http/Frontend/Mappers/FaviconMapper.cs b/src/Lidarr.Http/Frontend/Mappers/FaviconMapper.cs index c269fa1b3..8afc3bf40 100644 --- a/src/Lidarr.Http/Frontend/Mappers/FaviconMapper.cs +++ b/src/Lidarr.Http/Frontend/Mappers/FaviconMapper.cs @@ -11,7 +11,7 @@ namespace Lidarr.Http.Frontend.Mappers 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; @@ -37,4 +37,4 @@ namespace Lidarr.Http.Frontend.Mappers return resourceUrl.Equals("/favicon.ico"); } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Http/Frontend/Mappers/HtmlMapperBase.cs b/src/Lidarr.Http/Frontend/Mappers/HtmlMapperBase.cs index aac46ce45..8bb7e70d5 100644 --- a/src/Lidarr.Http/Frontend/Mappers/HtmlMapperBase.cs +++ b/src/Lidarr.Http/Frontend/Mappers/HtmlMapperBase.cs @@ -18,7 +18,8 @@ namespace Lidarr.Http.Frontend.Mappers protected HtmlMapperBase(IDiskProvider diskProvider, Func cacheBreakProviderFactory, - Logger logger) : base(diskProvider, logger) + Logger logger) + : base(diskProvider, logger) { _diskProvider = diskProvider; _cacheBreakProviderFactory = cacheBreakProviderFactory; @@ -65,7 +66,6 @@ namespace Lidarr.Http.Frontend.Mappers { url = match.Groups["path"].Value; } - else { url = cacheBreakProvider.AddCacheBreakerToPath(match.Groups["path"].Value); diff --git a/src/Lidarr.Http/Frontend/Mappers/IMapHttpRequestsToDisk.cs b/src/Lidarr.Http/Frontend/Mappers/IMapHttpRequestsToDisk.cs index 1bfd458ad..a66984d79 100644 --- a/src/Lidarr.Http/Frontend/Mappers/IMapHttpRequestsToDisk.cs +++ b/src/Lidarr.Http/Frontend/Mappers/IMapHttpRequestsToDisk.cs @@ -1,5 +1,4 @@ - -using Nancy; +using Nancy; namespace Lidarr.Http.Frontend.Mappers { diff --git a/src/Lidarr.Http/Frontend/Mappers/IndexHtmlMapper.cs b/src/Lidarr.Http/Frontend/Mappers/IndexHtmlMapper.cs index 938553a18..4a22c3dd5 100644 --- a/src/Lidarr.Http/Frontend/Mappers/IndexHtmlMapper.cs +++ b/src/Lidarr.Http/Frontend/Mappers/IndexHtmlMapper.cs @@ -37,7 +37,6 @@ namespace Lidarr.Http.Frontend.Mappers !resourceUrl.StartsWith("/mediacover") && !resourceUrl.Contains(".") && !resourceUrl.StartsWith("/login"); - } } } diff --git a/src/Lidarr.Http/Frontend/Mappers/LogFileMapper.cs b/src/Lidarr.Http/Frontend/Mappers/LogFileMapper.cs index c6f73732f..9ed755e96 100644 --- a/src/Lidarr.Http/Frontend/Mappers/LogFileMapper.cs +++ b/src/Lidarr.Http/Frontend/Mappers/LogFileMapper.cs @@ -29,4 +29,4 @@ namespace Lidarr.Http.Frontend.Mappers return resourceUrl.StartsWith("/updatelogfile/") && resourceUrl.EndsWith(".txt"); } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Http/Frontend/Mappers/LoginHtmlMapper.cs b/src/Lidarr.Http/Frontend/Mappers/LoginHtmlMapper.cs index da80817ee..30499d270 100644 --- a/src/Lidarr.Http/Frontend/Mappers/LoginHtmlMapper.cs +++ b/src/Lidarr.Http/Frontend/Mappers/LoginHtmlMapper.cs @@ -1,6 +1,5 @@ using System; using System.IO; -using Nancy; using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.EnvironmentInfo; diff --git a/src/Lidarr.Http/Frontend/Mappers/ManifestMapper.cs b/src/Lidarr.Http/Frontend/Mappers/ManifestMapper.cs index 92afc08ca..dbb9a082c 100644 --- a/src/Lidarr.Http/Frontend/Mappers/ManifestMapper.cs +++ b/src/Lidarr.Http/Frontend/Mappers/ManifestMapper.cs @@ -31,4 +31,4 @@ namespace Lidarr.Http.Frontend.Mappers return resourceUrl.StartsWith("/Content/Images/Icons/manifest"); } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Http/Frontend/Mappers/StaticResourceMapperBase.cs b/src/Lidarr.Http/Frontend/Mappers/StaticResourceMapperBase.cs index 96307eae7..f6216a415 100644 --- a/src/Lidarr.Http/Frontend/Mappers/StaticResourceMapperBase.cs +++ b/src/Lidarr.Http/Frontend/Mappers/StaticResourceMapperBase.cs @@ -47,6 +47,5 @@ namespace Lidarr.Http.Frontend.Mappers { return File.OpenRead(filePath); } - } } diff --git a/src/Lidarr.Http/Frontend/Mappers/UpdateLogFileMapper.cs b/src/Lidarr.Http/Frontend/Mappers/UpdateLogFileMapper.cs index 13fe24b58..88644438d 100644 --- a/src/Lidarr.Http/Frontend/Mappers/UpdateLogFileMapper.cs +++ b/src/Lidarr.Http/Frontend/Mappers/UpdateLogFileMapper.cs @@ -29,4 +29,4 @@ namespace Lidarr.Http.Frontend.Mappers return resourceUrl.StartsWith("/logfile/") && resourceUrl.EndsWith(".txt"); } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Http/Frontend/StaticResourceModule.cs b/src/Lidarr.Http/Frontend/StaticResourceModule.cs index 0c3b38037..e32c47b3d 100644 --- a/src/Lidarr.Http/Frontend/StaticResourceModule.cs +++ b/src/Lidarr.Http/Frontend/StaticResourceModule.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; +using Lidarr.Http.Frontend.Mappers; using Nancy; using NLog; -using Lidarr.Http.Frontend.Mappers; namespace Lidarr.Http.Frontend { @@ -12,7 +12,6 @@ namespace Lidarr.Http.Frontend private readonly IEnumerable _requestMappers; private readonly Logger _logger; - public StaticResourceModule(IEnumerable requestMappers, Logger logger) { _requestMappers = requestMappers; diff --git a/src/Lidarr.Http/LidarrBootstrapper.cs b/src/Lidarr.Http/LidarrBootstrapper.cs index 5368808a0..62506a51a 100644 --- a/src/Lidarr.Http/LidarrBootstrapper.cs +++ b/src/Lidarr.Http/LidarrBootstrapper.cs @@ -1,15 +1,15 @@ +using System; using System.Linq; +using Lidarr.Http.Extensions.Pipelines; +using Nancy; using Nancy.Bootstrapper; using Nancy.Diagnostics; +using Nancy.Responses.Negotiation; using NLog; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Common.Instrumentation; using NzbDrone.Core.Instrumentation; -using Lidarr.Http.Extensions.Pipelines; using TinyIoC; -using Nancy; -using System; -using Nancy.Responses.Negotiation; namespace Lidarr.Http { @@ -57,7 +57,8 @@ namespace Lidarr.Http 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/Lidarr.Http/LidarrRestModule.cs b/src/Lidarr.Http/LidarrRestModule.cs index 798565022..1984a5e0f 100644 --- a/src/Lidarr.Http/LidarrRestModule.cs +++ b/src/Lidarr.Http/LidarrRestModule.cs @@ -1,15 +1,15 @@ using System; -using NzbDrone.Core.Datastore; using Lidarr.Http.REST; using Lidarr.Http.Validation; +using NzbDrone.Core.Datastore; namespace Lidarr.Http { - public abstract class LidarrRestModule : RestModule where TResource : RestResource, new() + public abstract class LidarrRestModule : RestModule + where TResource : RestResource, new() { protected string Resource { get; private set; } - private static string BaseUrl() { var isV1 = typeof(TResource).Namespace.Contains(".V1."); @@ -17,6 +17,7 @@ namespace Lidarr.Http { return "/api/v1/"; } + return "/api/"; } diff --git a/src/Lidarr.Http/LidarrRestModuleWithSignalR.cs b/src/Lidarr.Http/LidarrRestModuleWithSignalR.cs index 5905930d3..0074da5cd 100644 --- a/src/Lidarr.Http/LidarrRestModuleWithSignalR.cs +++ b/src/Lidarr.Http/LidarrRestModuleWithSignalR.cs @@ -1,8 +1,8 @@ +using Lidarr.Http.REST; using NzbDrone.Core.Datastore; using NzbDrone.Core.Datastore.Events; using NzbDrone.Core.Messaging.Events; using NzbDrone.SignalR; -using Lidarr.Http.REST; namespace Lidarr.Http { @@ -25,7 +25,10 @@ namespace Lidarr.Http public void Handle(ModelEvent message) { - if (!_signalRBroadcaster.IsConnected) return; + if (!_signalRBroadcaster.IsConnected) + { + return; + } if (message.Action == ModelAction.Deleted || message.Action == ModelAction.Sync) { @@ -37,7 +40,10 @@ namespace Lidarr.Http protected void BroadcastResourceChange(ModelAction action, int id) { - if (!_signalRBroadcaster.IsConnected) return; + if (!_signalRBroadcaster.IsConnected) + { + return; + } if (action == ModelAction.Deleted) { @@ -52,7 +58,10 @@ namespace Lidarr.Http protected void BroadcastResourceChange(ModelAction action, TResource resource) { - if (!_signalRBroadcaster.IsConnected) return; + if (!_signalRBroadcaster.IsConnected) + { + return; + } if (GetType().Namespace.Contains("V1")) { @@ -67,10 +76,12 @@ namespace Lidarr.Http } } - protected void BroadcastResourceChange(ModelAction action) { - if (!_signalRBroadcaster.IsConnected) return; + if (!_signalRBroadcaster.IsConnected) + { + return; + } if (GetType().Namespace.Contains("V1")) { diff --git a/src/Lidarr.Http/Mapping/MappingValidation.cs b/src/Lidarr.Http/Mapping/MappingValidation.cs index e4f056520..af5a1da85 100644 --- a/src/Lidarr.Http/Mapping/MappingValidation.cs +++ b/src/Lidarr.Http/Mapping/MappingValidation.cs @@ -1,8 +1,8 @@ using System; using System.Linq; using System.Reflection; -using NzbDrone.Common.Reflection; using Lidarr.Http.REST; +using NzbDrone.Common.Reflection; namespace Lidarr.Http.Mapping { @@ -10,7 +10,7 @@ namespace Lidarr.Http.Mapping { 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()) { @@ -51,4 +51,4 @@ namespace Lidarr.Http.Mapping return null; } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Http/Mapping/ResourceMappingException.cs b/src/Lidarr.Http/Mapping/ResourceMappingException.cs index 3744d3d5e..aace10ac4 100644 --- a/src/Lidarr.Http/Mapping/ResourceMappingException.cs +++ b/src/Lidarr.Http/Mapping/ResourceMappingException.cs @@ -9,7 +9,6 @@ namespace Lidarr.Http.Mapping public ResourceMappingException(IEnumerable error) : base(Environment.NewLine + string.Join(Environment.NewLine, error.OrderBy(c => c))) { - } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Http/PagingResource.cs b/src/Lidarr.Http/PagingResource.cs index e123eba69..ee6f0b95c 100644 --- a/src/Lidarr.Http/PagingResource.cs +++ b/src/Lidarr.Http/PagingResource.cs @@ -29,7 +29,7 @@ namespace Lidarr.Http if (pagingResource.SortKey == null) { pagingSpec.SortKey = defaultSortKey; - if(pagingResource.SortDirection == SortDirection.Default) + if (pagingResource.SortDirection == SortDirection.Default) { pagingSpec.SortDirection = defaultSortDirection; } diff --git a/src/Lidarr.Http/REST/BadRequestException.cs b/src/Lidarr.Http/REST/BadRequestException.cs index 5f61a1d49..4502935c7 100644 --- a/src/Lidarr.Http/REST/BadRequestException.cs +++ b/src/Lidarr.Http/REST/BadRequestException.cs @@ -1,5 +1,5 @@ -using Nancy; -using Lidarr.Http.Exceptions; +using Lidarr.Http.Exceptions; +using Nancy; namespace Lidarr.Http.REST { @@ -10,4 +10,4 @@ namespace Lidarr.Http.REST { } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Http/REST/MethodNotAllowedException.cs b/src/Lidarr.Http/REST/MethodNotAllowedException.cs index e9dc7b74c..b5fca7776 100644 --- a/src/Lidarr.Http/REST/MethodNotAllowedException.cs +++ b/src/Lidarr.Http/REST/MethodNotAllowedException.cs @@ -1,5 +1,5 @@ -using Nancy; -using Lidarr.Http.Exceptions; +using Lidarr.Http.Exceptions; +using Nancy; namespace Lidarr.Http.REST { diff --git a/src/Lidarr.Http/REST/NotFoundException.cs b/src/Lidarr.Http/REST/NotFoundException.cs index e8377ced4..edf4bf8e3 100644 --- a/src/Lidarr.Http/REST/NotFoundException.cs +++ b/src/Lidarr.Http/REST/NotFoundException.cs @@ -1,5 +1,5 @@ -using Nancy; -using Lidarr.Http.Exceptions; +using Lidarr.Http.Exceptions; +using Nancy; namespace Lidarr.Http.REST { @@ -10,4 +10,4 @@ namespace Lidarr.Http.REST { } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Http/REST/ResourceValidator.cs b/src/Lidarr.Http/REST/ResourceValidator.cs index c97caed28..6ead3ab48 100644 --- a/src/Lidarr.Http/REST/ResourceValidator.cs +++ b/src/Lidarr.Http/REST/ResourceValidator.cs @@ -23,7 +23,6 @@ namespace Lidarr.Http.REST private static object GetValue(object container, Func> fieldListAccessor, string fieldName) { - var resource = fieldListAccessor((TResource)container).SingleOrDefault(c => c.Name == fieldName); if (resource == null) @@ -34,4 +33,4 @@ namespace Lidarr.Http.REST return resource.Value; } } -} \ No newline at end of file +} diff --git a/src/Lidarr.Http/REST/RestModule.cs b/src/Lidarr.Http/REST/RestModule.cs index d2c40a68a..41584aaf3 100644 --- a/src/Lidarr.Http/REST/RestModule.cs +++ b/src/Lidarr.Http/REST/RestModule.cs @@ -2,11 +2,11 @@ using System; using System.Collections.Generic; using System.Linq; using FluentValidation; -using Nancy; -using NzbDrone.Core.Datastore; using Lidarr.Http.Extensions; -using Newtonsoft.Json; +using Nancy; using Nancy.Responses.Negotiation; +using Newtonsoft.Json; +using NzbDrone.Core.Datastore; namespace Lidarr.Http.REST { @@ -16,7 +16,7 @@ namespace Lidarr.Http.REST private const string ROOT_ROUTE = "/"; private const string ID_ROUTE = @"/(?[\d]{1,10})"; - private HashSet EXCLUDED_KEYS = new HashSet(StringComparer.InvariantCultureIgnoreCase) + private readonly HashSet _excludedKeys = new HashSet(StringComparer.InvariantCultureIgnoreCase) { "page", "pageSize", @@ -56,10 +56,12 @@ namespace Lidarr.Http.REST SharedValidator = new ResourceValidator(); } - private void ValidateModule() { - if (GetResourceById != null) return; + if (GetResourceById != null) + { + return; + } if (CreateResource != null || UpdateResource != null) { @@ -69,7 +71,11 @@ namespace Lidarr.Http.REST protected Action DeleteResource { - private get { return _deleteResource; } + private get + { + return _deleteResource; + } + set { _deleteResource = value; @@ -85,7 +91,11 @@ namespace Lidarr.Http.REST protected Func GetResourceById { - get { return _getResourceById; } + get + { + return _getResourceById; + } + set { _getResourceById = value; @@ -113,11 +123,14 @@ namespace Lidarr.Http.REST protected Func> GetResourceAll { - private get { return _getResourceAll; } + private get + { + return _getResourceAll; + } + set { _getResourceAll = value; - Get(ROOT_ROUTE, options => { var resource = GetResourceAll(); @@ -128,11 +141,14 @@ namespace Lidarr.Http.REST protected Func, PagingResource> GetResourcePaged { - private get { return _getResourcePaged; } + private get + { + return _getResourcePaged; + } + set { _getResourcePaged = value; - Get(ROOT_ROUTE, options => { var resource = GetResourcePaged(ReadPagingResourceFromRequest()); @@ -143,11 +159,14 @@ namespace Lidarr.Http.REST protected Func GetResourceSingle { - private get { return _getResourceSingle; } + private get + { + return _getResourceSingle; + } + set { _getResourceSingle = value; - Get(ROOT_ROUTE, options => { var resource = GetResourceSingle(); @@ -158,7 +177,11 @@ namespace Lidarr.Http.REST protected Func CreateResource { - private get { return _createResource; } + private get + { + return _createResource; + } + set { _createResource = value; @@ -167,13 +190,16 @@ namespace Lidarr.Http.REST var id = CreateResource(ReadResourceFromRequest()); return ResponseWithCode(GetResourceById(id), HttpStatusCode.Created); }); - } } protected Action UpdateResource { - private get { return _updateResource; } + private get + { + return _updateResource; + } + set { _updateResource = value; @@ -183,7 +209,6 @@ namespace Lidarr.Http.REST UpdateResource(resource); return ResponseWithCode(GetResourceById(resource.Id), HttpStatusCode.Accepted); }); - Put(ID_ROUTE, options => { var resource = ReadResourceFromRequest(); @@ -240,12 +265,17 @@ namespace Lidarr.Http.REST { 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 { @@ -294,10 +324,9 @@ namespace Lidarr.Http.REST } // v3 uses filters in key=value format - foreach (var key in Request.Query) { - if (EXCLUDED_KEYS.Contains(key)) + if (_excludedKeys.Contains(key)) { continue; } diff --git a/src/Lidarr.Http/REST/RestResource.cs b/src/Lidarr.Http/REST/RestResource.cs index b08aa6eef..39742997e 100644 --- a/src/Lidarr.Http/REST/RestResource.cs +++ b/src/Lidarr.Http/REST/RestResource.cs @@ -10,4 +10,4 @@ namespace Lidarr.Http.REST [JsonIgnore] public virtual string ResourceName => GetType().Name.ToLowerInvariant().Replace("resource", ""); } -} \ No newline at end of file +} diff --git a/src/Lidarr.Http/REST/UnsupportedMediaTypeException.cs b/src/Lidarr.Http/REST/UnsupportedMediaTypeException.cs index 6755a51c3..e13190cc7 100644 --- a/src/Lidarr.Http/REST/UnsupportedMediaTypeException.cs +++ b/src/Lidarr.Http/REST/UnsupportedMediaTypeException.cs @@ -1,5 +1,5 @@ -using Nancy; using Lidarr.Http.Exceptions; +using Nancy; namespace Lidarr.Http.REST { diff --git a/src/Lidarr.Http/ResourceChangeMessage.cs b/src/Lidarr.Http/ResourceChangeMessage.cs index 3d2e67c78..0edf506c7 100644 --- a/src/Lidarr.Http/ResourceChangeMessage.cs +++ b/src/Lidarr.Http/ResourceChangeMessage.cs @@ -1,10 +1,11 @@ using System; -using NzbDrone.Core.Datastore.Events; using Lidarr.Http.REST; +using NzbDrone.Core.Datastore.Events; namespace Lidarr.Http { - public class ResourceChangeMessage where TResource : RestResource + public class ResourceChangeMessage + where TResource : RestResource { public TResource Resource { get; private set; } public ModelAction Action { get; private set; } @@ -25,5 +26,4 @@ namespace Lidarr.Http Action = action; } } - -} \ No newline at end of file +} diff --git a/src/Lidarr.Http/TinyIoCNancyBootstrapper.cs b/src/Lidarr.Http/TinyIoCNancyBootstrapper.cs index ff66e5d42..c4f0a28b0 100644 --- a/src/Lidarr.Http/TinyIoCNancyBootstrapper.cs +++ b/src/Lidarr.Http/TinyIoCNancyBootstrapper.cs @@ -1,17 +1,15 @@ -using TinyIoC; 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; namespace Lidarr.Http { - - /// /// TinyIoC bootstrapper - registers default route resolver and registers itself as /// INancyModuleCatalog for resolving modules but behaviour can be overridden if required. @@ -41,7 +39,7 @@ namespace Lidarr.Http /// Container instance protected override void ConfigureApplicationContainer(TinyIoCContainer container) { - AutoRegister(container, this.AutoRegisterIgnoredAssemblies); + AutoRegister(container, AutoRegisterIgnoredAssemblies); } /// @@ -50,43 +48,35 @@ namespace Lidarr.Http /// INancyEngine implementation protected override sealed INancyEngine GetEngineInternal() { - return this.ApplicationContainer.Resolve(); + return ApplicationContainer.Resolve(); } - // // Summary: // Gets the Nancy.Configuration.INancyEnvironmentConfigurator used by th. - // // Returns: // An Nancy.Configuration.INancyEnvironmentConfigurator instance. protected override INancyEnvironmentConfigurator GetEnvironmentConfigurator() { - return this.ApplicationContainer.Resolve(); + return ApplicationContainer.Resolve(); } - // // 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. public override INancyEnvironment GetEnvironment() { - return this.ApplicationContainer.Resolve(); + return ApplicationContainer.Resolve(); } - // // 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. protected override void RegisterNancyEnvironment(TinyIoCContainer container, INancyEnvironment environment) @@ -204,7 +194,7 @@ namespace Lidarr.Http /// Request container instance protected override TinyIoCContainer CreateRequestContainer(NancyContext context) { - return this.ApplicationContainer.GetChildContainer(); + return ApplicationContainer.GetChildContainer(); } /// @@ -213,7 +203,7 @@ namespace Lidarr.Http /// IDiagnostics implementation protected override IDiagnostics GetDiagnostics() { - return this.ApplicationContainer.Resolve(); + return ApplicationContainer.Resolve(); } /// @@ -222,7 +212,7 @@ namespace Lidarr.Http /// An instance containing instances. protected override IEnumerable GetApplicationStartupTasks() { - return this.ApplicationContainer.ResolveAll(false); + return ApplicationContainer.ResolveAll(false); } /// @@ -242,7 +232,7 @@ namespace Lidarr.Http /// An instance containing instances. protected override IEnumerable GetRegistrationTasks() { - return this.ApplicationContainer.ResolveAll(false); + return ApplicationContainer.ResolveAll(false); } /// diff --git a/src/Lidarr.Http/Validation/EmptyCollectionValidator.cs b/src/Lidarr.Http/Validation/EmptyCollectionValidator.cs index 1ad5e20e2..735f766a7 100644 --- a/src/Lidarr.Http/Validation/EmptyCollectionValidator.cs +++ b/src/Lidarr.Http/Validation/EmptyCollectionValidator.cs @@ -13,7 +13,10 @@ namespace Lidarr.Http.Validation protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } var collection = context.PropertyValue as IEnumerable; diff --git a/src/Marr.Data/Parameters/DbTypeBuilder.cs b/src/Marr.Data/Parameters/DbTypeBuilder.cs index 94b6d2f5c..89e1c3d63 100644 --- a/src/Marr.Data/Parameters/DbTypeBuilder.cs +++ b/src/Marr.Data/Parameters/DbTypeBuilder.cs @@ -22,37 +22,37 @@ namespace Marr.Data.Parameters { public Enum GetDbType(Type type) { - if (type == typeof(String)) + if (type == typeof(string)) return DbType.String; - if (type == typeof(Int32)) + if (type == typeof(int)) return DbType.Int32; - if (type == typeof(Decimal)) + if (type == typeof(decimal)) return DbType.Decimal; if (type == typeof(DateTime)) return DbType.DateTime; - if (type == typeof(Boolean)) + if (type == typeof(bool)) return DbType.Boolean; - if (type == typeof(Int16)) + if (type == typeof(short)) return DbType.Int16; - if (type == typeof(Single)) + if (type == typeof(float)) return DbType.Single; - if (type == typeof(Int64)) + if (type == typeof(long)) return DbType.Int64; - if (type == typeof(Double)) + if (type == typeof(double)) return DbType.Double; - if (type == typeof(Byte)) + if (type == typeof(byte)) return DbType.Byte; - if (type == typeof(Byte[])) + if (type == typeof(byte[])) return DbType.Binary; if (type == typeof(Guid)) diff --git a/src/Marr.Data/QGen/Dialects/Dialect.cs b/src/Marr.Data/QGen/Dialects/Dialect.cs index 195cabc1f..a07963d42 100644 --- a/src/Marr.Data/QGen/Dialects/Dialect.cs +++ b/src/Marr.Data/QGen/Dialects/Dialect.cs @@ -16,7 +16,7 @@ namespace Marr.Data.QGen.Dialects return string.Empty; } - string[] parts = token.Replace('[', new Char()).Replace(']', new Char()).Split('.'); + string[] parts = token.Replace('[', new char()).Replace(']', new char()).Split('.'); StringBuilder sb = new StringBuilder(); foreach (string part in parts) diff --git a/src/Marr.Data/QGen/Dialects/FirebirdDialect.cs b/src/Marr.Data/QGen/Dialects/FirebirdDialect.cs index 49f42ab21..a67f4ce93 100644 --- a/src/Marr.Data/QGen/Dialects/FirebirdDialect.cs +++ b/src/Marr.Data/QGen/Dialects/FirebirdDialect.cs @@ -11,7 +11,7 @@ namespace Marr.Data.QGen.Dialects return string.Empty; } - return token.Replace('[', new Char()).Replace(']', new Char()); + return token.Replace('[', new char()).Replace(']', new char()); } } } diff --git a/src/Marr.Data/QGen/Dialects/OracleDialect.cs b/src/Marr.Data/QGen/Dialects/OracleDialect.cs index 23bc76751..43124a92d 100644 --- a/src/Marr.Data/QGen/Dialects/OracleDialect.cs +++ b/src/Marr.Data/QGen/Dialects/OracleDialect.cs @@ -13,7 +13,7 @@ namespace Marr.Data.QGen.Dialects return string.Empty; } - string[] parts = token.Replace('[', new Char()).Replace(']', new Char()).Split('.'); + string[] parts = token.Replace('[', new char()).Replace(']', new char()).Split('.'); StringBuilder sb = new StringBuilder(); foreach (string part in parts) diff --git a/src/Marr.Data/QGen/SqlitePagingQueryDecorator.cs b/src/Marr.Data/QGen/SqlitePagingQueryDecorator.cs index f77614523..d2d78ec2f 100644 --- a/src/Marr.Data/QGen/SqlitePagingQueryDecorator.cs +++ b/src/Marr.Data/QGen/SqlitePagingQueryDecorator.cs @@ -45,7 +45,7 @@ namespace Marr.Data.QGen _innerQuery.BuildJoinClauses(sql); _innerQuery.BuildWhereClause(sql); _innerQuery.BuildOrderClause(sql); - sql.AppendLine(String.Format(" LIMIT {0},{1}", _skip, _take)); + sql.AppendLine(string.Format(" LIMIT {0},{1}", _skip, _take)); return sql.ToString(); } diff --git a/src/MonoTorrent/BEncoding/BEncodedDictionary.cs b/src/MonoTorrent/BEncoding/BEncodedDictionary.cs index 3329c6848..5c814d7ef 100644 --- a/src/MonoTorrent/BEncoding/BEncodedDictionary.cs +++ b/src/MonoTorrent/BEncoding/BEncodedDictionary.cs @@ -82,7 +82,7 @@ namespace MonoTorrent.BEncoding if (oldkey != null && oldkey.CompareTo(key) > 0) if (strictDecoding) - throw new BEncodingException(String.Format( + throw new BEncodingException(string.Format( "Illegal BEncodedDictionary. The attributes are not ordered correctly. Old key: {0}, New key: {1}", oldkey, key)); diff --git a/src/MonoTorrent/Torrent.cs b/src/MonoTorrent/Torrent.cs index 726131f94..4668dc3fc 100644 --- a/src/MonoTorrent/Torrent.cs +++ b/src/MonoTorrent/Torrent.cs @@ -468,7 +468,7 @@ namespace MonoTorrent break; case ("publisher-url"): - if ((String.IsNullOrEmpty(this.publisherUrl)) && (keypair.Value.ToString().Length > 0)) + if ((string.IsNullOrEmpty(this.publisherUrl)) && (keypair.Value.ToString().Length > 0)) this.publisherUrl = keypair.Value.ToString(); break; @@ -478,7 +478,7 @@ namespace MonoTorrent break; case ("publisher"): - if ((String.IsNullOrEmpty(this.publisher)) && (keypair.Value.ToString().Length > 0)) + if ((string.IsNullOrEmpty(this.publisher)) && (keypair.Value.ToString().Length > 0)) this.publisher = keypair.Value.ToString(); break; @@ -492,7 +492,7 @@ namespace MonoTorrent break; case ("name"): - if ((String.IsNullOrEmpty(this.name)) && (keypair.Value.ToString().Length > 0)) + if ((string.IsNullOrEmpty(this.name)) && (keypair.Value.ToString().Length > 0)) this.name = keypair.Value.ToString(); break; @@ -767,7 +767,7 @@ namespace MonoTorrent if (e is ArgumentOutOfRangeException) throw new BEncodingException("Argument out of range exception when adding seconds to creation date.", e); else if (e is FormatException) - throw new BEncodingException(String.Format("Could not parse {0} into a number", keypair.Value), e); + throw new BEncodingException(string.Format("Could not parse {0} into a number", keypair.Value), e); else throw; } @@ -784,7 +784,7 @@ namespace MonoTorrent break; // even if there's an existing value case ("comment"): - if (String.IsNullOrEmpty(this.comment)) + if (string.IsNullOrEmpty(this.comment)) this.comment = keypair.Value.ToString(); break; @@ -793,7 +793,7 @@ namespace MonoTorrent break; case ("publisher-url"): - if (String.IsNullOrEmpty(this.publisherUrl)) + if (string.IsNullOrEmpty(this.publisherUrl)) this.publisherUrl = keypair.Value.ToString(); break; @@ -844,7 +844,7 @@ namespace MonoTorrent } else { - throw new BEncodingException(String.Format("Non-BEncodedList found in announce-list (found {0})", + throw new BEncodingException(string.Format("Non-BEncodedList found in announce-list (found {0})", announces[j].GetType())); } } diff --git a/src/MonoTorrent/UriHelper.cs b/src/MonoTorrent/UriHelper.cs index d806e596a..34cc888ac 100644 --- a/src/MonoTorrent/UriHelper.cs +++ b/src/MonoTorrent/UriHelper.cs @@ -93,9 +93,9 @@ namespace MonoTorrent else result.WriteByte ((byte)'%'); - int idx = ((int) c) >> 4; + int idx = c >> 4; result.WriteByte ((byte)hexChars [idx]); - idx = ((int) c) & 0x0F; + idx = c & 0x0F; result.WriteByte ((byte)hexChars [idx]); } else { diff --git a/src/NzbDrone.Api.Test/ClientSchemaTests/SchemaBuilderFixture.cs b/src/NzbDrone.Api.Test/ClientSchemaTests/SchemaBuilderFixture.cs index 8d3f040ea..2cb87a17d 100644 --- a/src/NzbDrone.Api.Test/ClientSchemaTests/SchemaBuilderFixture.cs +++ b/src/NzbDrone.Api.Test/ClientSchemaTests/SchemaBuilderFixture.cs @@ -1,6 +1,6 @@ using FluentAssertions; -using NUnit.Framework; using Lidarr.Http.ClientSchema; +using NUnit.Framework; using NzbDrone.Core.Annotations; using NzbDrone.Test.Common; @@ -16,7 +16,6 @@ namespace NzbDrone.Api.Test.ClientSchemaTests schema.Should().HaveCount(2); } - [Test] public void schema_should_have_proper_fields() { @@ -36,8 +35,6 @@ namespace NzbDrone.Api.Test.ClientSchemaTests (string)c.Value == "Bob"); } - - [Test] public void schema_should_have_nested_fields() { diff --git a/src/NzbDrone.Automation.Test/AutomationTestAttribute.cs b/src/NzbDrone.Automation.Test/AutomationTestAttribute.cs index d1cf9faec..2ed2fac7e 100644 --- a/src/NzbDrone.Automation.Test/AutomationTestAttribute.cs +++ b/src/NzbDrone.Automation.Test/AutomationTestAttribute.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Automation.Test public AutomationTestAttribute() : base("AutomationTest") { - } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Automation.Test/MainPagesTest.cs b/src/NzbDrone.Automation.Test/MainPagesTest.cs index 4f818d92d..f11a72199 100644 --- a/src/NzbDrone.Automation.Test/MainPagesTest.cs +++ b/src/NzbDrone.Automation.Test/MainPagesTest.cs @@ -8,72 +8,72 @@ 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 artist_page() { - page.LibraryNavIcon.Click(); - page.WaitForNoSpinner(); - page.Find(By.CssSelector("div[class*='ArtistIndex']")).Should().NotBeNull(); + _page.LibraryNavIcon.Click(); + _page.WaitForNoSpinner(); + _page.Find(By.CssSelector("div[class*='ArtistIndex']")).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 wanted_page() { - page.WantedNavIcon.Click(); - page.WaitForNoSpinner(); + _page.WantedNavIcon.Click(); + _page.WaitForNoSpinner(); - page.Find(By.LinkText("Missing")).Should().NotBeNull(); - page.Find(By.LinkText("Cutoff Unmet")).Should().NotBeNull(); + _page.Find(By.LinkText("Missing")).Should().NotBeNull(); + _page.Find(By.LinkText("Cutoff Unmet")).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_artist_page() { - page.LibraryNavIcon.Click(); - page.WaitForNoSpinner(); + _page.LibraryNavIcon.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*='AddNewItem-searchInput']")).Should().NotBeNull(); + _page.Find(By.CssSelector("input[class*='AddNewItem-searchInput']")).Should().NotBeNull(); } } } diff --git a/src/NzbDrone.Common.Test/CacheTests/CachedDictionaryFixture.cs b/src/NzbDrone.Common.Test/CacheTests/CachedDictionaryFixture.cs index 23781d033..4b98d7313 100644 --- a/src/NzbDrone.Common.Test/CacheTests/CachedDictionaryFixture.cs +++ b/src/NzbDrone.Common.Test/CacheTests/CachedDictionaryFixture.cs @@ -99,4 +99,4 @@ namespace NzbDrone.Common.Test.CacheTests return result; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common.Test/CacheTests/CachedFixture.cs b/src/NzbDrone.Common.Test/CacheTests/CachedFixture.cs index eb06fe0c8..9bb63c7e7 100644 --- a/src/NzbDrone.Common.Test/CacheTests/CachedFixture.cs +++ b/src/NzbDrone.Common.Test/CacheTests/CachedFixture.cs @@ -26,7 +26,6 @@ namespace NzbDrone.Common.Test.CacheTests _cachedString.Get("Test", _worker.GetString); _worker.HitCount.Should().Be(1); - } [Test] @@ -38,7 +37,6 @@ namespace NzbDrone.Common.Test.CacheTests first.Should().Be(second); } - [Test] public void should_be_able_to_update_key() { @@ -48,7 +46,6 @@ namespace NzbDrone.Common.Test.CacheTests _cachedString.Find("Key").Should().Be("New"); } - [Test] public void should_be_able_to_remove_key() { @@ -70,7 +67,6 @@ namespace NzbDrone.Common.Test.CacheTests { int hitCount = 0; - for (int i = 0; i < 10; i++) { _cachedString.Get("key", () => @@ -84,7 +80,7 @@ namespace NzbDrone.Common.Test.CacheTests } [Test] - [Platform(Exclude="MacOsX")] + [Platform(Exclude = "MacOsX")] public void should_honor_ttl() { int hitCount = 0; @@ -92,11 +88,13 @@ namespace NzbDrone.Common.Test.CacheTests 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); } @@ -106,7 +104,7 @@ namespace NzbDrone.Common.Test.CacheTests [Test] [Retry(3)] - [Platform(Exclude="MacOsX")] + [Platform(Exclude = "MacOsX")] public void should_clear_expired_when_they_expire() { int hitCount = 0; @@ -114,11 +112,13 @@ namespace NzbDrone.Common.Test.CacheTests 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/CacheTests/CachedManagerFixture.cs b/src/NzbDrone.Common.Test/CacheTests/CachedManagerFixture.cs index ec3f9de35..29d4516fb 100644 --- a/src/NzbDrone.Common.Test/CacheTests/CachedManagerFixture.cs +++ b/src/NzbDrone.Common.Test/CacheTests/CachedManagerFixture.cs @@ -26,4 +26,4 @@ namespace NzbDrone.Common.Test.CacheTests result1.Should().BeSameAs(result2); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common.Test/ConfigFileProviderTest.cs b/src/NzbDrone.Common.Test/ConfigFileProviderTest.cs index 05367247b..e298b77e9 100644 --- a/src/NzbDrone.Common.Test/ConfigFileProviderTest.cs +++ b/src/NzbDrone.Common.Test/ConfigFileProviderTest.cs @@ -62,10 +62,8 @@ namespace NzbDrone.Common.Test const string key = "Port"; const int value = 8686; - var result = Subject.GetValueInt(key, value); - result.Should().Be(value); } @@ -75,20 +73,16 @@ namespace NzbDrone.Common.Test 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 @@ namespace NzbDrone.Common.Test { const int value = 8686; - var result = Subject.Port; - result.Should().Be(value); } @@ -110,10 +102,8 @@ namespace NzbDrone.Common.Test const string key = "LaunchBrowser"; const bool value = false; - Subject.SetValue(key, value); - var result = Subject.LaunchBrowser; result.Should().Be(value); } @@ -124,10 +114,8 @@ namespace NzbDrone.Common.Test const string key = "Port"; const int value = 12345; - Subject.SetValue(key, value); - var result = Subject.Port; result.Should().Be(value); } @@ -138,10 +126,8 @@ namespace NzbDrone.Common.Test const string key = "Hello"; const string value = "World"; - var result = Subject.GetValue(key, value); - result.Should().Be(value); } @@ -178,7 +164,6 @@ namespace NzbDrone.Common.Test dic["SslPort"] = origSslPort; Subject.SaveConfigDictionary(dic); - dic = new Dictionary(); dic["SslPort"] = sslPort; Subject.SaveConfigDictionary(dic); @@ -213,4 +198,4 @@ namespace NzbDrone.Common.Test Assert.Throws(() => Subject.GetValue("key", "value")); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common.Test/DiskTests/DiskProviderFixtureBase.cs b/src/NzbDrone.Common.Test/DiskTests/DiskProviderFixtureBase.cs index a27a09fba..3eec15fcc 100644 --- a/src/NzbDrone.Common.Test/DiskTests/DiskProviderFixtureBase.cs +++ b/src/NzbDrone.Common.Test/DiskTests/DiskProviderFixtureBase.cs @@ -1,6 +1,5 @@ using System; using System.IO; -using System.IO.Abstractions; using FluentAssertions; using NUnit.Framework; using NzbDrone.Common.Disk; @@ -8,7 +7,8 @@ using NzbDrone.Test.Common; namespace NzbDrone.Common.Test.DiskTests { - public abstract class DiskProviderFixtureBase : TestBase where TSubject : class, IDiskProvider + public abstract class DiskProviderFixtureBase : TestBase + where TSubject : class, IDiskProvider { [Test] public void directory_exist_should_be_able_to_find_existing_folder() @@ -166,7 +166,7 @@ namespace NzbDrone.Common.Test.DiskTests 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(); } @@ -175,7 +175,7 @@ namespace NzbDrone.Common.Test.DiskTests 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); @@ -186,7 +186,7 @@ namespace NzbDrone.Common.Test.DiskTests 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)) { @@ -198,7 +198,7 @@ namespace NzbDrone.Common.Test.DiskTests 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); } @@ -207,7 +207,7 @@ namespace NzbDrone.Common.Test.DiskTests 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 10f9379a3..54d43adba 100644 --- a/src/NzbDrone.Common.Test/DiskTests/DiskTransferServiceFixture.cs +++ b/src/NzbDrone.Common.Test/DiskTests/DiskTransferServiceFixture.cs @@ -490,7 +490,10 @@ namespace NzbDrone.Common.Test.DiskTests .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); @@ -509,7 +512,10 @@ namespace NzbDrone.Common.Test.DiskTests .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)); @@ -886,7 +892,9 @@ namespace NzbDrone.Common.Test.DiskTests { var dir = Path.GetDirectoryName(path); if (exists && dir.IsNotNullOrWhiteSpace()) + { WithExistingFolder(dir); + } Mocker.GetMock() .Setup(v => v.FolderExists(path)) @@ -897,7 +905,9 @@ namespace NzbDrone.Common.Test.DiskTests { var dir = Path.GetDirectoryName(path); if (exists && dir.IsNotNullOrWhiteSpace()) + { WithExistingFolder(dir); + } Mocker.GetMock() .Setup(v => v.FileExists(path)) @@ -951,7 +961,6 @@ namespace NzbDrone.Common.Test.DiskTests WithExistingFile(v, false); }); - Mocker.GetMock() .Setup(v => v.FolderExists(It.IsAny())) .Returns(false); @@ -969,6 +978,7 @@ namespace NzbDrone.Common.Test.DiskTests { WithExistingFolder(s, false); WithExistingFolder(d); + // Note: Should also deal with the files. }); @@ -977,6 +987,7 @@ namespace NzbDrone.Common.Test.DiskTests .Callback((f, r) => { WithExistingFolder(f, false); + // Note: Should also deal with the files. }); @@ -996,39 +1007,39 @@ namespace NzbDrone.Common.Test.DiskTests private void WithRealDiskProvider() { - IFileSystem _fileSystem = new FileSystem(); + IFileSystem fileSystem = new FileSystem(); Mocker.GetMock() .Setup(v => v.FolderExists(It.IsAny())) - .Returns(v => _fileSystem.Directory.Exists(v)); + .Returns(v => fileSystem.Directory.Exists(v)); Mocker.GetMock() .Setup(v => v.FileExists(It.IsAny())) - .Returns(v => _fileSystem.File.Exists(v)); + .Returns(v => fileSystem.File.Exists(v)); Mocker.GetMock() .Setup(v => v.CreateFolder(It.IsAny())) - .Callback(v => _fileSystem.Directory.CreateDirectory(v)); + .Callback(v => fileSystem.Directory.CreateDirectory(v)); Mocker.GetMock() .Setup(v => v.DeleteFolder(It.IsAny(), It.IsAny())) - .Callback((v, r) => _fileSystem.Directory.Delete(v, r)); + .Callback((v, r) => fileSystem.Directory.Delete(v, r)); Mocker.GetMock() .Setup(v => v.DeleteFile(It.IsAny())) - .Callback(v => _fileSystem.File.Delete(v)); + .Callback(v => fileSystem.File.Delete(v)); Mocker.GetMock() .Setup(v => v.GetDirectoryInfos(It.IsAny())) - .Returns(v => _fileSystem.DirectoryInfo.FromDirectoryName(v).GetDirectories().ToList()); + .Returns(v => fileSystem.DirectoryInfo.FromDirectoryName(v).GetDirectories().ToList()); Mocker.GetMock() .Setup(v => v.GetFileInfos(It.IsAny(), It.IsAny())) - .Returns((string v, SearchOption option) => _fileSystem.DirectoryInfo.FromDirectoryName(v).GetFiles("*", option).ToList()); + .Returns((string v, SearchOption option) => fileSystem.DirectoryInfo.FromDirectoryName(v).GetFiles("*", option).ToList()); Mocker.GetMock() .Setup(v => v.GetFileSize(It.IsAny())) - .Returns(v => _fileSystem.FileInfo.FromFileName(v).Length); + .Returns(v => fileSystem.FileInfo.FromFileName(v).Length); Mocker.GetMock() .Setup(v => v.TryCreateHardLink(It.IsAny(), It.IsAny())) @@ -1036,13 +1047,18 @@ namespace NzbDrone.Common.Test.DiskTests Mocker.GetMock() .Setup(v => v.CopyFile(It.IsAny(), It.IsAny(), It.IsAny())) - .Callback((s, d, o) => _fileSystem.File.Copy(s, d, o)); + .Callback((s, d, o) => fileSystem.File.Copy(s, d, o)); Mocker.GetMock() .Setup(v => v.MoveFile(It.IsAny(), It.IsAny(), It.IsAny())) - .Callback((s, d, o) => { - if (_fileSystem.File.Exists(d) && o) _fileSystem.File.Delete(d); - _fileSystem.File.Move(s, d); + .Callback((s, d, o) => + { + if (fileSystem.File.Exists(d) && o) + { + fileSystem.File.Delete(d); + } + + fileSystem.File.Move(s, d); }); Mocker.GetMock() diff --git a/src/NzbDrone.Common.Test/DiskTests/FreeSpaceFixtureBase.cs b/src/NzbDrone.Common.Test/DiskTests/FreeSpaceFixtureBase.cs index bf6d8ec27..2b4d356cd 100644 --- a/src/NzbDrone.Common.Test/DiskTests/FreeSpaceFixtureBase.cs +++ b/src/NzbDrone.Common.Test/DiskTests/FreeSpaceFixtureBase.cs @@ -7,7 +7,8 @@ using NzbDrone.Test.Common; namespace NzbDrone.Common.Test.DiskTests { - public abstract class FreeSpaceFixtureBase : TestBase where TSubject : class, IDiskProvider + public abstract class FreeSpaceFixtureBase : TestBase + where TSubject : class, IDiskProvider { [Test] public void should_get_free_space_for_folder() diff --git a/src/NzbDrone.Common.Test/EnsureTest/PathExtensionFixture.cs b/src/NzbDrone.Common.Test/EnsureTest/PathExtensionFixture.cs index b130f82a6..fcad87fdd 100644 --- a/src/NzbDrone.Common.Test/EnsureTest/PathExtensionFixture.cs +++ b/src/NzbDrone.Common.Test/EnsureTest/PathExtensionFixture.cs @@ -15,7 +15,6 @@ namespace NzbDrone.Common.Test.EnsureTest Ensure.That(path, () => path).IsValidPath(); } - [TestCase(@"/var/user/file with, comma.mp3")] public void EnsureLinuxPath(string path) { diff --git a/src/NzbDrone.Common.Test/EnvironmentProviderTest.cs b/src/NzbDrone.Common.Test/EnvironmentProviderTest.cs index dd7e8fcf0..1d9936a8b 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 826cf9520..a4f0bdc6d 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 c34c0cf70..07df9c79e 100644 --- a/src/NzbDrone.Common.Test/EnvironmentTests/StartupArgumentsFixture.cs +++ b/src/NzbDrone.Common.Test/EnvironmentTests/StartupArgumentsFixture.cs @@ -26,7 +26,6 @@ namespace NzbDrone.Common.Test.EnvironmentTests args.Flags.Contains("t").Should().BeTrue(); } - [TestCase("/key=value")] [TestCase("/KEY=value")] [TestCase(" /key=\"value\"")] @@ -37,7 +36,6 @@ namespace NzbDrone.Common.Test.EnvironmentTests 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 @@ namespace NzbDrone.Common.Test.EnvironmentTests args.PreservedArguments.Should().Be(preserved); } - [Test] public void should_preserver_both() { diff --git a/src/NzbDrone.Common.Test/ExtensionTests/FuzzyContainsFixture.cs b/src/NzbDrone.Common.Test/ExtensionTests/FuzzyContainsFixture.cs index 76e87888f..4aca7ab8d 100644 --- a/src/NzbDrone.Common.Test/ExtensionTests/FuzzyContainsFixture.cs +++ b/src/NzbDrone.Common.Test/ExtensionTests/FuzzyContainsFixture.cs @@ -49,9 +49,9 @@ namespace NzbDrone.Common.Test [TestCase("", "", 0)] [TestCase("abcdef", "de", 1)] [TestCase("abcdef", "defy", 0.75)] - [TestCase("abcdef", "abcdefghk", 6.0/9)] - [TestCase("abcdef", "zabcdefz", 6.0/8)] - [TestCase("plusifeelneedforredundantinformationintitlefield", "anthology", 4.0/9)] + [TestCase("abcdef", "abcdefghk", 6.0 / 9)] + [TestCase("abcdef", "zabcdefz", 6.0 / 8)] + [TestCase("plusifeelneedforredundantinformationintitlefield", "anthology", 4.0 / 9)] [TestCase("+ (Plus) - I feel the need for redundant information in the title field", "+", 1)] public void FuzzyContains(string text, string pattern, double expectedScore) { diff --git a/src/NzbDrone.Common.Test/ExtensionTests/IEnumerableExtensionTests/ExceptByFixture.cs b/src/NzbDrone.Common.Test/ExtensionTests/IEnumerableExtensionTests/ExceptByFixture.cs index 1688fd8c4..2b7ef935b 100644 --- a/src/NzbDrone.Common.Test/ExtensionTests/IEnumerableExtensionTests/ExceptByFixture.cs +++ b/src/NzbDrone.Common.Test/ExtensionTests/IEnumerableExtensionTests/ExceptByFixture.cs @@ -56,7 +56,7 @@ namespace NzbDrone.Common.Test.ExtensionTests.IEnumerableExtensionTests 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 978742af3..f7ed71f94 100644 --- a/src/NzbDrone.Common.Test/ExtensionTests/IPAddressExtensionsFixture.cs +++ b/src/NzbDrone.Common.Test/ExtensionTests/IPAddressExtensionsFixture.cs @@ -24,7 +24,6 @@ namespace NzbDrone.Common.Test.ExtensionTests public void should_return_false_for_public_ip_address(string ipAddress) { IPAddress.Parse(ipAddress).IsLocalAddress().Should().BeFalse(); - } } } diff --git a/src/NzbDrone.Common.Test/ExtensionTests/UrlExtensionsFixture.cs b/src/NzbDrone.Common.Test/ExtensionTests/UrlExtensionsFixture.cs index eae0736dc..651f9fbde 100644 --- a/src/NzbDrone.Common.Test/ExtensionTests/UrlExtensionsFixture.cs +++ b/src/NzbDrone.Common.Test/ExtensionTests/UrlExtensionsFixture.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using FluentAssertions; +using FluentAssertions; using NUnit.Framework; using NzbDrone.Common.Extensions; diff --git a/src/NzbDrone.Common.Test/HashUtilFixture.cs b/src/NzbDrone.Common.Test/HashUtilFixture.cs index 02869fa24..d487b78ba 100644 --- a/src/NzbDrone.Common.Test/HashUtilFixture.cs +++ b/src/NzbDrone.Common.Test/HashUtilFixture.cs @@ -18,4 +18,4 @@ namespace NzbDrone.Common.Test HashUtil.AnonymousToken().Should().Be(HashUtil.AnonymousToken()); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common.Test/Http/HttpClientFixture.cs b/src/NzbDrone.Common.Test/Http/HttpClientFixture.cs index e062b92c4..36e7c7e5a 100644 --- a/src/NzbDrone.Common.Test/Http/HttpClientFixture.cs +++ b/src/NzbDrone.Common.Test/Http/HttpClientFixture.cs @@ -629,7 +629,7 @@ namespace NzbDrone.Common.Test.Http [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 e0a22072e..e5221e408 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 8bc2a265b..4af9bb501 100644 --- a/src/NzbDrone.Common.Test/Http/HttpRequestBuilderFixture.cs +++ b/src/NzbDrone.Common.Test/Http/HttpRequestBuilderFixture.cs @@ -35,7 +35,6 @@ namespace NzbDrone.Common.Test.Http var request = builder.Resource("/v1/").Build(); request.Url.FullUri.Should().Be("http://domain/v1/"); - } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common.Test/Http/HttpRequestFixture.cs b/src/NzbDrone.Common.Test/Http/HttpRequestFixture.cs index 94b55f9f3..060504beb 100644 --- a/src/NzbDrone.Common.Test/Http/HttpRequestFixture.cs +++ b/src/NzbDrone.Common.Test/Http/HttpRequestFixture.cs @@ -6,4 +6,4 @@ namespace NzbDrone.Common.Test.Http public class HttpRequestFixture { } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common.Test/Http/HttpUriFixture.cs b/src/NzbDrone.Common.Test/Http/HttpUriFixture.cs index b76f6ca1f..59d3c90c8 100644 --- a/src/NzbDrone.Common.Test/Http/HttpUriFixture.cs +++ b/src/NzbDrone.Common.Test/Http/HttpUriFixture.cs @@ -84,7 +84,7 @@ namespace NzbDrone.Common.Test.Http public void should_combine_relative_path(string basePath, string relativePath, string expected) { var newUri = new HttpUri(basePath).CombinePath(relativePath); - + newUri.FullUri.Should().Be(expected); } } diff --git a/src/NzbDrone.Common.Test/Http/UserAgentBuilderFixture.cs b/src/NzbDrone.Common.Test/Http/UserAgentBuilderFixture.cs index 6b99793ea..5b764c206 100644 --- a/src/NzbDrone.Common.Test/Http/UserAgentBuilderFixture.cs +++ b/src/NzbDrone.Common.Test/Http/UserAgentBuilderFixture.cs @@ -27,4 +27,4 @@ namespace NzbDrone.Common.Test.Http Subject.GetUserAgent(false).Should().NotBeNullOrWhiteSpace(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common.Test/InstrumentationTests/CleanseLogMessageFixture.cs b/src/NzbDrone.Common.Test/InstrumentationTests/CleanseLogMessageFixture.cs index 9f22141d7..fe744b18d 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 { @@ -16,9 +16,11 @@ namespace NzbDrone.Common.Test.InstrumentationTests [TestCase(@"https://dognzb.cr/fetch/2b51db35e1912ffc138825a12b9933d2/2b51db35e1910123321025a12b9933d2")] [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")] + // 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")] @@ -29,6 +31,7 @@ namespace NzbDrone.Common.Test.InstrumentationTests [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""}]")] @@ -36,14 +39,17 @@ namespace NzbDrone.Common.Test.InstrumentationTests [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)")] [TestCase(@"""DownloadURL"":""https:\/\/broadcasthe.net\/torrents.php?action=download&id=123&authkey=mySecret&torrent_pass=mySecret""")] + // Spotify Refresh [TestCase(@"https://spotify.lidarr.audio/renew?refresh_token=mySecret")] public void should_clean_message(string message) diff --git a/src/NzbDrone.Common.Test/InstrumentationTests/SentryTargetFixture.cs b/src/NzbDrone.Common.Test/InstrumentationTests/SentryTargetFixture.cs index 010578eb8..017bbd347 100644 --- a/src/NzbDrone.Common.Test/InstrumentationTests/SentryTargetFixture.cs +++ b/src/NzbDrone.Common.Test/InstrumentationTests/SentryTargetFixture.cs @@ -1,26 +1,25 @@ -using NUnit.Framework; -using NzbDrone.Common.Instrumentation; -using FluentAssertions; -using NzbDrone.Common.Instrumentation.Sentry; -using System; -using NLog; -using NzbDrone.Test.Common; +using System; using System.Globalization; -using System.Collections.Generic; 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)), new OutOfMemoryException() @@ -29,7 +28,7 @@ namespace NzbDrone.Common.Test.InstrumentationTests [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) @@ -37,44 +36,50 @@ namespace NzbDrone.Common.Test.InstrumentationTests 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")] @@ -82,7 +87,7 @@ namespace NzbDrone.Common.Test.InstrumentationTests 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 a7c20f866..6d79e0cfc 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 3b0db0f79..f5dec0346 100644 --- a/src/NzbDrone.Common.Test/PathExtensionFixture.cs +++ b/src/NzbDrone.Common.Test/PathExtensionFixture.cs @@ -87,7 +87,7 @@ namespace NzbDrone.Common.Test { first.AsOsAgnostic().PathEquals(second.AsOsAgnostic()).Should().BeFalse(); } - + [Test] public void should_return_false_when_not_a_child() { @@ -111,6 +111,7 @@ namespace NzbDrone.Common.Test _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")] @@ -164,7 +165,6 @@ namespace NzbDrone.Common.Test // 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\lidarr\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\lidarr\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(); @@ -199,10 +199,9 @@ namespace NzbDrone.Common.Test 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() { @@ -219,12 +218,11 @@ namespace NzbDrone.Common.Test 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 d00fd9d1b..f0802d10d 100644 --- a/src/NzbDrone.Common.Test/ProcessProviderFixture.cs +++ b/src/NzbDrone.Common.Test/ProcessProviderFixture.cs @@ -19,7 +19,6 @@ namespace NzbDrone.Common.Test [TestFixture] public class ProcessProviderFixture : TestBase { - [SetUp] public void Setup() { @@ -45,7 +44,6 @@ namespace NzbDrone.Common.Test { TestLogger.Warn(ex, "{0} when killing process", ex.Message); } - }); } @@ -87,7 +85,7 @@ namespace NzbDrone.Common.Test } [Test] - [Platform(Exclude="MacOsX")] + [Platform(Exclude = "MacOsX")] [Retry(3)] public void exists_should_find_running_process() { @@ -105,7 +103,7 @@ namespace NzbDrone.Common.Test } [Test] - [Platform(Exclude="MacOsX")] + [Platform(Exclude = "MacOsX")] [Retry(3)] public void kill_all_should_kill_all_process_with_name() { @@ -135,12 +133,13 @@ namespace NzbDrone.Common.Test } 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 95b5027ff..b10f1adee 100644 --- a/src/NzbDrone.Common.Test/ServiceFactoryFixture.cs +++ b/src/NzbDrone.Common.Test/ServiceFactoryFixture.cs @@ -28,4 +28,4 @@ namespace NzbDrone.Common.Test handlers.Should().OnlyHaveUniqueItems(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common.Test/ServiceProviderFixture.cs b/src/NzbDrone.Common.Test/ServiceProviderFixture.cs index 7039a48c7..cdc1a9ed5 100644 --- a/src/NzbDrone.Common.Test/ServiceProviderFixture.cs +++ b/src/NzbDrone.Common.Test/ServiceProviderFixture.cs @@ -35,7 +35,6 @@ namespace NzbDrone.Common.Test } } - private void CleanupService() { if (Subject.ServiceExist(TEMP_SERVICE_NAME)) @@ -61,7 +60,6 @@ namespace NzbDrone.Common.Test Subject.ServiceExist("random_service_name").Should().BeFalse(); } - [Test] public void Service_should_be_installed_and_then_uninstalled() { @@ -121,7 +119,6 @@ namespace NzbDrone.Common.Test Subject.Start(ALWAYS_INSTALLED_SERVICE); Assert.Throws(() => Subject.Start(ALWAYS_INSTALLED_SERVICE)); - ExceptionVerification.ExpectedWarns(1); } @@ -131,15 +128,14 @@ namespace NzbDrone.Common.Test 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 fafac4c0b..4b7349f4a 100644 --- a/src/NzbDrone.Common.Test/TPLTests/DebouncerFixture.cs +++ b/src/NzbDrone.Common.Test/TPLTests/DebouncerFixture.cs @@ -7,7 +7,7 @@ using NzbDrone.Common.TPL; namespace NzbDrone.Common.Test.TPLTests { [TestFixture] - [Platform(Exclude="MacOsX")] + [Platform(Exclude = "MacOsX")] public class DebouncerFixture { public class Counter @@ -20,7 +20,6 @@ namespace NzbDrone.Common.Test.TPLTests } } - [Test] [Retry(3)] public void should_hold_the_call_for_debounce_duration() @@ -34,11 +33,9 @@ namespace NzbDrone.Common.Test.TPLTests counter.Count.Should().Be(0); - Thread.Sleep(100); counter.Count.Should().Be(1); - } [Test] @@ -54,7 +51,6 @@ namespace NzbDrone.Common.Test.TPLTests counter.Count.Should().Be(0); - Thread.Sleep(200); debounceFunction.Execute(); @@ -64,7 +60,6 @@ namespace NzbDrone.Common.Test.TPLTests 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 cd4d611e6..919868458 100644 --- a/src/NzbDrone.Common.Test/TPLTests/RateLimitServiceFixture.cs +++ b/src/NzbDrone.Common.Test/TPLTests/RateLimitServiceFixture.cs @@ -1,16 +1,16 @@ 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 { [TestFixture] - [Platform(Exclude="MacOsX")] + [Platform(Exclude = "MacOsX")] public class RateLimitServiceFixture : TestBase { private DateTime _epoch; diff --git a/src/NzbDrone.Common/ArchiveService.cs b/src/NzbDrone.Common/ArchiveService.cs index 25cbe2f0a..57335ae7c 100644 --- a/src/NzbDrone.Common/ArchiveService.cs +++ b/src/NzbDrone.Common/ArchiveService.cs @@ -31,7 +31,6 @@ namespace NzbDrone.Common { ExtractZip(compressedFile, destination); } - else { ExtractTgz(compressedFile, destination); @@ -74,11 +73,12 @@ namespace NzbDrone.Common { 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); @@ -86,7 +86,9 @@ namespace NzbDrone.Common 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 7c2ef01f3..6c080a02e 100644 --- a/src/NzbDrone.Common/Cache/CacheManager.cs +++ b/src/NzbDrone.Common/Cache/CacheManager.cs @@ -20,7 +20,6 @@ namespace NzbDrone.Common.Cache public CacheManager() { _cache = new Cached(); - } public void Clear() @@ -52,4 +51,4 @@ namespace NzbDrone.Common.Cache return (ICachedDictionary)_cache.Get("dict_" + host.FullName + "_" + name, () => new CachedDictionary(fetchFunc, lifeTime)); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Cache/Cached.cs b/src/NzbDrone.Common/Cache/Cached.cs index 572e1a560..8c953190e 100644 --- a/src/NzbDrone.Common/Cache/Cached.cs +++ b/src/NzbDrone.Common/Cache/Cached.cs @@ -6,7 +6,6 @@ using NzbDrone.Common.EnsureThat; namespace NzbDrone.Common.Cache { - public class Cached : ICached { private class CacheItem @@ -114,6 +113,5 @@ namespace NzbDrone.Common.Cache return _store.Values.Select(c => c.Object).ToList(); } } - } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Cache/CachedDictionary.cs b/src/NzbDrone.Common/Cache/CachedDictionary.cs index 7bbda022a..6332f5054 100644 --- a/src/NzbDrone.Common/Cache/CachedDictionary.cs +++ b/src/NzbDrone.Common/Cache/CachedDictionary.cs @@ -5,7 +5,6 @@ using System.Diagnostics; namespace NzbDrone.Common.Cache { - public class CachedDictionary : ICachedDictionary { private readonly Func> _fetchFunc; @@ -34,7 +33,7 @@ namespace NzbDrone.Common.Cache } public void RefreshIfExpired(TimeSpan ttl) - { + { if (IsExpired(ttl)) { Refresh(); diff --git a/src/NzbDrone.Common/Cache/ICached.cs b/src/NzbDrone.Common/Cache/ICached.cs index 179491a4f..e64b1637c 100644 --- a/src/NzbDrone.Common/Cache/ICached.cs +++ b/src/NzbDrone.Common/Cache/ICached.cs @@ -19,4 +19,4 @@ namespace NzbDrone.Common.Cache ICollection Values { get; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Composition/Container.cs b/src/NzbDrone.Common/Composition/Container.cs index 3b9b2c8fe..6ae1e4bfa 100644 --- a/src/NzbDrone.Common/Composition/Container.cs +++ b/src/NzbDrone.Common/Composition/Container.cs @@ -24,12 +24,14 @@ namespace NzbDrone.Common.Composition _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 @@ namespace NzbDrone.Common.Composition _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)); } @@ -67,7 +70,8 @@ namespace NzbDrone.Common.Composition }); } - public IEnumerable ResolveAll() where T : class + public IEnumerable ResolveAll() + where T : class { return _container.ResolveAll(); } @@ -103,8 +107,7 @@ namespace NzbDrone.Common.Composition .Where(implementation => contractType.IsAssignableFrom(implementation) && !implementation.IsInterface && - !implementation.IsAbstract - ); + !implementation.IsAbstract); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Composition/ContainerBuilderBase.cs b/src/NzbDrone.Common/Composition/ContainerBuilderBase.cs index 998c38cc1..81858b813 100644 --- a/src/NzbDrone.Common/Composition/ContainerBuilderBase.cs +++ b/src/NzbDrone.Common/Composition/ContainerBuilderBase.cs @@ -8,8 +8,8 @@ using TinyIoC; #if NETCOREAPP using System.IO; -using System.Runtime.Loader; using System.Runtime.InteropServices; +using System.Runtime.Loader; #endif namespace NzbDrone.Common.Composition @@ -33,11 +33,11 @@ namespace NzbDrone.Common.Composition _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()); } AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(ContainerResolveEventHandler); @@ -52,8 +52,8 @@ namespace NzbDrone.Common.Composition #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) { @@ -68,8 +68,7 @@ namespace NzbDrone.Common.Composition // This ensures we look for sqlite3 using libsqlite3.so.0 on Linux and not libsqlite3.so which // is less likely to exist. var sqliteAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath( - Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System.Data.SQLite.dll") - ); + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System.Data.SQLite.dll")); try { @@ -117,6 +116,7 @@ namespace NzbDrone.Common.Composition { 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 87d076842..9e7402017 100644 --- a/src/NzbDrone.Common/Composition/IContainer.cs +++ b/src/NzbDrone.Common/Composition/IContainer.cs @@ -5,20 +5,24 @@ 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); IEnumerable GetImplementations(Type contractType); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/ConsoleService.cs b/src/NzbDrone.Common/ConsoleService.cs index e44dfcf52..5b0051523 100644 --- a/src/NzbDrone.Common/ConsoleService.cs +++ b/src/NzbDrone.Common/ConsoleService.cs @@ -27,6 +27,7 @@ namespace NzbDrone.Common Console.WriteLine(" /{0} Uninstall already installed Windows Service ({1}).", StartupContext.UNINSTALL_SERVICE, ServiceProvider.SERVICE_NAME); Console.WriteLine(" /{0} Register URL and open firewall port (allows access from other devices on your network).", StartupContext.REGISTER_URL); } + Console.WriteLine(" /{0} Don't open Lidarr in a browser", StartupContext.NO_BROWSER); Console.WriteLine(" /{0} Start Lidarr terminating any other instances", StartupContext.TERMINATE); Console.WriteLine(" /{0}=path Path to use as the AppData location (stores database, config, logs, etc)", StartupContext.APPDATA); diff --git a/src/NzbDrone.Common/ConvertBase32.cs b/src/NzbDrone.Common/ConvertBase32.cs index 29cb3618e..3ee7803d5 100644 --- a/src/NzbDrone.Common/ConvertBase32.cs +++ b/src/NzbDrone.Common/ConvertBase32.cs @@ -16,7 +16,7 @@ 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/Crypto/HashProvider.cs b/src/NzbDrone.Common/Crypto/HashProvider.cs index 04868cb8c..10a09f359 100644 --- a/src/NzbDrone.Common/Crypto/HashProvider.cs +++ b/src/NzbDrone.Common/Crypto/HashProvider.cs @@ -28,4 +28,4 @@ namespace NzbDrone.Common.Crypto } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Disk/DestinationAlreadyExistsException.cs b/src/NzbDrone.Common/Disk/DestinationAlreadyExistsException.cs index 986413742..ffdc36e0e 100644 --- a/src/NzbDrone.Common/Disk/DestinationAlreadyExistsException.cs +++ b/src/NzbDrone.Common/Disk/DestinationAlreadyExistsException.cs @@ -10,19 +10,23 @@ namespace NzbDrone.Common.Disk { } - 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 65b013954..bda56eb3e 100644 --- a/src/NzbDrone.Common/Disk/DiskProviderBase.cs +++ b/src/NzbDrone.Common/Disk/DiskProviderBase.cs @@ -122,6 +122,7 @@ namespace NzbDrone.Common.Disk { return _fileSystem.File.Exists(path) && path == path.GetActualCasing(); } + default: { return _fileSystem.File.Exists(path); @@ -347,9 +348,11 @@ namespace NzbDrone.Common.Disk 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); @@ -364,7 +367,6 @@ namespace NzbDrone.Common.Disk 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) @@ -375,7 +377,7 @@ namespace NzbDrone.Common.Disk if (attributes.HasFlag(FileAttributes.ReadOnly)) { - var newAttributes = attributes & ~(FileAttributes.ReadOnly); + var newAttributes = attributes & ~FileAttributes.ReadOnly; File.SetAttributes(path, newAttributes); } } @@ -425,12 +427,12 @@ namespace NzbDrone.Common.Disk throw new FileNotFoundException("Unable to find file: " + path, path); } - return (FileStream) _fileSystem.FileStream.Create(path, FileMode.Open, FileAccess.Read); + return (FileStream)_fileSystem.FileStream.Create(path, FileMode.Open, FileAccess.Read); } public FileStream OpenWriteStream(string path) { - return (FileStream) _fileSystem.FileStream.Create(path, FileMode.Create); + return (FileStream)_fileSystem.FileStream.Create(path, FileMode.Create); } public List GetMounts() diff --git a/src/NzbDrone.Common/Disk/DiskTransferService.cs b/src/NzbDrone.Common/Disk/DiskTransferService.cs index 661426210..32b98c6ef 100644 --- a/src/NzbDrone.Common/Disk/DiskTransferService.cs +++ b/src/NzbDrone.Common/Disk/DiskTransferService.cs @@ -84,14 +84,20 @@ namespace NzbDrone.Common.Disk 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); @@ -125,14 +131,20 @@ namespace NzbDrone.Common.Disk 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)); } @@ -142,14 +154,20 @@ namespace NzbDrone.Common.Disk 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); @@ -282,6 +300,7 @@ namespace NzbDrone.Common.Disk { return TransferMode.HardLink; } + if (!mode.HasFlag(TransferMode.Copy)) { throw new IOException("Hardlinking from '" + sourcePath + "' to '" + targetPath + "' failed."); @@ -519,6 +538,7 @@ namespace NzbDrone.Common.Disk { 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/DriveInfoMount.cs b/src/NzbDrone.Common/Disk/DriveInfoMount.cs index d80513666..76020f219 100644 --- a/src/NzbDrone.Common/Disk/DriveInfoMount.cs +++ b/src/NzbDrone.Common/Disk/DriveInfoMount.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using System.IO; using System.IO.Abstractions; using NzbDrone.Common.Extensions; diff --git a/src/NzbDrone.Common/Disk/FileSystemLookupService.cs b/src/NzbDrone.Common/Disk/FileSystemLookupService.cs index 819407cd2..d0e3eda0d 100644 --- a/src/NzbDrone.Common/Disk/FileSystemLookupService.cs +++ b/src/NzbDrone.Common/Disk/FileSystemLookupService.cs @@ -101,12 +101,12 @@ namespace NzbDrone.Common.Disk return true; }) .Select(d => new FileSystemModel - { - Type = FileSystemEntityType.Drive, - Name = d.VolumeName, - Path = d.RootDirectory, - LastModified = null - }) + { + Type = FileSystemEntityType.Drive, + Name = d.VolumeName, + Path = d.RootDirectory, + LastModified = null + }) .ToList(); } @@ -124,7 +124,6 @@ namespace NzbDrone.Common.Disk result.Files = GetFiles(path); } } - catch (DirectoryNotFoundException) { return new FileSystemResult { Parent = GetParent(path) }; @@ -150,12 +149,12 @@ namespace NzbDrone.Common.Disk var directories = _diskProvider.GetDirectoryInfos(path) .OrderBy(d => d.Name) .Select(d => new FileSystemModel - { - Name = d.Name, - Path = GetDirectoryPath(d.FullName.GetActualCasing()), - LastModified = d.LastWriteTimeUtc, - Type = FileSystemEntityType.Folder - }) + { + Name = d.Name, + Path = GetDirectoryPath(d.FullName.GetActualCasing()), + LastModified = d.LastWriteTimeUtc, + Type = FileSystemEntityType.Folder + }) .ToList(); directories.RemoveAll(d => _setToRemove.Contains(d.Name.ToLowerInvariant())); @@ -168,14 +167,14 @@ namespace NzbDrone.Common.Disk return _diskProvider.GetFileInfos(path) .OrderBy(d => d.Name) .Select(d => new FileSystemModel - { - Name = d.Name, - Path = d.FullName.GetActualCasing(), - LastModified = d.LastWriteTimeUtc, - Extension = d.Extension, - Size = d.Length, - Type = FileSystemEntityType.File - }) + { + Name = d.Name, + Path = d.FullName.GetActualCasing(), + LastModified = d.LastWriteTimeUtc, + Extension = d.Extension, + Size = d.Length, + Type = FileSystemEntityType.File + }) .ToList(); } @@ -185,7 +184,7 @@ namespace NzbDrone.Common.Disk { return mountInfo.Name; } - + return $"{mountInfo.Name} ({mountInfo.VolumeLabel})"; } diff --git a/src/NzbDrone.Common/Disk/IMount.cs b/src/NzbDrone.Common/Disk/IMount.cs index 3b15a4cb2..f41d40914 100644 --- a/src/NzbDrone.Common/Disk/IMount.cs +++ b/src/NzbDrone.Common/Disk/IMount.cs @@ -1,5 +1,4 @@ -using System.Collections.Generic; -using System.IO; +using System.IO; namespace NzbDrone.Common.Disk { diff --git a/src/NzbDrone.Common/Disk/NotParentException.cs b/src/NzbDrone.Common/Disk/NotParentException.cs index 66dae7789..9621d36c3 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 bed4c67c6..02aaf6561 100644 --- a/src/NzbDrone.Common/Disk/OsPath.cs +++ b/src/NzbDrone.Common/Disk/OsPath.cs @@ -44,22 +44,36 @@ namespace NzbDrone.Common.Disk { 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,11 +107,12 @@ namespace NzbDrone.Common.Disk { return _path.StartsWith(@"\\") || HasWindowsDriveLetter(_path); } + if (IsUnixPath) { return _path.StartsWith("/"); } - + return false; } } @@ -112,7 +127,7 @@ namespace NzbDrone.Common.Disk { return new OsPath(null); } - + return new OsPath(_path.Substring(0, index), _kind).AsDirectory(); } } @@ -136,7 +151,7 @@ namespace NzbDrone.Common.Disk return path; } - + return _path.Substring(index).Trim('\\', '/'); } } @@ -191,10 +206,12 @@ namespace NzbDrone.Common.Disk { return Equals((OsPath)obj); } + if (obj is string) { return Equals(new OsPath(obj as string)); } + return false; } @@ -212,6 +229,7 @@ namespace NzbDrone.Common.Disk case OsPathKind.Unix: return new OsPath(_path.TrimEnd('/') + "/", _kind); } + return this; } @@ -245,7 +263,10 @@ namespace NzbDrone.Common.Disk 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 @@ namespace NzbDrone.Common.Disk { 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 @@ namespace NzbDrone.Common.Disk { 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 @@ namespace NzbDrone.Common.Disk { return new OsPath(string.Join("\\", newFragments), OsPathKind.Unknown); } + return new OsPath(string.Join("/", newFragments), OsPathKind.Unknown); } } diff --git a/src/NzbDrone.Common/EnsureThat/Ensure.cs b/src/NzbDrone.Common/EnsureThat/Ensure.cs index d918d0e66..cb63dd14c 100644 --- a/src/NzbDrone.Common/EnsureThat/Ensure.cs +++ b/src/NzbDrone.Common/EnsureThat/Ensure.cs @@ -20,4 +20,4 @@ namespace NzbDrone.Common.EnsureThat return new TypeParam(name, value.GetType()); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureBoolExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureBoolExtensions.cs index de18bb06c..a393d556c 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureBoolExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureBoolExtensions.cs @@ -9,7 +9,9 @@ namespace NzbDrone.Common.EnsureThat public static Param IsTrue(this Param param) { if (!param.Value) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotTrue); + } return param; } @@ -18,9 +20,11 @@ namespace NzbDrone.Common.EnsureThat public static Param IsFalse(this Param param) { if (param.Value) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotFalse); + } return param; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureCollectionExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureCollectionExtensions.cs index 34565f8a0..cf0392487 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 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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,19 +58,22 @@ namespace NzbDrone.Common.EnsureThat 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; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureDateTimeExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureDateTimeExtensions.cs index 8586c4ddf..97d9f58ee 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 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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,15 +73,17 @@ namespace NzbDrone.Common.EnsureThat 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) { return IsGt(param, _minTime); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureDecimalExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureDecimalExtensions.cs index 5fa967337..e1bf3ba6d 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureDecimalExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureDecimalExtensions.cs @@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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,12 +54,16 @@ namespace NzbDrone.Common.EnsureThat 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; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureDoubleExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureDoubleExtensions.cs index 7c91f41b4..d67abe512 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureDoubleExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureDoubleExtensions.cs @@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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,12 +54,16 @@ namespace NzbDrone.Common.EnsureThat 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; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureGuidExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureGuidExtensions.cs index 77a7be433..a9d6190b3 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureGuidExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureGuidExtensions.cs @@ -10,9 +10,11 @@ namespace NzbDrone.Common.EnsureThat public static Param IsNotEmpty(this Param param) { if (Guid.Empty.Equals(param.Value)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyGuid); + } return param; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureIntExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureIntExtensions.cs index ecbdb0e3f..77ecaf669 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureIntExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureIntExtensions.cs @@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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,12 +65,16 @@ namespace NzbDrone.Common.EnsureThat 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; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureLongExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureLongExtensions.cs index 066c78c2f..568fefb5a 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureLongExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureLongExtensions.cs @@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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,12 +54,16 @@ namespace NzbDrone.Common.EnsureThat 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; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureNullableValueTypeExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureNullableValueTypeExtensions.cs index 54d5af7ad..3603da257 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureNullableValueTypeExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureNullableValueTypeExtensions.cs @@ -6,12 +6,15 @@ 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; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureObjectExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureObjectExtensions.cs index a5fe6a23f..7833d02e5 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureObjectExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureObjectExtensions.cs @@ -6,12 +6,15 @@ 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; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureShortExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureShortExtensions.cs index 425494d43..54f082b8f 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureShortExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureShortExtensions.cs @@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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,12 +54,16 @@ namespace NzbDrone.Common.EnsureThat 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; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/EnsureStringExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureStringExtensions.cs index 99f348667..1c10c9f28 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureStringExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureStringExtensions.cs @@ -13,7 +13,9 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_NoMatch.Inject(param.Value, match)); } + return param; } @@ -78,7 +93,9 @@ namespace NzbDrone.Common.EnsureThat 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 @@ namespace NzbDrone.Common.EnsureThat 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 74f4246fb..00c1b4dc2 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureTypeExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureTypeExtensions.cs @@ -9,7 +9,7 @@ namespace NzbDrone.Common.EnsureThat { 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,10 +78,12 @@ namespace NzbDrone.Common.EnsureThat 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; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/ExceptionFactory.cs b/src/NzbDrone.Common/EnsureThat/ExceptionFactory.cs index 42bbb1b5c..d3f24a43f 100644 --- a/src/NzbDrone.Common/EnsureThat/ExceptionFactory.cs +++ b/src/NzbDrone.Common/EnsureThat/ExceptionFactory.cs @@ -19,4 +19,4 @@ namespace NzbDrone.Common.EnsureThat return new ArgumentNullException(paramName, message); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/ExpressionExtensions.cs b/src/NzbDrone.Common/EnsureThat/ExpressionExtensions.cs index dc4b25946..11e3598c5 100644 --- a/src/NzbDrone.Common/EnsureThat/ExpressionExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/ExpressionExtensions.cs @@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat var parent = e.Expression as MemberExpression; if (parent != null) + { path = parent.ToPath() + "."; + } return path + e.Member.Name; } @@ -23,17 +25,23 @@ namespace NzbDrone.Common.EnsureThat 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); @@ -48,4 +56,4 @@ namespace NzbDrone.Common.EnsureThat return null; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/Param.cs b/src/NzbDrone.Common/EnsureThat/Param.cs index c1ff3c963..1eea2851d 100644 --- a/src/NzbDrone.Common/EnsureThat/Param.cs +++ b/src/NzbDrone.Common/EnsureThat/Param.cs @@ -16,9 +16,10 @@ namespace NzbDrone.Common.EnsureThat { public readonly T Value; - internal Param(string name, T value) : base(name) + internal Param(string name, T value) + : base(name) { Value = value; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnsureThat/TypeParam.cs b/src/NzbDrone.Common/EnsureThat/TypeParam.cs index 202dacf87..09788e446 100644 --- a/src/NzbDrone.Common/EnsureThat/TypeParam.cs +++ b/src/NzbDrone.Common/EnsureThat/TypeParam.cs @@ -12,4 +12,4 @@ namespace NzbDrone.Common.EnsureThat Type = type; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnvironmentInfo/AppFolderFactory.cs b/src/NzbDrone.Common/EnvironmentInfo/AppFolderFactory.cs index 0a9baa4e3..92818c4da 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/AppFolderFactory.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/AppFolderFactory.cs @@ -41,7 +41,6 @@ namespace NzbDrone.Common.EnvironmentInfo { throw new LidarrStartupException("Cannot create AppFolder, Access to the path {0} is denied", _appFolderInfo.AppDataFolder); } - if (OsInfo.IsWindows) { @@ -70,7 +69,10 @@ namespace NzbDrone.Common.EnvironmentInfo private void InitializeMonoApplicationData() { - if (OsInfo.IsWindows) return; + if (OsInfo.IsWindows) + { + return; + } try { @@ -80,7 +82,7 @@ namespace NzbDrone.Common.EnvironmentInfo 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. @@ -90,7 +92,7 @@ namespace NzbDrone.Common.EnvironmentInfo 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 8ad24d56c..0f54f2ae8 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/AppFolderInfo.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/AppFolderInfo.cs @@ -15,8 +15,7 @@ namespace NzbDrone.Common.EnvironmentInfo 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)); @@ -24,7 +23,7 @@ namespace NzbDrone.Common.EnvironmentInfo { if (OsInfo.IsNotWindows) { - DATA_SPECIAL_FOLDER = Environment.SpecialFolder.ApplicationData; + _dataSpecialFolder = Environment.SpecialFolder.ApplicationData; } if (startupContext.Args.ContainsKey(StartupContext.APPDATA)) @@ -34,7 +33,7 @@ namespace NzbDrone.Common.EnvironmentInfo } else { - AppDataFolder = Path.Combine(Environment.GetFolderPath(DATA_SPECIAL_FOLDER, Environment.SpecialFolderOption.DoNotVerify), "Lidarr"); + AppDataFolder = Path.Combine(Environment.GetFolderPath(_dataSpecialFolder, Environment.SpecialFolderOption.DoNotVerify), "Lidarr"); } 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 15dc9ae98..277383467 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/BuildInfo.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/BuildInfo.cs @@ -29,7 +29,7 @@ namespace NzbDrone.Common.EnvironmentInfo public static string AppName { get; } = "Lidarr"; 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 ed0cd2e17..b844a29c2 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/IOsVersionAdapter.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/IOsVersionAdapter.cs @@ -1,9 +1,8 @@ namespace NzbDrone.Common.EnvironmentInfo { - public interface IOsVersionAdapter { bool Enabled { get; } OsVersionModel Read(); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnvironmentInfo/OsInfo.cs b/src/NzbDrone.Common/EnvironmentInfo/OsInfo.cs index 4579ca48f..1a2b6ce9d 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/OsInfo.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/OsInfo.cs @@ -17,7 +17,7 @@ namespace NzbDrone.Common.EnvironmentInfo // this needs to not be static so we can mock it public bool IsDocker { get; } - + public string Version { get; } public string Name { get; } public string FullName { get; } @@ -33,14 +33,14 @@ namespace NzbDrone.Common.EnvironmentInfo 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 @@ namespace NzbDrone.Common.EnvironmentInfo { Os = Os.Linux; } + break; } } diff --git a/src/NzbDrone.Common/EnvironmentInfo/OsVersionModel.cs b/src/NzbDrone.Common/EnvironmentInfo/OsVersionModel.cs index f36a27134..f5e8074fc 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); @@ -26,4 +24,4 @@ namespace NzbDrone.Common.EnvironmentInfo public string FullName { get; } public string Version { get; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/EnvironmentInfo/PlatformInfo.cs b/src/NzbDrone.Common/EnvironmentInfo/PlatformInfo.cs index f13d6bbc3..0a0ac17c9 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/PlatformInfo.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/PlatformInfo.cs @@ -5,7 +5,6 @@ using Microsoft.Win32; namespace NzbDrone.Common.EnvironmentInfo { - public enum PlatformType { DotNet = 0, @@ -122,38 +121,47 @@ namespace NzbDrone.Common.EnvironmentInfo { 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 b919756c8..6664ef0e9 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/RuntimeInfo.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/RuntimeInfo.cs @@ -21,7 +21,6 @@ namespace NzbDrone.Common.EnvironmentInfo public RuntimeInfo(IServiceProvider serviceProvider, Logger logger) { _logger = logger; - IsWindowsService = !IsUserInteractive && OsInfo.IsWindows && @@ -35,7 +34,6 @@ namespace NzbDrone.Common.EnvironmentInfo { ExecutingApplication = entry.Location; IsWindowsTray = OsInfo.IsWindows && entry.ManifestModule.Name == $"{ProcessProvider.LIDARR_PROCESS_NAME}.exe"; - } } @@ -48,7 +46,7 @@ namespace NzbDrone.Common.EnvironmentInfo // An official build running outside of the testing environment. (Analytics configurable) IsProduction = !IsTesting && officialBuild; - + // An unofficial build running outside of the testing environment. (Analytics enabled) IsDevelopment = !IsTesting && !officialBuild && !InternalIsDebug(); } @@ -127,7 +125,6 @@ namespace NzbDrone.Common.EnvironmentInfo } } - public bool RestartPending { get; set; } public string ExecutingApplication { get; } @@ -135,46 +132,83 @@ namespace NzbDrone.Common.EnvironmentInfo 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; } @@ -182,7 +216,10 @@ namespace NzbDrone.Common.EnvironmentInfo 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/LidarrStartupException.cs b/src/NzbDrone.Common/Exceptions/LidarrStartupException.cs index b43e12cf1..b8e8581bb 100644 --- a/src/NzbDrone.Common/Exceptions/LidarrStartupException.cs +++ b/src/NzbDrone.Common/Exceptions/LidarrStartupException.cs @@ -7,19 +7,16 @@ namespace NzbDrone.Common.Exceptions public LidarrStartupException(string message, params object[] args) : base("Lidarr failed to start: " + string.Format(message, args)) { - } public LidarrStartupException(string message) : base("Lidarr failed to start: " + message) { - } public LidarrStartupException() : base("Lidarr failed to start") { - } public LidarrStartupException(Exception innerException, string message, params object[] args) @@ -35,7 +32,6 @@ namespace NzbDrone.Common.Exceptions public LidarrStartupException(Exception innerException) : base("Lidarr failed to start: " + innerException.Message) { - } } } diff --git a/src/NzbDrone.Common/Exceptions/NzbDroneException.cs b/src/NzbDrone.Common/Exceptions/NzbDroneException.cs index 7e0be7312..015ffc0b5 100644 --- a/src/NzbDrone.Common/Exceptions/NzbDroneException.cs +++ b/src/NzbDrone.Common/Exceptions/NzbDroneException.cs @@ -7,19 +7,16 @@ namespace NzbDrone.Common.Exceptions 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/Exceptions/ServiceProviderException.cs b/src/NzbDrone.Common/Exceptions/ServiceProviderException.cs index 6c3ec7b15..0d2d5b913 100644 --- a/src/NzbDrone.Common/Exceptions/ServiceProviderException.cs +++ b/src/NzbDrone.Common/Exceptions/ServiceProviderException.cs @@ -7,13 +7,11 @@ namespace NzbDrone.Common.Exceptions public ServiceProviderException(string message, params object[] args) : base(string.Format(message, args)) { - } public ServiceProviderException(string message) : base(message) { - } public ServiceProviderException(Exception innerException, string message, params object[] args) diff --git a/src/NzbDrone.Common/Expansive/CircularReferenceException.cs b/src/NzbDrone.Common/Expansive/CircularReferenceException.cs index 93478ad00..737663c54 100644 --- a/src/NzbDrone.Common/Expansive/CircularReferenceException.cs +++ b/src/NzbDrone.Common/Expansive/CircularReferenceException.cs @@ -9,4 +9,4 @@ namespace NzbDrone.Common.Expansive { } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Expansive/Expansive.cs b/src/NzbDrone.Common/Expansive/Expansive.cs index 9ad255ce6..f6a2ff3c5 100644 --- a/src/NzbDrone.Common/Expansive/Expansive.cs +++ b/src/NzbDrone.Common/Expansive/Expansive.cs @@ -11,7 +11,6 @@ namespace NzbDrone.Common.Expansive { private static PatternStyle _patternStyle; - public static bool RequireAllExpansions { get; set; } public static Func DefaultExpansionFactory { get; set; } @@ -26,7 +25,6 @@ namespace NzbDrone.Common.Expansive return source.Expand(DefaultExpansionFactory); } - public static string Expand(this string source, params string[] args) { var output = source; @@ -50,9 +48,11 @@ namespace NzbDrone.Common.Expansive { 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 @@ namespace NzbDrone.Common.Expansive 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 @@ namespace NzbDrone.Common.Expansive return source.ExpandInternal(expansionFactory); } - - - public static string Expand(this string source, object model) { return source.ExpandInternal( @@ -106,17 +108,20 @@ namespace NzbDrone.Common.Expansive 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 @@ namespace NzbDrone.Common.Expansive // 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 @@ namespace NzbDrone.Common.Expansive output = Regex.Replace(output, patternStyle.OutputFilter(match.Value), child); } } + return output; } @@ -171,7 +180,11 @@ namespace NzbDrone.Common.Expansive { 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 @@ namespace NzbDrone.Common.Expansive d.Add(item.Name, item.GetValue(o, null)); } } + return result; } + /// /// Turns the object into a Dictionary /// @@ -195,4 +210,4 @@ namespace NzbDrone.Common.Expansive return (IDictionary)thingy.ToExpando(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Expansive/PatternStyle.cs b/src/NzbDrone.Common/Expansive/PatternStyle.cs index 0e4f0fcc1..011e77315 100644 --- a/src/NzbDrone.Common/Expansive/PatternStyle.cs +++ b/src/NzbDrone.Common/Expansive/PatternStyle.cs @@ -9,4 +9,4 @@ namespace NzbDrone.Common.Expansive public Func TokenReplaceFilter { get; set; } public Func OutputFilter { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Expansive/Tree.cs b/src/NzbDrone.Common/Expansive/Tree.cs index 24be6b642..744c0714e 100644 --- a/src/NzbDrone.Common/Expansive/Tree.cs +++ b/src/NzbDrone.Common/Expansive/Tree.cs @@ -8,4 +8,4 @@ Value = rootValue; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Expansive/TreeNode.cs b/src/NzbDrone.Common/Expansive/TreeNode.cs index d3470072a..5f44d1277 100644 --- a/src/NzbDrone.Common/Expansive/TreeNode.cs +++ b/src/NzbDrone.Common/Expansive/TreeNode.cs @@ -7,25 +7,29 @@ namespace NzbDrone.Common.Expansive 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 @@ namespace NzbDrone.Common.Expansive get { //return (Parent == null) ? this : Parent.Root; - TreeNode node = this; while (node.Parent != null) { node = node.Parent; } + return node; } } @@ -75,11 +79,16 @@ namespace NzbDrone.Common.Expansive node = node.Parent; _CallTree.Add(node.Value); } + return _CallTree; } - private set { _CallTree = value; } + + private set + { + _CallTree = value; + } } public T Value { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Expansive/TreeNodeList.cs b/src/NzbDrone.Common/Expansive/TreeNodeList.cs index 3c92944b2..a239a3b15 100644 --- a/src/NzbDrone.Common/Expansive/TreeNodeList.cs +++ b/src/NzbDrone.Common/Expansive/TreeNodeList.cs @@ -6,27 +6,26 @@ namespace NzbDrone.Common.Expansive { 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(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Extensions/DictionaryExtensions.cs b/src/NzbDrone.Common/Extensions/DictionaryExtensions.cs index ec1d63f71..0c32d49c7 100644 --- a/src/NzbDrone.Common/Extensions/DictionaryExtensions.cs +++ b/src/NzbDrone.Common/Extensions/DictionaryExtensions.cs @@ -16,8 +16,15 @@ namespace NzbDrone.Common.Extensions public static Dictionary Merge(this Dictionary first, Dictionary second) { - if (first == null) throw new ArgumentNullException(nameof(first)); - if (second == null) throw new ArgumentNullException(nameof(second)); + if (first == null) + { + throw new ArgumentNullException(nameof(first)); + } + + if (second == null) + { + throw new ArgumentNullException(nameof(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 bb74db80a..b9d92118a 100644 --- a/src/NzbDrone.Common/Extensions/ExceptionExtensions.cs +++ b/src/NzbDrone.Common/Extensions/ExceptionExtensions.cs @@ -1,36 +1,40 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; 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)); @@ -50,16 +54,19 @@ namespace NzbDrone.Common.Extensions { 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/FuzzyContains.cs b/src/NzbDrone.Common/Extensions/FuzzyContains.cs index 6a372c44f..e3aad635a 100644 --- a/src/NzbDrone.Common/Extensions/FuzzyContains.cs +++ b/src/NzbDrone.Common/Extensions/FuzzyContains.cs @@ -1,6 +1,6 @@ /* - * This file incorporates work covered by the following copyright and - * permission notice: + * This file incorporates work covered by the following copyright and + * permission notice: * * Diff Match and Patch * Copyright 2018 The diff-match-patch Authors. @@ -25,9 +25,8 @@ using System.Numerics; namespace NzbDrone.Common.Extensions { - - public static class FuzzyContainsExtension { - + public static class FuzzyContainsExtension + { public static int FuzzyFind(this string text, string pattern, double matchProb) { return match(text, pattern, matchProb).Item1; @@ -38,7 +37,7 @@ namespace NzbDrone.Common.Extensions { return match(text, pattern, 0.25).Item2; } - + /** * Locate the best instance of 'pattern' in 'text'. * Returns (-1, 1) if no match found. @@ -46,11 +45,13 @@ namespace NzbDrone.Common.Extensions * @param pattern The pattern to search for. * @return Best match index or -1. */ - private static Tuple match(string text, string pattern, double matchThreshold = 0.5) { + private static Tuple match(string text, string pattern, double matchThreshold = 0.5) + { // Check for null inputs not needed since null can't be passed in C#. - if (text.Length == 0 || pattern.Length == 0) { + if (text.Length == 0 || pattern.Length == 0) + { // Nothing to match. - return new Tuple (-1, 0); + return new Tuple(-1, 0); } if (pattern.Length <= text.Length) @@ -59,7 +60,7 @@ namespace NzbDrone.Common.Extensions if (loc != -1) { // Perfect match! - return new Tuple (loc, 1); + return new Tuple(loc, 1); } } @@ -74,63 +75,81 @@ namespace NzbDrone.Common.Extensions * @param pattern The pattern to search for. * @return Best match index or -1. */ - private static Tuple match_bitap(string text, string pattern, double matchThreshold) { - + private static Tuple match_bitap(string text, string pattern, double matchThreshold) + { // Initialise the alphabet. Dictionary s = alphabet(pattern); + // don't keep creating new BigInteger(1) var big1 = new BigInteger(1); // Lowest score belowe which we give up. var score_threshold = matchThreshold; - + // Initialise the bit arrays. var matchmask = big1 << (pattern.Length - 1); int best_loc = -1; // Empty initialization added to appease C# compiler. var last_rd = new BigInteger[0]; - for (int d = 0; d < pattern.Length; d++) { + for (int d = 0; d < pattern.Length; d++) + { // Scan for the best match; each iteration allows for one more error. int start = 1; int finish = text.Length + pattern.Length; var rd = new BigInteger[finish + 2]; rd[finish + 1] = (big1 << d) - big1; - for (int j = finish; j >= start; j--) { + for (int j = finish; j >= start; j--) + { BigInteger charMatch; - if (text.Length <= j - 1 || !s.ContainsKey(text[j - 1])) { + if (text.Length <= j - 1 || !s.ContainsKey(text[j - 1])) + { // Out of range. charMatch = 0; - } else { + } + else + { charMatch = s[text[j - 1]]; } - if (d == 0) { + + if (d == 0) + { // First pass: exact match. rd[j] = ((rd[j + 1] << 1) | big1) & charMatch; - } else { + } + else + { // Subsequent passes: fuzzy match. rd[j] = ((rd[j + 1] << 1) | big1) & charMatch | (((last_rd[j + 1] | last_rd[j]) << 1) | big1) | last_rd[j + 1]; } - if ((rd[j] & matchmask) != 0) { + + if ((rd[j] & matchmask) != 0) + { var score = bitapScore(d, pattern); + // This match will almost certainly be better than any existing // match. But check anyway. - if (score >= score_threshold) { + if (score >= score_threshold) + { // Told you so. score_threshold = score; best_loc = j - 1; } } } - if (bitapScore(d + 1, pattern) < score_threshold) { + + if (bitapScore(d + 1, pattern) < score_threshold) + { // No hope for a (better) match at greater error levels. break; } + last_rd = rd; } - return new Tuple (best_loc, score_threshold); + + return new Tuple(best_loc, score_threshold); } /** @@ -139,8 +158,9 @@ namespace NzbDrone.Common.Extensions * @param pattern Pattern being sought. * @return Overall score for match (1.0 = good, 0.0 = bad). */ - private static double bitapScore(int e, string pattern) { - return 1.0 - (double)e / pattern.Length; + private static double bitapScore(int e, string pattern) + { + return 1.0 - ((double)e / pattern.Length); } /** @@ -148,19 +168,25 @@ namespace NzbDrone.Common.Extensions * @param pattern The text to encode. * @return Hash of character locations. */ - private static Dictionary alphabet(string pattern) { + private static Dictionary alphabet(string pattern) + { var s = new Dictionary(); char[] char_pattern = pattern.ToCharArray(); - foreach (char c in char_pattern) { - if (!s.ContainsKey(c)) { + foreach (char c in char_pattern) + { + if (!s.ContainsKey(c)) + { s.Add(c, 0); } } + int i = 0; - foreach (char c in char_pattern) { + foreach (char c in char_pattern) + { s[c] = s[c] | (new BigInteger(1) << (pattern.Length - i - 1)); i++; } + return s; } } diff --git a/src/NzbDrone.Common/Extensions/IEnumerableExtensions.cs b/src/NzbDrone.Common/Extensions/IEnumerableExtensions.cs index 85a288aee..d2bd23467 100644 --- a/src/NzbDrone.Common/Extensions/IEnumerableExtensions.cs +++ b/src/NzbDrone.Common/Extensions/IEnumerableExtensions.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Linq.Expressions; namespace NzbDrone.Common.Extensions { @@ -14,8 +13,10 @@ namespace NzbDrone.Common.Extensions return source.Where(element => 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); @@ -32,9 +33,11 @@ namespace NzbDrone.Common.Extensions } } - 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(); @@ -70,6 +73,7 @@ namespace NzbDrone.Common.Extensions { throw new ArgumentNullException("source"); } + if (predicate == null) { throw new ArgumentNullException("predicate"); @@ -91,6 +95,7 @@ namespace NzbDrone.Common.Extensions result[key] = item; } } + return result; } @@ -105,6 +110,7 @@ namespace NzbDrone.Common.Extensions result[key] = valueSelector(item); } } + return result; } diff --git a/src/NzbDrone.Common/Extensions/Int64Extensions.cs b/src/NzbDrone.Common/Extensions/Int64Extensions.cs index 911e3b296..bfca7f66c 100644 --- a/src/NzbDrone.Common/Extensions/Int64Extensions.cs +++ b/src/NzbDrone.Common/Extensions/Int64Extensions.cs @@ -11,8 +11,15 @@ namespace NzbDrone.Common.Extensions { 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 f2a49da7d..825525457 100644 --- a/src/NzbDrone.Common/Extensions/LevenstheinExtensions.cs +++ b/src/NzbDrone.Common/Extensions/LevenstheinExtensions.cs @@ -6,9 +6,20 @@ namespace NzbDrone.Common.Extensions { 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]; @@ -47,4 +58,4 @@ namespace NzbDrone.Common.Extensions return expected.LevenshteinDistance(other, 1, 3, 3); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Extensions/ObjectExtensions.cs b/src/NzbDrone.Common/Extensions/ObjectExtensions.cs index 98f694090..5182465e5 100644 --- a/src/NzbDrone.Common/Extensions/ObjectExtensions.cs +++ b/src/NzbDrone.Common/Extensions/ObjectExtensions.cs @@ -4,10 +4,11 @@ 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); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Extensions/PathExtensions.cs b/src/NzbDrone.Common/Extensions/PathExtensions.cs index 5591cd731..2b9feaf86 100644 --- a/src/NzbDrone.Common/Extensions/PathExtensions.cs +++ b/src/NzbDrone.Common/Extensions/PathExtensions.cs @@ -33,7 +33,8 @@ namespace NzbDrone.Common.Extensions var info = new FileInfo(path.Trim()); - if (OsInfo.IsWindows && info.FullName.StartsWith(@"\\")) //UNC + //UNC + if (OsInfo.IsWindows && info.FullName.StartsWith(@"\\")) { return info.FullName.TrimEnd('/', '\\', ' '); } @@ -58,7 +59,11 @@ namespace NzbDrone.Common.Extensions 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); } @@ -92,6 +97,7 @@ namespace NzbDrone.Common.Extensions { 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 6283f5fc0..8f6036baa 100644 --- a/src/NzbDrone.Common/Extensions/StreamExtensions.cs +++ b/src/NzbDrone.Common/Extensions/StreamExtensions.cs @@ -14,6 +14,7 @@ namespace NzbDrone.Common.Extensions { 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 71ecc73a8..4a07aa7b8 100644 --- a/src/NzbDrone.Common/Extensions/StringExtensions.cs +++ b/src/NzbDrone.Common/Extensions/StringExtensions.cs @@ -18,7 +18,11 @@ namespace NzbDrone.Common.Extensions public static object NullSafe(this object target) { - if (target != null) return target; + if (target != null) + { + return target; + } + return "[NULL]"; } @@ -76,7 +80,9 @@ namespace NzbDrone.Common.Extensions public static string TrimEnd(this string text, string postfix) { if (text.EndsWith(postfix)) + { text = text.Substring(0, text.Length - postfix.Length); + } return text; } @@ -105,12 +111,12 @@ namespace NzbDrone.Common.Extensions { return text.StartsWith(startsWith, StringComparison.InvariantCultureIgnoreCase); } - + public static bool EqualsIgnoreCase(this string text, string equals) { return text.Equals(equals, StringComparison.InvariantCultureIgnoreCase); } - + public static bool ContainsIgnoreCase(this string text, string contains) { return text.IndexOf(contains, StringComparison.InvariantCultureIgnoreCase) > -1; @@ -129,7 +135,7 @@ namespace NzbDrone.Common.Extensions 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(); } @@ -146,9 +152,9 @@ namespace NzbDrone.Common.Extensions 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) @@ -193,15 +199,16 @@ namespace NzbDrone.Common.Extensions indexDistance = Math.Abs(i - x); } } - sum += (1.0 - (double)indexDistance / weightDenom) * high; + + sum += (1.0 - (indexDistance / weightDenom)) * high; } + return sum; } public static double LevenshteinCoefficient(this string a, string b) { - return 1.0 - (double)a.LevenshteinDistance(b) / Math.Max(a.Length, b.Length); + return 1.0 - ((double)a.LevenshteinDistance(b) / Math.Max(a.Length, b.Length)); } - } } diff --git a/src/NzbDrone.Common/Extensions/TryParseExtensions.cs b/src/NzbDrone.Common/Extensions/TryParseExtensions.cs index 21255f514..1ed79c319 100644 --- a/src/NzbDrone.Common/Extensions/TryParseExtensions.cs +++ b/src/NzbDrone.Common/Extensions/TryParseExtensions.cs @@ -1,4 +1,3 @@ -using System; using System.Globalization; namespace NzbDrone.Common.Extensions diff --git a/src/NzbDrone.Common/Extensions/UrlExtensions.cs b/src/NzbDrone.Common/Extensions/UrlExtensions.cs index 50e0b9856..e44843838 100644 --- a/src/NzbDrone.Common/Extensions/UrlExtensions.cs +++ b/src/NzbDrone.Common/Extensions/UrlExtensions.cs @@ -28,7 +28,6 @@ namespace NzbDrone.Common.Extensions } return true; - } } } diff --git a/src/NzbDrone.Common/HashUtil.cs b/src/NzbDrone.Common/HashUtil.cs index d826324f3..3d31fe2ea 100644 --- a/src/NzbDrone.Common/HashUtil.cs +++ b/src/NzbDrone.Common/HashUtil.cs @@ -11,7 +11,7 @@ namespace NzbDrone.Common 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 @@ namespace NzbDrone.Common } } } + return $"{mCrc:x8}"; } @@ -33,4 +34,4 @@ namespace NzbDrone.Common return HashUtil.CalculateCrc(seed); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Http/Dispatchers/ManagedHttpDispatcher.cs b/src/NzbDrone.Common/Http/Dispatchers/ManagedHttpDispatcher.cs index 44bbeea8b..fd98974f9 100644 --- a/src/NzbDrone.Common/Http/Dispatchers/ManagedHttpDispatcher.cs +++ b/src/NzbDrone.Common/Http/Dispatchers/ManagedHttpDispatcher.cs @@ -108,7 +108,7 @@ namespace NzbDrone.Common.Http.Dispatchers else { throw; - }; + } } } @@ -121,7 +121,7 @@ namespace NzbDrone.Common.Http.Dispatchers try { data = responseStream.ToBytes(); - + if (PlatformInfo.IsMono && httpWebResponse.ContentEncoding == "gzip") { data = data.Decompress(); @@ -211,6 +211,7 @@ namespace NzbDrone.Common.Http.Dispatchers { 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/GZipWebClient.cs b/src/NzbDrone.Common/Http/GZipWebClient.cs index 6b8ddb582..191bfb10b 100644 --- a/src/NzbDrone.Common/Http/GZipWebClient.cs +++ b/src/NzbDrone.Common/Http/GZipWebClient.cs @@ -12,4 +12,4 @@ namespace NzbDrone.Common.Http return request; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Http/HttpAccept.cs b/src/NzbDrone.Common/Http/HttpAccept.cs index 3da3ee443..8e76f87d3 100644 --- a/src/NzbDrone.Common/Http/HttpAccept.cs +++ b/src/NzbDrone.Common/Http/HttpAccept.cs @@ -5,7 +5,7 @@ public static readonly HttpAccept Rss = new HttpAccept("application/rss+xml, text/rss+xml, application/xml, text/xml"); public static readonly HttpAccept Json = new HttpAccept("application/json"); public static readonly HttpAccept Html = new HttpAccept("text/html"); - + public string Value { get; private set; } public HttpAccept(string accept) diff --git a/src/NzbDrone.Common/Http/HttpClient.cs b/src/NzbDrone.Common/Http/HttpClient.cs index 58896af48..afc8b9209 100644 --- a/src/NzbDrone.Common/Http/HttpClient.cs +++ b/src/NzbDrone.Common/Http/HttpClient.cs @@ -18,10 +18,12 @@ namespace NzbDrone.Common.Http 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 @@ -264,7 +266,8 @@ namespace NzbDrone.Common.Http 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); @@ -283,7 +286,8 @@ namespace NzbDrone.Common.Http 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 005fab57a..d78dd5b3e 100644 --- a/src/NzbDrone.Common/Http/HttpException.cs +++ b/src/NzbDrone.Common/Http/HttpException.cs @@ -17,13 +17,11 @@ namespace NzbDrone.Common.Http 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 46180515f..4aee4092f 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 @@ namespace NzbDrone.Common.Http public HttpHeader(NameValueCollection headers) : base(headers) { - } public HttpHeader() { - } public bool ContainsKey(string key) @@ -35,6 +33,7 @@ namespace NzbDrone.Common.Http { return null; } + if (values.Length > 1) { throw new ApplicationException($"Expected {key} to occur only once, but was {values.Join("|")}."); @@ -43,7 +42,8 @@ namespace NzbDrone.Common.Http 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,8 +53,9 @@ namespace NzbDrone.Common.Http return converter(value); } + protected void SetSingleValue(string key, string value) - { + { if (value == null) { Remove(key); @@ -65,7 +66,8 @@ namespace NzbDrone.Common.Http } } - 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 301890804..12efd6229 100644 --- a/src/NzbDrone.Common/Http/HttpRequest.cs +++ b/src/NzbDrone.Common/Http/HttpRequest.cs @@ -16,7 +16,6 @@ namespace NzbDrone.Common.Http StoreRequestCookie = true; 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 d4ccc26d3..2e9bf1a5b 100644 --- a/src/NzbDrone.Common/Http/HttpRequestBuilder.cs +++ b/src/NzbDrone.Common/Http/HttpRequestBuilder.cs @@ -46,7 +46,6 @@ namespace NzbDrone.Common.Http 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 @@ namespace NzbDrone.Common.Http protected virtual void ApplyFormData(HttpRequest request) { - if (FormData.Empty()) return; + if (FormData.Empty()) + { + return; + } if (request.ContentData != null) { @@ -173,11 +175,22 @@ namespace NzbDrone.Common.Http 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 @@ namespace NzbDrone.Common.Http 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 @@ namespace NzbDrone.Common.Http return this; } } - } diff --git a/src/NzbDrone.Common/Http/HttpRequestBuilderFactory.cs b/src/NzbDrone.Common/Http/HttpRequestBuilderFactory.cs index 18ee914a7..b7a616143 100644 --- a/src/NzbDrone.Common/Http/HttpRequestBuilderFactory.cs +++ b/src/NzbDrone.Common/Http/HttpRequestBuilderFactory.cs @@ -16,7 +16,6 @@ namespace NzbDrone.Common.Http protected HttpRequestBuilderFactory() { - } protected void SetRootBuilder(HttpRequestBuilder rootBuilder) diff --git a/src/NzbDrone.Common/Http/HttpResponse.cs b/src/NzbDrone.Common/Http/HttpResponse.cs index 10b55f199..f30144df5 100644 --- a/src/NzbDrone.Common/Http/HttpResponse.cs +++ b/src/NzbDrone.Common/Http/HttpResponse.cs @@ -48,7 +48,6 @@ namespace NzbDrone.Common.Http } } - public bool HasHttpError => (int)StatusCode >= 400; public bool HasHttpRedirect => StatusCode == HttpStatusCode.Moved || @@ -91,8 +90,8 @@ namespace NzbDrone.Common.Http } } - - 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 a62933e82..9dfd384ad 100644 --- a/src/NzbDrone.Common/Http/HttpUri.cs +++ b/src/NzbDrone.Common/Http/HttpUri.cs @@ -47,6 +47,7 @@ namespace NzbDrone.Common.Http { builder.Append('/'); } + builder.Append(path.TrimStart('/')); } @@ -78,7 +79,7 @@ namespace NzbDrone.Common.Http 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 @@ namespace NzbDrone.Common.Http _queryParams = dict.AsReadOnly(); } + return _queryParams; } } @@ -168,7 +170,7 @@ namespace NzbDrone.Common.Http { return basePath.Substring(0, baseSlashIndex) + "/" + relativePath; } - + return relativePath; } @@ -200,6 +202,7 @@ namespace NzbDrone.Common.Http { builder.Append("&"); } + builder.Append(Uri.EscapeDataString(pair.Key)); builder.Append("="); builder.Append(Uri.EscapeDataString(pair.Value)); @@ -208,7 +211,6 @@ namespace NzbDrone.Common.Http return SetQuery(builder.ToString()); } - public override int GetHashCode() { return _uri.GetHashCode(); @@ -237,7 +239,10 @@ namespace NzbDrone.Common.Http public bool Equals(HttpUri other) { - if (object.ReferenceEquals(other, null)) return false; + if (object.ReferenceEquals(other, null)) + { + return false; + } return _uri.Equals(other._uri); } @@ -263,7 +268,7 @@ namespace NzbDrone.Common.Http { return new HttpUri(baseUrl.Scheme, baseUrl.Host, baseUrl.Port, CombineRelativePath(baseUrl.Path, relativeUrl.Path), relativeUrl.Query, relativeUrl.Fragment); } - + return new HttpUri(baseUrl.Scheme, baseUrl.Host, baseUrl.Port, baseUrl.Path, relativeUrl.Query, relativeUrl.Fragment); } } diff --git a/src/NzbDrone.Common/Http/JsonRpcRequestBuilder.cs b/src/NzbDrone.Common/Http/JsonRpcRequestBuilder.cs index 3722fd9ce..ae987a23d 100644 --- a/src/NzbDrone.Common/Http/JsonRpcRequestBuilder.cs +++ b/src/NzbDrone.Common/Http/JsonRpcRequestBuilder.cs @@ -22,7 +22,7 @@ namespace NzbDrone.Common.Http } 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 3d22f245f..58a7541da 100644 --- a/src/NzbDrone.Common/Http/Proxy/HttpProxySettings.cs +++ b/src/NzbDrone.Common/Http/Proxy/HttpProxySettings.cs @@ -30,15 +30,17 @@ namespace NzbDrone.Common.Http.Proxy 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 4e0a8458b..ca58fedee 100644 --- a/src/NzbDrone.Common/Http/Proxy/ManagedWebProxyFactory.cs +++ b/src/NzbDrone.Common/Http/Proxy/ManagedWebProxyFactory.cs @@ -31,6 +31,7 @@ namespace NzbDrone.Common.Http.Proxy return proxy; } + private IWebProxy CreateWebProxy(HttpProxySettings proxySettings) { switch (proxySettings.Type) @@ -44,6 +45,7 @@ namespace NzbDrone.Common.Http.Proxy { 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 cb1b5f93a..cb3743c03 100644 --- a/src/NzbDrone.Common/Http/TlsFailureException.cs +++ b/src/NzbDrone.Common/Http/TlsFailureException.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Text; +using System.Net; namespace NzbDrone.Common.Http { @@ -11,8 +7,6 @@ namespace NzbDrone.Common.Http 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 fedf94761..09bf0a492 100644 --- a/src/NzbDrone.Common/Http/UnexpectedHtmlContentException.cs +++ b/src/NzbDrone.Common/Http/UnexpectedHtmlContentException.cs @@ -1,5 +1,3 @@ -using System; - namespace NzbDrone.Common.Http { public class UnexpectedHtmlContentException : HttpException @@ -7,7 +5,6 @@ namespace NzbDrone.Common.Http 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/Http/UserAgentBuilder.cs b/src/NzbDrone.Common/Http/UserAgentBuilder.cs index 525b8ee0b..b750cffe7 100644 --- a/src/NzbDrone.Common/Http/UserAgentBuilder.cs +++ b/src/NzbDrone.Common/Http/UserAgentBuilder.cs @@ -37,4 +37,4 @@ namespace NzbDrone.Common.Http _userAgentSimplified = $"{BuildInfo.AppName}/{BuildInfo.Version.ToString(2)}"; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Instrumentation/CleansingJsonVisitor.cs b/src/NzbDrone.Common/Instrumentation/CleansingJsonVisitor.cs index f33f4587b..1e32d399f 100644 --- a/src/NzbDrone.Common/Instrumentation/CleansingJsonVisitor.cs +++ b/src/NzbDrone.Common/Instrumentation/CleansingJsonVisitor.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Linq; using NzbDrone.Common.Serializer; namespace NzbDrone.Common.Instrumentation @@ -19,6 +15,7 @@ namespace NzbDrone.Common.Instrumentation json[i] = new JValue(CleanseLogMessage.Cleanse(text)); } } + foreach (JToken token in json) { Visit(token); diff --git a/src/NzbDrone.Common/Instrumentation/Extensions/SentryLoggerExtensions.cs b/src/NzbDrone.Common/Instrumentation/Extensions/SentryLoggerExtensions.cs index a2af08de7..2e17aad44 100644 --- a/src/NzbDrone.Common/Instrumentation/Extensions/SentryLoggerExtensions.cs +++ b/src/NzbDrone.Common/Instrumentation/Extensions/SentryLoggerExtensions.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System.Linq; using NLog; using NLog.Fluent; @@ -55,4 +52,4 @@ namespace NzbDrone.Common.Instrumentation.Extensions .Exception(logEvent.Exception); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Instrumentation/GlobalExceptionHandlers.cs b/src/NzbDrone.Common/Instrumentation/GlobalExceptionHandlers.cs index 3b99b7ad3..6f778d7de 100644 --- a/src/NzbDrone.Common/Instrumentation/GlobalExceptionHandlers.cs +++ b/src/NzbDrone.Common/Instrumentation/GlobalExceptionHandlers.cs @@ -26,7 +26,10 @@ namespace NzbDrone.Common.Instrumentation { 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 @@ namespace NzbDrone.Common.Instrumentation 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/InitializeLogger.cs b/src/NzbDrone.Common/Instrumentation/InitializeLogger.cs index aa7696204..038be8da8 100644 --- a/src/NzbDrone.Common/Instrumentation/InitializeLogger.cs +++ b/src/NzbDrone.Common/Instrumentation/InitializeLogger.cs @@ -1,8 +1,6 @@ using System.Linq; using NLog; -using NLog.Fluent; using NzbDrone.Common.EnvironmentInfo; -using NzbDrone.Common.Instrumentation.Extensions; using NzbDrone.Common.Instrumentation.Sentry; namespace NzbDrone.Common.Instrumentation diff --git a/src/NzbDrone.Common/Instrumentation/LogEventExtensions.cs b/src/NzbDrone.Common/Instrumentation/LogEventExtensions.cs index 4589050e0..2c8e7c8a0 100644 --- a/src/NzbDrone.Common/Instrumentation/LogEventExtensions.cs +++ b/src/NzbDrone.Common/Instrumentation/LogEventExtensions.cs @@ -29,10 +29,9 @@ namespace NzbDrone.Common.Instrumentation message += ": " + logEvent.Exception.Message; } } - } return message; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Instrumentation/NzbDroneLogger.cs b/src/NzbDrone.Common/Instrumentation/NzbDroneLogger.cs index 489d16a3b..c4c6a3bd6 100644 --- a/src/NzbDrone.Common/Instrumentation/NzbDroneLogger.cs +++ b/src/NzbDrone.Common/Instrumentation/NzbDroneLogger.cs @@ -1,7 +1,6 @@ using System; using System.Diagnostics; using System.IO; -using System.Linq; using NLog; using NLog.Config; using NLog.Targets; @@ -13,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() @@ -20,7 +21,6 @@ namespace NzbDrone.Common.Instrumentation LogManager.Configuration = new LoggingConfiguration(); } - public static void Register(IStartupContext startupContext, bool updateApp, bool inConsole) { if (_isConfigured) @@ -62,13 +62,11 @@ namespace NzbDrone.Common.Instrumentation private static void RegisterSentry(bool updateClient) { - string dsn; if (updateClient) { dsn = "https://2f3cc03453e4453bb3c1dd3ff77b15ab@sentry.io/1339335"; - } else { @@ -118,8 +116,6 @@ namespace NzbDrone.Common.Instrumentation 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", "Lidarr.txt", 5, LogLevel.Info); @@ -195,6 +191,5 @@ namespace NzbDrone.Common.Instrumentation { return GetLogger(obj.GetType()); } - } } diff --git a/src/NzbDrone.Common/Instrumentation/Sentry/SentryCleanser.cs b/src/NzbDrone.Common/Instrumentation/Sentry/SentryCleanser.cs index 7d351a55a..76f0bcb54 100644 --- a/src/NzbDrone.Common/Instrumentation/Sentry/SentryCleanser.cs +++ b/src/NzbDrone.Common/Instrumentation/Sentry/SentryCleanser.cs @@ -36,7 +36,6 @@ namespace NzbDrone.Common.Instrumentation.Sentry } catch (Exception) { - } return sentryEvent; @@ -50,9 +49,8 @@ namespace NzbDrone.Common.Instrumentation.Sentry 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 @@ namespace NzbDrone.Common.Instrumentation.Sentry private static string ShortenPath(string path) { - if (string.IsNullOrWhiteSpace(path)) { return null; @@ -68,7 +65,7 @@ namespace NzbDrone.Common.Instrumentation.Sentry // 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/SentryDebounce.cs b/src/NzbDrone.Common/Instrumentation/Sentry/SentryDebounce.cs index 942f3934a..77585e7a7 100644 --- a/src/NzbDrone.Common/Instrumentation/Sentry/SentryDebounce.cs +++ b/src/NzbDrone.Common/Instrumentation/Sentry/SentryDebounce.cs @@ -35,4 +35,4 @@ namespace NzbDrone.Common.Instrumentation.Sentry _cache.Clear(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Instrumentation/Sentry/SentryTarget.cs b/src/NzbDrone.Common/Instrumentation/Sentry/SentryTarget.cs index 352124a2e..d6cbf285a 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 @@ namespace NzbDrone.Common.Instrumentation.Sentry // 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,20 +36,26 @@ namespace NzbDrone.Common.Instrumentation.Sentry // 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", + // Out Of Memory isn't very informative "OutOfMemoryException", + // 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" }; @@ -56,35 +63,36 @@ namespace NzbDrone.Common.Instrumentation.Sentry // 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 readonly SentryDebounce _debounce; private bool _disposed; - private readonly SentryDebounce _debounce; private bool _unauthorized; public bool FilterEvents { get; set; } @@ -107,6 +115,7 @@ namespace NzbDrone.Common.Instrumentation.Sentry // 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; @@ -246,7 +255,7 @@ namespace NzbDrone.Common.Instrumentation.Sentry { return false; } - + if (FilteredExceptionMessages.Any(x => logEvent.Exception.Message.Contains(x))) { return false; @@ -259,7 +268,6 @@ namespace NzbDrone.Common.Instrumentation.Sentry return false; } - protected override void Write(LogEventInfo logEvent) { if (_unauthorized || !SentryEnabled) @@ -324,6 +332,7 @@ namespace NzbDrone.Common.Instrumentation.Sentry { _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/Messaging/IEvent.cs b/src/NzbDrone.Common/Messaging/IEvent.cs index 00f40b449..70800b9e1 100644 --- a/src/NzbDrone.Common/Messaging/IEvent.cs +++ b/src/NzbDrone.Common/Messaging/IEvent.cs @@ -3,4 +3,4 @@ namespace NzbDrone.Common.Messaging public interface IEvent : IMessage { } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Messaging/IMessage.cs b/src/NzbDrone.Common/Messaging/IMessage.cs index 1c7b25371..5a005a093 100644 --- a/src/NzbDrone.Common/Messaging/IMessage.cs +++ b/src/NzbDrone.Common/Messaging/IMessage.cs @@ -3,4 +3,4 @@ namespace NzbDrone.Common.Messaging public interface IMessage { } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Model/ProcessInfo.cs b/src/NzbDrone.Common/Model/ProcessInfo.cs index 9eb8df647..4f4943189 100644 --- a/src/NzbDrone.Common/Model/ProcessInfo.cs +++ b/src/NzbDrone.Common/Model/ProcessInfo.cs @@ -11,4 +11,4 @@ return string.Format("{0}:{1} [{2}]", Id, Name ?? "Unknown", StartPath ?? "Unknown"); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/OAuth/OAuthRequest.cs b/src/NzbDrone.Common/OAuth/OAuthRequest.cs index 9c3476101..7f84d9e7f 100644 --- a/src/NzbDrone.Common/OAuth/OAuthRequest.cs +++ b/src/NzbDrone.Common/OAuth/OAuthRequest.cs @@ -32,8 +32,6 @@ namespace NzbDrone.Common.OAuth /// public virtual string RequestUrl { get; set; } - #region Authorization Header - #if !WINRT public string GetAuthorizationHeader(NameValueCollection parameters) { @@ -121,10 +119,6 @@ namespace NzbDrone.Common.OAuth return authorization; } - #endregion - - #region Authorization Query - #if !WINRT public string GetAuthorizationQuery(NameValueCollection parameters) { @@ -209,8 +203,6 @@ namespace NzbDrone.Common.OAuth return authorization; } - #endregion - private string GetNewSignature(WebParameterCollection parameters) { var timestamp = OAuthTools.GetTimestamp(); @@ -241,8 +233,6 @@ namespace NzbDrone.Common.OAuth return signature; } - #region Static Helpers - public static OAuthRequest ForRequestToken(string consumerKey, string consumerSecret) { var credentials = new OAuthRequest @@ -335,8 +325,6 @@ namespace NzbDrone.Common.OAuth return credentials; } - #endregion - private void ValidateRequestState() { if (IsNullOrBlank(Method)) @@ -500,9 +488,7 @@ namespace NzbDrone.Common.OAuth 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/OAuthRequestType.cs b/src/NzbDrone.Common/OAuth/OAuthRequestType.cs index e6f86dbd6..9f3032d27 100644 --- a/src/NzbDrone.Common/OAuth/OAuthRequestType.cs +++ b/src/NzbDrone.Common/OAuth/OAuthRequestType.cs @@ -11,4 +11,4 @@ ProtectedResource, ClientAuthentication } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/OAuth/OAuthSignatureMethod.cs b/src/NzbDrone.Common/OAuth/OAuthSignatureMethod.cs index 173e03a3c..79064f88e 100644 --- a/src/NzbDrone.Common/OAuth/OAuthSignatureMethod.cs +++ b/src/NzbDrone.Common/OAuth/OAuthSignatureMethod.cs @@ -9,4 +9,4 @@ namespace NzbDrone.Common.OAuth PlainText, RsaSha1 } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/OAuth/OAuthSignatureTreatment.cs b/src/NzbDrone.Common/OAuth/OAuthSignatureTreatment.cs index 3b64d736e..6a60ff888 100644 --- a/src/NzbDrone.Common/OAuth/OAuthSignatureTreatment.cs +++ b/src/NzbDrone.Common/OAuth/OAuthSignatureTreatment.cs @@ -10,4 +10,4 @@ Escaped, Unescaped } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/OAuth/OAuthTools.cs b/src/NzbDrone.Common/OAuth/OAuthTools.cs index 3d0f8aabc..c2b14c519 100644 --- a/src/NzbDrone.Common/OAuth/OAuthTools.cs +++ b/src/NzbDrone.Common/OAuth/OAuthTools.cs @@ -55,13 +55,13 @@ namespace NzbDrone.Common.OAuth #endif /// - /// Generates a random 16-byte lowercase alphanumeric string. + /// Generates a random 16-byte lowercase alphanumeric string. /// /// /// 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 @@ namespace NzbDrone.Common.OAuth nonce[i] = chars[_random.Next(0, chars.Length)]; } } + return new string(nonce); } @@ -98,7 +99,7 @@ namespace NzbDrone.Common.OAuth 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 @@ namespace NzbDrone.Common.OAuth sb.Append(string.Format("%{0:X}", b)); } } + return sb.ToString(); } @@ -155,8 +157,7 @@ namespace NzbDrone.Common.OAuth 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 @@ namespace NzbDrone.Common.OAuth copy.RemoveAll(exclusions); - foreach(var parameter in copy) + foreach (var parameter in copy) { parameter.Value = UrlEncodeStrict(parameter.Value); } @@ -225,7 +226,7 @@ namespace NzbDrone.Common.OAuth #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 } @@ -259,7 +260,7 @@ namespace NzbDrone.Common.OAuth } /// - /// Creates a request elements concatentation value to send with a request. + /// Creates a request elements concatentation value to send with a request. /// This is also known as the signature base. /// /// @@ -276,7 +277,7 @@ namespace NzbDrone.Common.OAuth var requestMethod = string.Concat(method.ToUpper(), "&"); var requestUrl = string.Concat(UrlEncodeRelaxed(ConstructRequestUrl(new Uri(url))), "&"); var requestParameters = UrlEncodeRelaxed(NormalizeRequestParameters(parameters)); - + sb.Append(requestMethod); sb.Append(requestUrl); sb.Append(requestParameters); @@ -293,7 +294,7 @@ namespace NzbDrone.Common.OAuth /// The signature base /// The consumer key /// - public static string GetSignature(OAuthSignatureMethod signatureMethod, + public static string GetSignature(OAuthSignatureMethod signatureMethod, string signatureBase, string consumerSecret) { @@ -311,7 +312,7 @@ namespace NzbDrone.Common.OAuth /// The consumer key /// public static string GetSignature(OAuthSignatureMethod signatureMethod, - OAuthSignatureTreatment signatureTreatment, + OAuthSignatureTreatment signatureTreatment, string signatureBase, string consumerSecret) { @@ -327,7 +328,7 @@ namespace NzbDrone.Common.OAuth /// The consumer secret /// The token secret /// - public static string GetSignature(OAuthSignatureMethod signatureMethod, + public static string GetSignature(OAuthSignatureMethod signatureMethod, string signatureBase, string consumerSecret, string tokenSecret) @@ -345,7 +346,7 @@ namespace NzbDrone.Common.OAuth /// The consumer secret /// The token secret /// - public static string GetSignature(OAuthSignatureMethod signatureMethod, + public static string GetSignature(OAuthSignatureMethod signatureMethod, OAuthSignatureTreatment signatureTreatment, string signatureBase, string consumerSecret, @@ -353,7 +354,7 @@ namespace NzbDrone.Common.OAuth { if (IsNullOrBlank(tokenSecret)) { - tokenSecret = String.Empty; + tokenSecret = string.Empty; } consumerSecret = UrlEncodeRelaxed(consumerSecret); @@ -381,6 +382,7 @@ namespace NzbDrone.Common.OAuth break; } + default: throw new NotImplementedException("Only HMAC-SHA1 is currently supported."); } @@ -403,7 +405,7 @@ namespace NzbDrone.Common.OAuth 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); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/OAuth/WebParameterCollection.cs b/src/NzbDrone.Common/OAuth/WebParameterCollection.cs index af3e92439..a1084a0ef 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 { @@ -15,13 +15,13 @@ namespace NzbDrone.Common.OAuth get { 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 @@ namespace NzbDrone.Common.OAuth } #if !WINRT - public WebParameterCollection(NameValueCollection collection) : this() + public WebParameterCollection(NameValueCollection collection) + : this() { AddCollection(collection); } @@ -67,7 +68,8 @@ namespace NzbDrone.Common.OAuth } #endif - public WebParameterCollection(IDictionary collection) : this() + public WebParameterCollection(IDictionary collection) + : this() { AddCollection(collection); } @@ -128,8 +130,6 @@ namespace NzbDrone.Common.OAuth _parameters.Add(pair); } - #region IList Members - public virtual IEnumerator GetEnumerator() { return _parameters.GetEnumerator(); @@ -142,7 +142,6 @@ namespace NzbDrone.Common.OAuth public virtual void Add(WebParameter parameter) { - _parameters.Add(parameter); } @@ -196,7 +195,5 @@ namespace NzbDrone.Common.OAuth get { return _parameters[index]; } set { _parameters[index] = value; } } - - #endregion } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/PathEqualityComparer.cs b/src/NzbDrone.Common/PathEqualityComparer.cs index f015792c3..d443a3bf0 100644 --- a/src/NzbDrone.Common/PathEqualityComparer.cs +++ b/src/NzbDrone.Common/PathEqualityComparer.cs @@ -10,7 +10,6 @@ namespace NzbDrone.Common 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 d69d90bf9..103cdc183 100644 --- a/src/NzbDrone.Common/Processes/ProcessProvider.cs +++ b/src/NzbDrone.Common/Processes/ProcessProvider.cs @@ -136,7 +136,6 @@ namespace NzbDrone.Common.Processes { _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 @@ namespace NzbDrone.Common.Processes process.OutputDataReceived += (sender, eventArgs) => { - if (string.IsNullOrWhiteSpace(eventArgs.Data)) return; + if (string.IsNullOrWhiteSpace(eventArgs.Data)) + { + return; + } logger.Debug(eventArgs.Data); @@ -168,7 +170,10 @@ namespace NzbDrone.Common.Processes process.ErrorDataReceived += (sender, eventArgs) => { - if (string.IsNullOrWhiteSpace(eventArgs.Data)) return; + if (string.IsNullOrWhiteSpace(eventArgs.Data)) + { + return; + } logger.Error(eventArgs.Data); @@ -209,8 +214,11 @@ namespace NzbDrone.Common.Processes 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 @@ namespace NzbDrone.Common.Processes private ProcessInfo ConvertToProcessInfo(Process process) { - if (process == null) return null; + if (process == null) + { + return null; + } process.Refresh(); @@ -291,7 +302,10 @@ namespace NzbDrone.Common.Processes try { - if (process.Id <= 0) return null; + if (process.Id <= 0) + { + return null; + } processInfo = new ProcessInfo(); processInfo.Id = process.Id; @@ -309,7 +323,6 @@ namespace NzbDrone.Common.Processes } return processInfo; - } private static string GetExeFileName(Process process) @@ -325,7 +338,6 @@ namespace NzbDrone.Common.Processes 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 1e778b843..b8fd7c6f5 100644 --- a/src/NzbDrone.Common/Reflection/ReflectionExtensions.cs +++ b/src/NzbDrone.Common/Reflection/ReflectionExtensions.cs @@ -29,7 +29,6 @@ namespace NzbDrone.Common.Reflection type = type.GetGenericArguments()[0]; } - return type.IsPrimitive || type.IsEnum || type == typeof(string) @@ -48,7 +47,8 @@ namespace NzbDrone.Common.Reflection 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 @@ namespace NzbDrone.Common.Reflection 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/HttpUriConverter.cs b/src/NzbDrone.Common/Serializer/HttpUriConverter.cs index d11f76b9f..0cba98e8d 100644 --- a/src/NzbDrone.Common/Serializer/HttpUriConverter.cs +++ b/src/NzbDrone.Common/Serializer/HttpUriConverter.cs @@ -28,4 +28,4 @@ namespace NzbDrone.Common.Serializer return objectType == typeof(HttpUri); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Serializer/IntConverter.cs b/src/NzbDrone.Common/Serializer/IntConverter.cs index 105dee3a6..e49676735 100644 --- a/src/NzbDrone.Common/Serializer/IntConverter.cs +++ b/src/NzbDrone.Common/Serializer/IntConverter.cs @@ -23,6 +23,7 @@ namespace NzbDrone.Common.Serializer { throw new JsonSerializationException("Can't convert type " + existingValue.GetType().FullName + " to number"); } + if (objectType == typeof(long)) { return Convert.ToInt64(reader.Value); @@ -36,4 +37,4 @@ namespace NzbDrone.Common.Serializer return objectType == typeof(int) || objectType == typeof(long) || objectType == typeof(int); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Serializer/Json.cs b/src/NzbDrone.Common/Serializer/Json.cs index 5b16c8278..47d5bce67 100644 --- a/src/NzbDrone.Common/Serializer/Json.cs +++ b/src/NzbDrone.Common/Serializer/Json.cs @@ -35,7 +35,8 @@ namespace NzbDrone.Common.Serializer return serializerSettings; } - public static T Deserialize(string json) where T : new() + public static T Deserialize(string json) + where T : new() { return JsonConvert.DeserializeObject(json, SerializerSettings); } @@ -45,7 +46,8 @@ namespace NzbDrone.Common.Serializer return JsonConvert.DeserializeObject(json, type, SerializerSettings); } - 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 { @@ -81,4 +83,4 @@ namespace NzbDrone.Common.Serializer Serialize(model, new StreamWriter(outputStream)); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/Serializer/JsonVisitor.cs b/src/NzbDrone.Common/Serializer/JsonVisitor.cs index 87fdeeeec..0e69a0ae0 100644 --- a/src/NzbDrone.Common/Serializer/JsonVisitor.cs +++ b/src/NzbDrone.Common/Serializer/JsonVisitor.cs @@ -1,12 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Linq; namespace NzbDrone.Common.Serializer { - public class JsonVisitor { protected void Dispatch(JToken json) @@ -70,6 +65,7 @@ namespace NzbDrone.Common.Serializer Visit(token); } } + public virtual void Visit(JConstructor json) { } @@ -89,7 +85,6 @@ namespace NzbDrone.Common.Serializer public virtual void Visit(JValue value) { - } } } diff --git a/src/NzbDrone.Common/Serializer/UnderscoreStringEnumConverter.cs b/src/NzbDrone.Common/Serializer/UnderscoreStringEnumConverter.cs index 49ca2e207..06084b07a 100644 --- a/src/NzbDrone.Common/Serializer/UnderscoreStringEnumConverter.cs +++ b/src/NzbDrone.Common/Serializer/UnderscoreStringEnumConverter.cs @@ -48,8 +48,10 @@ namespace NzbDrone.Common.Serializer { 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 3e1d3aba9..4f7e4bb0b 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 @@ namespace NzbDrone.Common _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()); } @@ -42,4 +46,4 @@ namespace NzbDrone.Common return _container.GetImplementations(contract); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/ServiceProvider.cs b/src/NzbDrone.Common/ServiceProvider.cs index 0e788e79f..4243c78c5 100644 --- a/src/NzbDrone.Common/ServiceProvider.cs +++ b/src/NzbDrone.Common/ServiceProvider.cs @@ -61,7 +61,6 @@ namespace NzbDrone.Common public virtual void Install(string serviceName) { - _logger.Info("Installing service '{0}'", serviceName); var args = $"create {serviceName} " + @@ -152,7 +151,7 @@ namespace NzbDrone.Common 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 d8c961ddc..0fa101525 100644 --- a/src/NzbDrone.Common/TPL/Debouncer.cs +++ b/src/NzbDrone.Common/TPL/Debouncer.cs @@ -17,7 +17,7 @@ namespace NzbDrone.Common.TPL _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) { @@ -60,4 +60,4 @@ namespace NzbDrone.Common.TPL } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/TPL/LimitedConcurrencyLevelTaskScheduler.cs b/src/NzbDrone.Common/TPL/LimitedConcurrencyLevelTaskScheduler.cs index 890ba16df..770ca59a7 100644 --- a/src/NzbDrone.Common/TPL/LimitedConcurrencyLevelTaskScheduler.cs +++ b/src/NzbDrone.Common/TPL/LimitedConcurrencyLevelTaskScheduler.cs @@ -11,30 +11,37 @@ namespace NzbDrone.Common.TPL /// 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) - /// 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) - /// - /// Initializes an instance of the LimitedConcurrencyLevelTaskScheduler class with the - /// specified degree of parallelism. - /// + /// The list of tasks to be executed. + private readonly LinkedList _tasks = new LinkedList(); // protected by lock(_tasks) + + /// 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) + + /// + /// Initializes an instance of the LimitedConcurrencyLevelTaskScheduler class with the + /// specified degree of parallelism. + /// /// The maximum degree of parallelism provided by this scheduler. public LimitedConcurrencyLevelTaskScheduler(int maxDegreeOfParallelism) { - if (maxDegreeOfParallelism < 1) throw new ArgumentOutOfRangeException(nameof(maxDegreeOfParallelism)); + if (maxDegreeOfParallelism < 1) + { + throw new ArgumentOutOfRangeException(nameof(maxDegreeOfParallelism)); + } + _maxDegreeOfParallelism = maxDegreeOfParallelism; } - /// Queues a task to the scheduler. + /// Queues a task to the scheduler. /// The task to be queued. protected sealed override void QueueTask(Task task) { - // Add the task to the list of tasks to be processed. If there aren't enough - // delegates currently queued or running to process tasks, schedule another. + // Add the task to the list of tasks to be processed. If there aren't enough + // delegates currently queued or running to process tasks, schedule another. lock (_tasks) { _tasks.AddLast(task); @@ -46,26 +53,26 @@ namespace NzbDrone.Common.TPL } } - /// - /// Informs the ThreadPool that there's work to be executed for this scheduler. - /// + /// + /// Informs the ThreadPool that there's work to be executed for this scheduler. + /// private void NotifyThreadPoolOfPendingWork() { ThreadPool.UnsafeQueueUserWorkItem(_ => { - // Note that the current thread is now processing work items. + // Note that the current thread is now processing work items. // This is necessary to enable inlining of tasks into this thread. _currentThreadIsProcessingItems = true; try { - // Process all available items in the queue. + // Process all available items in the queue. while (true) { Task item; lock (_tasks) { - // When there are no more items to be processed, - // note that we're done processing, and get out. + // When there are no more items to be processed, + // note that we're done processing, and get out. if (_tasks.Count == 0) { --_delegatesQueuedOrRunning; @@ -77,57 +84,79 @@ namespace NzbDrone.Common.TPL _tasks.RemoveFirst(); } - // Execute the task we pulled out of the queue - base.TryExecuteTask(item); + // Execute the task we pulled out of the queue + TryExecuteTask(item); } } - // We're done processing items on the current thread - finally { _currentThreadIsProcessingItems = false; } + + // We're done processing items on the current thread + finally + { + _currentThreadIsProcessingItems = false; + } }, null); } - /// Attempts to execute the specified task on the current thread. + /// Attempts to execute the specified task on the current thread. /// The task to be executed. /// - /// Whether the task could be executed on the current thread. + /// Whether the task could be executed on the current thread. 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 this thread isn't already processing a task, we don't support inlining + if (!_currentThreadIsProcessingItems) + { + return false; + } - // If the task was previously queued, remove it from the queue - if (taskWasPreviouslyQueued) TryDequeue(task); + // If the task was previously queued, remove it from the queue + if (taskWasPreviouslyQueued) + { + TryDequeue(task); + } - // Try to run the task. - return base.TryExecuteTask(task); + // Try to run the task. + return TryExecuteTask(task); } - /// Attempts to remove a previously scheduled task from the scheduler. + /// Attempts to remove a previously scheduled task from the scheduler. /// The task to be removed. - /// Whether the task could be found and removed. + /// 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. + /// Gets the maximum concurrency level supported by this scheduler. public sealed override int MaximumConcurrencyLevel => _maxDegreeOfParallelism; - /// Gets an enumerable of the tasks currently scheduled on this scheduler. - /// An enumerable of the tasks currently scheduled. + /// Gets an enumerable of the tasks currently scheduled on this scheduler. + /// An enumerable of the tasks currently scheduled. protected sealed override IEnumerable GetScheduledTasks() { bool lockTaken = false; 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); + } } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/TPL/RateLimitService.cs b/src/NzbDrone.Common/TPL/RateLimitService.cs index 6d1b9ee17..f0d30b4ff 100644 --- a/src/NzbDrone.Common/TPL/RateLimitService.cs +++ b/src/NzbDrone.Common/TPL/RateLimitService.cs @@ -25,7 +25,7 @@ namespace NzbDrone.Common.TPL { 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/TPL/TaskExtensions.cs b/src/NzbDrone.Common/TPL/TaskExtensions.cs index aea8f3a11..93b884732 100644 --- a/src/NzbDrone.Common/TPL/TaskExtensions.cs +++ b/src/NzbDrone.Common/TPL/TaskExtensions.cs @@ -25,4 +25,4 @@ namespace NzbDrone.Common.TPL return task; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Common/TinyIoC.cs b/src/NzbDrone.Common/TinyIoC.cs index 7c5d7196f..d2a293706 100644 --- a/src/NzbDrone.Common/TinyIoC.cs +++ b/src/NzbDrone.Common/TinyIoC.cs @@ -13,6 +13,8 @@ // 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 @@ -21,7 +23,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 @@ -322,32 +323,32 @@ namespace TinyIoC } //#if NETFX_CORE - // /// - // /// Gets a generic method from a type given the method name, generic types and parameter types - // /// - // /// Source type - // /// Name of the method - // /// Generic types to use to make the method generic - // /// Method parameters - // /// MethodInfo or null if no matches found - // /// - // /// - // public static MethodInfo GetGenericMethod(this Type sourceType, string methodName, Type[] genericTypes, Type[] parameterTypes) - // { - // MethodInfo method; - // var cacheKey = new GenericMethodCacheKey(sourceType, methodName, genericTypes, parameterTypes); + // /// + // /// Gets a generic method from a type given the method name, generic types and parameter types + // /// + // /// Source type + // /// Name of the method + // /// Generic types to use to make the method generic + // /// Method parameters + // /// MethodInfo or null if no matches found + // /// + // /// + // public static MethodInfo GetGenericMethod(this Type sourceType, string methodName, Type[] genericTypes, Type[] parameterTypes) + // { + // MethodInfo method; + // var cacheKey = new GenericMethodCacheKey(sourceType, methodName, genericTypes, parameterTypes); - // // Shouldn't need any additional locking - // // we don't care if we do the method info generation - // // more than once before it gets cached. - // if (!_genericMethodCache.TryGetValue(cacheKey, out method)) - // { - // method = GetMethod(sourceType, methodName, genericTypes, parameterTypes); - // _genericMethodCache[cacheKey] = method; - // } + // // Shouldn't need any additional locking + // // we don't care if we do the method info generation + // // more than once before it gets cached. + // if (!_genericMethodCache.TryGetValue(cacheKey, out method)) + // { + // method = GetMethod(sourceType, methodName, genericTypes, parameterTypes); + // _genericMethodCache[cacheKey] = method; + // } - // return method; - // } + // return method; + // } //#else /// /// Gets a generic method from a type given the method name, binding flags, generic types and parameter types @@ -376,8 +377,8 @@ namespace TinyIoC return method; } - //#endif + //#endif #if NETFX_CORE private static MethodInfo GetMethod(Type sourceType, BindingFlags flags, string methodName, Type[] genericTypes, Type[] parameterTypes) { @@ -509,7 +510,6 @@ namespace TinyIoC } } } - } // @mbrit - 2012-05-22 - shim for ForEach call on List... @@ -676,7 +676,7 @@ namespace TinyIoC { /// /// Attempt to resolve type, even if the type isn't registered. - /// + /// /// Registered types/options will always take precedence. /// AttemptResolve, @@ -689,7 +689,7 @@ namespace TinyIoC /// /// Attempt to resolve unregistered type if requested type is generic /// and no registration exists for the specific generic parameters used. - /// + /// /// Registered types/options will always take precedence. /// GenericsOnly @@ -904,7 +904,7 @@ namespace TinyIoC #endif /// /// Switches to a custom lifetime manager factory if possible. - /// + /// /// Usually used for RegisterOptions "To*" extension methods such as the ASP.Net per-request one. /// /// RegisterOptions instance @@ -994,7 +994,7 @@ namespace TinyIoC #region Registration /// /// Attempt to automatically register all non-generic classes and interfaces in the current app domain. - /// + /// /// If more than one class implements an interface then only one implementation will be registered /// although no error will be thrown. /// @@ -1010,7 +1010,7 @@ namespace TinyIoC /// /// Attempt to automatically register all non-generic classes and interfaces in the current app domain. /// Types will only be registered if they pass the supplied registration predicate. - /// + /// /// If more than one class implements an interface then only one implementation will be registered /// although no error will be thrown. /// @@ -1056,7 +1056,7 @@ namespace TinyIoC /// /// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies - /// + /// /// If more than one class implements an interface then only one implementation will be registered /// although no error will be thrown. /// @@ -1069,7 +1069,7 @@ namespace TinyIoC /// /// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies /// Types will only be registered if they pass the supplied registration predicate. - /// + /// /// If more than one class implements an interface then only one implementation will be registered /// although no error will be thrown. /// @@ -1123,7 +1123,6 @@ namespace TinyIoC public RegisterOptions Register(Type registerType, string name) { return RegisterInternal(registerType, name, GetDefaultObjectFactory(registerType, registerType)); - } /// @@ -1134,7 +1133,7 @@ namespace TinyIoC /// RegisterOptions for fluent API public RegisterOptions Register(Type registerType, Type registerImplementation) { - return this.RegisterInternal(registerType, string.Empty, GetDefaultObjectFactory(registerType, registerImplementation)); + return RegisterInternal(registerType, string.Empty, GetDefaultObjectFactory(registerType, registerImplementation)); } /// @@ -1146,7 +1145,7 @@ namespace TinyIoC /// RegisterOptions for fluent API public RegisterOptions Register(Type registerType, Type registerImplementation, string name) { - return this.RegisterInternal(registerType, name, GetDefaultObjectFactory(registerType, registerImplementation)); + return RegisterInternal(registerType, name, GetDefaultObjectFactory(registerType, registerImplementation)); } /// @@ -1228,7 +1227,7 @@ namespace TinyIoC public RegisterOptions Register() where RegisterType : class { - return this.Register(typeof(RegisterType)); + return Register(typeof(RegisterType)); } /// @@ -1240,7 +1239,7 @@ namespace TinyIoC public RegisterOptions Register(string name) where RegisterType : class { - return this.Register(typeof(RegisterType), name); + return Register(typeof(RegisterType), name); } /// @@ -1253,7 +1252,7 @@ namespace TinyIoC where RegisterType : class where RegisterImplementation : class, RegisterType { - return this.Register(typeof(RegisterType), typeof(RegisterImplementation)); + return Register(typeof(RegisterType), typeof(RegisterImplementation)); } /// @@ -1267,7 +1266,7 @@ namespace TinyIoC where RegisterType : class where RegisterImplementation : class, RegisterType { - return this.Register(typeof(RegisterType), typeof(RegisterImplementation), name); + return Register(typeof(RegisterType), typeof(RegisterImplementation), name); } /// @@ -1279,7 +1278,7 @@ namespace TinyIoC public RegisterOptions Register(RegisterType instance) where RegisterType : class { - return this.Register(typeof(RegisterType), instance); + return Register(typeof(RegisterType), instance); } /// @@ -1292,7 +1291,7 @@ namespace TinyIoC public RegisterOptions Register(RegisterType instance, string name) where RegisterType : class { - return this.Register(typeof(RegisterType), instance, name); + return Register(typeof(RegisterType), instance, name); } /// @@ -1306,7 +1305,7 @@ namespace TinyIoC where RegisterType : class where RegisterImplementation : class, RegisterType { - return this.Register(typeof(RegisterType), typeof(RegisterImplementation), instance); + return Register(typeof(RegisterType), typeof(RegisterImplementation), instance); } /// @@ -1321,7 +1320,7 @@ namespace TinyIoC where RegisterType : class where RegisterImplementation : class, RegisterType { - return this.Register(typeof(RegisterType), typeof(RegisterImplementation), instance, name); + return Register(typeof(RegisterType), typeof(RegisterImplementation), instance, name); } /// @@ -1338,7 +1337,7 @@ namespace TinyIoC throw new ArgumentNullException("factory"); } - return this.Register(typeof(RegisterType), (c, o) => factory(c, o)); + return Register(typeof(RegisterType), (c, o) => factory(c, o)); } /// @@ -1356,12 +1355,12 @@ namespace TinyIoC throw new ArgumentNullException("factory"); } - return this.Register(typeof(RegisterType), (c, o) => factory(c, o), name); + return Register(typeof(RegisterType), (c, o) => factory(c, o), name); } /// /// Register multiple implementations of a type. - /// + /// /// Internally this registers each implementation using the full name of the class as its registration name. /// /// Type that each implementation implements @@ -1374,7 +1373,7 @@ namespace TinyIoC /// /// Register multiple implementations of a type. - /// + /// /// Internally this registers each implementation using the full name of the class as its registration name. /// /// Type that each implementation implements @@ -1387,7 +1386,7 @@ namespace TinyIoC foreach (var type in implementationTypes) //#if NETFX_CORE - // if (!registrationType.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())) + // if (!registrationType.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())) //#else if (!registrationType.IsAssignableFrom(type)) //#endif @@ -1720,7 +1719,7 @@ namespace TinyIoC /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. - /// + /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve @@ -1736,7 +1735,7 @@ namespace TinyIoC /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. - /// + /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve @@ -1753,7 +1752,7 @@ namespace TinyIoC /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. - /// + /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve @@ -1770,7 +1769,7 @@ namespace TinyIoC /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. - /// + /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve @@ -1845,7 +1844,7 @@ namespace TinyIoC /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. - /// + /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve @@ -1862,7 +1861,7 @@ namespace TinyIoC /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. - /// + /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve @@ -1880,7 +1879,7 @@ namespace TinyIoC /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. - /// + /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve @@ -1898,7 +1897,7 @@ namespace TinyIoC /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. - /// + /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve @@ -2296,7 +2295,7 @@ namespace TinyIoC public IEnumerable ResolveAll(bool includeUnnamed) where ResolveType : class { - return this.ResolveAll(typeof(ResolveType), includeUnnamed).Cast(); + return ResolveAll(typeof(ResolveType), includeUnnamed).Cast(); } /// @@ -2360,7 +2359,7 @@ namespace TinyIoC { /// /// Whether to assume this factory sucessfully constructs its objects - /// + /// /// Generally set to true for delegate style factories as CanResolve cannot delve /// into the delegates they contain. /// @@ -2390,7 +2389,7 @@ namespace TinyIoC { get { - throw new TinyIoCRegistrationException(this.GetType(), "singleton"); + throw new TinyIoCRegistrationException(GetType(), "singleton"); } } @@ -2398,7 +2397,7 @@ namespace TinyIoC { get { - throw new TinyIoCRegistrationException(this.GetType(), "multi-instance"); + throw new TinyIoCRegistrationException(GetType(), "multi-instance"); } } @@ -2406,7 +2405,7 @@ namespace TinyIoC { get { - throw new TinyIoCRegistrationException(this.GetType(), "strong reference"); + throw new TinyIoCRegistrationException(GetType(), "strong reference"); } } @@ -2414,13 +2413,13 @@ namespace TinyIoC { get { - throw new TinyIoCRegistrationException(this.GetType(), "weak reference"); + throw new TinyIoCRegistrationException(GetType(), "weak reference"); } } public virtual ObjectFactoryBase GetCustomObjectLifetimeVariant(ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorString) { - throw new TinyIoCRegistrationException(this.GetType(), errorString); + throw new TinyIoCRegistrationException(GetType(), errorString); } public virtual void SetConstructor(ConstructorInfo constructor) @@ -2441,13 +2440,13 @@ namespace TinyIoC { private readonly Type registerType; private readonly Type registerImplementation; - public override Type CreatesType => this.registerImplementation; + public override Type CreatesType => registerImplementation; public MultiInstanceFactory(Type registerType, Type registerImplementation) { //#if NETFX_CORE - // if (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface()) - // throw new TinyIoCRegistrationTypeException(registerImplementation, "MultiInstanceFactory"); + // if (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface()) + // throw new TinyIoCRegistrationTypeException(registerImplementation, "MultiInstanceFactory"); //#else if (registerImplementation.IsAbstract() || registerImplementation.IsInterface()) throw new TinyIoCRegistrationTypeException(registerImplementation, "MultiInstanceFactory"); @@ -2463,19 +2462,19 @@ namespace TinyIoC { try { - return container.ConstructType(requestedType, this.registerImplementation, Constructor, parameters, options); + return container.ConstructType(requestedType, registerImplementation, Constructor, parameters, options); } catch (TinyIoCResolutionException ex) { - throw new TinyIoCResolutionException(this.registerType, ex); + throw new TinyIoCResolutionException(registerType, ex); } } - public override ObjectFactoryBase SingletonVariant => new SingletonFactory(this.registerType, this.registerImplementation); + public override ObjectFactoryBase SingletonVariant => new SingletonFactory(registerType, registerImplementation); public override ObjectFactoryBase GetCustomObjectLifetimeVariant(ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorString) { - return new CustomObjectLifetimeFactory(this.registerType, this.registerImplementation, lifetimeProvider, errorString); + return new CustomObjectLifetimeFactory(registerType, registerImplementation, lifetimeProvider, errorString); } public override ObjectFactoryBase MultiInstanceVariant => this; @@ -2492,7 +2491,7 @@ namespace TinyIoC public override bool AssumeConstruction => true; - public override Type CreatesType => this.registerType; + public override Type CreatesType => registerType; public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options) { @@ -2502,7 +2501,7 @@ namespace TinyIoC } catch (Exception ex) { - throw new TinyIoCResolutionException(this.registerType, ex); + throw new TinyIoCResolutionException(registerType, ex); } } @@ -2516,7 +2515,7 @@ namespace TinyIoC this.registerType = registerType; } - public override ObjectFactoryBase WeakReferenceVariant => new WeakDelegateFactory(this.registerType, _factory); + public override ObjectFactoryBase WeakReferenceVariant => new WeakDelegateFactory(registerType, _factory); public override ObjectFactoryBase StrongReferenceVariant => this; @@ -2538,14 +2537,14 @@ namespace TinyIoC public override bool AssumeConstruction => true; - public override Type CreatesType => this.registerType; + public override Type CreatesType => registerType; public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options) { var factory = _factory.Target as Func; if (factory == null) - throw new TinyIoCWeakReferenceException(this.registerType); + throw new TinyIoCWeakReferenceException(registerType); try { @@ -2553,7 +2552,7 @@ namespace TinyIoC } catch (Exception ex) { - throw new TinyIoCResolutionException(this.registerType, ex); + throw new TinyIoCResolutionException(registerType, ex); } } @@ -2574,9 +2573,9 @@ namespace TinyIoC var factory = _factory.Target as Func; if (factory == null) - throw new TinyIoCWeakReferenceException(this.registerType); + throw new TinyIoCWeakReferenceException(registerType); - return new DelegateFactory(this.registerType, factory); + return new DelegateFactory(registerType, factory); } } @@ -2609,16 +2608,16 @@ namespace TinyIoC _instance = instance; } - public override Type CreatesType => this.registerImplementation; + public override Type CreatesType => registerImplementation; public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options) { return _instance; } - public override ObjectFactoryBase MultiInstanceVariant => new MultiInstanceFactory(this.registerType, this.registerImplementation); + public override ObjectFactoryBase MultiInstanceVariant => new MultiInstanceFactory(registerType, registerImplementation); - public override ObjectFactoryBase WeakReferenceVariant => new WeakInstanceFactory(this.registerType, this.registerImplementation, this._instance); + public override ObjectFactoryBase WeakReferenceVariant => new WeakInstanceFactory(registerType, registerImplementation, _instance); public override ObjectFactoryBase StrongReferenceVariant => this; @@ -2638,7 +2637,7 @@ namespace TinyIoC /// /// Stores an particular instance to return for a type - /// + /// /// Stores the instance with a weak reference /// private class WeakInstanceFactory : ObjectFactoryBase, IDisposable @@ -2657,19 +2656,19 @@ namespace TinyIoC _instance = new WeakReference(instance); } - public override Type CreatesType => this.registerImplementation; + public override Type CreatesType => registerImplementation; public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options) { var instance = _instance.Target; if (instance == null) - throw new TinyIoCWeakReferenceException(this.registerType); + throw new TinyIoCWeakReferenceException(registerType); return instance; } - public override ObjectFactoryBase MultiInstanceVariant => new MultiInstanceFactory(this.registerType, this.registerImplementation); + public override ObjectFactoryBase MultiInstanceVariant => new MultiInstanceFactory(registerType, registerImplementation); public override ObjectFactoryBase WeakReferenceVariant => this; @@ -2680,9 +2679,9 @@ namespace TinyIoC var instance = _instance.Target; if (instance == null) - throw new TinyIoCWeakReferenceException(this.registerType); + throw new TinyIoCWeakReferenceException(registerType); - return new InstanceFactory(this.registerType, this.registerImplementation, instance); + return new InstanceFactory(registerType, registerImplementation, instance); } } @@ -2713,7 +2712,7 @@ namespace TinyIoC public SingletonFactory(Type registerType, Type registerImplementation) { //#if NETFX_CORE - // if (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface()) + // if (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface()) //#else if (registerImplementation.IsAbstract() || registerImplementation.IsInterface()) //#endif @@ -2726,7 +2725,7 @@ namespace TinyIoC this.registerImplementation = registerImplementation; } - public override Type CreatesType => this.registerImplementation; + public override Type CreatesType => registerImplementation; public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options) { @@ -2735,7 +2734,7 @@ namespace TinyIoC lock (SingletonLock) if (_Current == null) - _Current = container.ConstructType(requestedType, this.registerImplementation, Constructor, options); + _Current = container.ConstructType(requestedType, registerImplementation, Constructor, options); return _Current; } @@ -2744,10 +2743,10 @@ namespace TinyIoC public override ObjectFactoryBase GetCustomObjectLifetimeVariant(ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorString) { - return new CustomObjectLifetimeFactory(this.registerType, this.registerImplementation, lifetimeProvider, errorString); + return new CustomObjectLifetimeFactory(registerType, registerImplementation, lifetimeProvider, errorString); } - public override ObjectFactoryBase MultiInstanceVariant => new MultiInstanceFactory(this.registerType, this.registerImplementation); + public override ObjectFactoryBase MultiInstanceVariant => new MultiInstanceFactory(registerType, registerImplementation); public override ObjectFactoryBase GetFactoryForChildContainer(Type type, TinyIoCContainer parent, TinyIoCContainer child) { @@ -2760,10 +2759,10 @@ namespace TinyIoC public void Dispose() { - if (this._Current == null) + if (_Current == null) return; - var disposable = this._Current as IDisposable; + var disposable = _Current as IDisposable; if (disposable != null) disposable.Dispose(); @@ -2789,7 +2788,7 @@ namespace TinyIoC throw new TinyIoCRegistrationTypeException(registerImplementation, "SingletonFactory"); //#if NETFX_CORE - // if (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface()) + // if (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface()) //#else if (registerImplementation.IsAbstract() || registerImplementation.IsInterface()) //#endif @@ -2800,7 +2799,7 @@ namespace TinyIoC _LifetimeProvider = lifetimeProvider; } - public override Type CreatesType => this.registerImplementation; + public override Type CreatesType => registerImplementation; public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options) { @@ -2811,7 +2810,7 @@ namespace TinyIoC current = _LifetimeProvider.GetObject(); if (current == null) { - current = container.ConstructType(requestedType, this.registerImplementation, Constructor, options); + current = container.ConstructType(requestedType, registerImplementation, Constructor, options); _LifetimeProvider.SetObject(current); } } @@ -2824,7 +2823,7 @@ namespace TinyIoC get { _LifetimeProvider.ReleaseObject(); - return new SingletonFactory(this.registerType, this.registerImplementation); + return new SingletonFactory(registerType, registerImplementation); } } @@ -2833,14 +2832,14 @@ namespace TinyIoC get { _LifetimeProvider.ReleaseObject(); - return new MultiInstanceFactory(this.registerType, this.registerImplementation); + return new MultiInstanceFactory(registerType, registerImplementation); } } public override ObjectFactoryBase GetCustomObjectLifetimeVariant(ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorString) { _LifetimeProvider.ReleaseObject(); - return new CustomObjectLifetimeFactory(this.registerType, this.registerImplementation, lifetimeProvider, errorString); + return new CustomObjectLifetimeFactory(registerType, registerImplementation, lifetimeProvider, errorString); } public override ObjectFactoryBase GetFactoryForChildContainer(Type type, TinyIoCContainer parent, TinyIoCContainer child) @@ -2915,6 +2914,7 @@ namespace TinyIoC return _hashCode; } } + private readonly SafeDictionary _RegisteredTypes; #if USE_OBJECT_CONSTRUCTOR private delegate object ObjectConstructor(params object[] parameters); @@ -2930,7 +2930,7 @@ namespace TinyIoC RegisterDefaultTypes(); } - TinyIoCContainer _Parent; + private TinyIoCContainer _Parent; private TinyIoCContainer(TinyIoCContainer parent) : this() { @@ -2947,7 +2947,7 @@ namespace TinyIoC var types = assemblies.SelectMany(a => a.SafeGetTypes()).Where(t => !IsIgnoredType(t, registrationPredicate)).ToList(); var concreteTypes = from type in types - where type.IsClass() && (type.IsAbstract() == false) && (type != this.GetType() && (type.DeclaringType != this.GetType()) && (!type.IsGenericTypeDefinition())) + where type.IsClass() && (type.IsAbstract() == false) && (type != GetType() && (type.DeclaringType != GetType()) && (!type.IsGenericTypeDefinition())) select type; foreach (var type in concreteTypes) @@ -2963,7 +2963,7 @@ namespace TinyIoC } var abstractInterfaceTypes = from type in types - where ((type.IsInterface() || type.IsAbstract()) && (type.DeclaringType != this.GetType()) && (!type.IsGenericTypeDefinition())) + where ((type.IsInterface() || type.IsAbstract()) && (type.DeclaringType != GetType()) && (!type.IsGenericTypeDefinition())) select type; foreach (var type in abstractInterfaceTypes) @@ -3093,7 +3093,7 @@ namespace TinyIoC private ObjectFactoryBase GetDefaultObjectFactory(Type registerType, Type registerImplementation) { //#if NETFX_CORE - // if (registerType.GetTypeInfo().IsInterface() || registerType.GetTypeInfo().IsAbstract()) + // if (registerType.GetTypeInfo().IsInterface() || registerType.GetTypeInfo().IsAbstract()) //#else if (registerType.IsInterface() || registerType.IsAbstract()) //#endif @@ -3185,7 +3185,7 @@ namespace TinyIoC // 2 parameter func with string as first parameter (name) //#if NETFX_CORE - // if ((genericType == typeof(Func<,>) && type.GetTypeInfo().GenericTypeArguments[0] == typeof(string))) + // if ((genericType == typeof(Func<,>) && type.GetTypeInfo().GenericTypeArguments[0] == typeof(string))) //#else if ((genericType == typeof(Func<,>) && type.GetGenericArguments()[0] == typeof(string))) //#endif @@ -3193,7 +3193,7 @@ namespace TinyIoC // 3 parameter func with string as first parameter (name) and IDictionary as second (parameters) //#if NETFX_CORE - // if ((genericType == typeof(Func<,,>) && type.GetTypeInfo().GenericTypeArguments[0] == typeof(string) && type.GetTypeInfo().GenericTypeArguments[1] == typeof(IDictionary))) + // 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 @@ -3331,7 +3331,7 @@ namespace TinyIoC Type genericType = type.GetGenericTypeDefinition(); //#if NETFX_CORE - // Type[] genericArguments = type.GetTypeInfo().GenericTypeArguments.ToArray(); + // Type[] genericArguments = type.GetTypeInfo().GenericTypeArguments.ToArray(); //#else Type[] genericArguments = type.GetGenericArguments(); //#endif @@ -3342,7 +3342,7 @@ namespace TinyIoC Type returnType = genericArguments[0]; //#if NETFX_CORE - // MethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods("Resolve").First(mi => !mi.GetParameters().Any()); + // MethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods("Resolve").First(mi => !mi.GetParameters().Any()); //#else MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod("Resolve", new Type[] { }); //#endif @@ -3361,7 +3361,7 @@ namespace TinyIoC Type returnType = genericArguments[1]; //#if NETFX_CORE - // MethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods("Resolve").First(mi => mi.GetParameters().Length == 1 && mi.GetParameters()[0].GetType() == typeof(String)); + // 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 @@ -3377,7 +3377,7 @@ namespace TinyIoC // 3 parameter func with string as first parameter (name) and IDictionary as second (parameters) //#if NETFX_CORE - // if ((genericType == typeof(Func<,,>) && type.GenericTypeArguments[0] == typeof(string) && type.GenericTypeArguments[1] == typeof(IDictionary))) + // 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 @@ -3388,7 +3388,7 @@ namespace TinyIoC var parameters = Expression.Parameter(typeof(IDictionary), "parameters"); //#if NETFX_CORE - // 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)); + // 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 @@ -3407,11 +3407,10 @@ namespace TinyIoC private object GetIEnumerableRequest(Type type) { //#if NETFX_CORE - // var genericResolveAllMethod = this.GetType().GetGenericMethod("ResolveAll", type.GenericTypeArguments, new[] { typeof(bool) }); + // 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) }); + var genericResolveAllMethod = GetType().GetGenericMethod(BindingFlags.Public | BindingFlags.Instance, "ResolveAll", type.GetGenericArguments(), new[] { typeof(bool) }); //#endif - return genericResolveAllMethod.Invoke(this, new object[] { false }); } @@ -3427,8 +3426,8 @@ namespace TinyIoC var isParameterOverload = parameters.ContainsKey(parameter.Name); - //#if NETFX_CORE - // if (parameter.ParameterType.GetTypeInfo().IsPrimitive && !isParameterOverload) + //#if NETFX_CORE + // if (parameter.ParameterType.GetTypeInfo().IsPrimitive && !isParameterOverload) //#else if (parameter.ParameterType.IsPrimitive() && !isParameterOverload) //#endif @@ -3447,7 +3446,7 @@ namespace TinyIoC throw new ArgumentNullException("parameters"); //#if NETFX_CORE - // if (type.GetTypeInfo().IsValueType) + // if (type.GetTypeInfo().IsValueType) //#else if (type.IsValueType()) //#endif @@ -3455,11 +3454,11 @@ namespace TinyIoC // Get constructors in reverse order based on the number of parameters // i.e. be as "greedy" as possible so we satify the most amount of dependencies possible - var ctors = this.GetTypeConstructors(type); + var ctors = GetTypeConstructors(type); foreach (var ctor in ctors) { - if (this.CanConstruct(ctor, parameters, options)) + if (CanConstruct(ctor, parameters, options)) return ctor; } @@ -3469,7 +3468,7 @@ namespace TinyIoC private IEnumerable GetTypeConstructors(Type type) { //#if NETFX_CORE - // return type.GetTypeInfo().DeclaredConstructors.OrderByDescending(ctor => ctor.GetParameters().Count()); + // return type.GetTypeInfo().DeclaredConstructors.OrderByDescending(ctor => ctor.GetParameters().Count()); //#else return type.GetConstructors().OrderByDescending(ctor => ctor.GetParameters().Count()); //#endif @@ -3524,15 +3523,12 @@ namespace TinyIoC try { - if (ctorParams[parameterIndex].ParameterType == typeof(Logger)) { args[parameterIndex] = LogManager.GetLogger(implementationType.Name); } else { - - args[parameterIndex] = parameters.ContainsKey(currentParam.Name) ? parameters[currentParam.Name] : ResolveInternal( @@ -3578,7 +3574,7 @@ namespace TinyIoC // We could lock the cache here, but there's no real side // effect to two threads creating the same ObjectConstructor - // at the same time, compared to the cost of a lock for + // at the same time, compared to the cost of a lock for // every creation. var constructorParams = constructor.GetParameters(); var lambdaParams = Expression.Parameter(typeof(object[]), "parameters"); @@ -3605,15 +3601,14 @@ namespace TinyIoC private void BuildUpInternal(object input, ResolveOptions resolveOptions) { //#if NETFX_CORE - // var properties = from property in input.GetType().GetTypeInfo().DeclaredProperties - // where (property.GetMethod != null) && (property.SetMethod != null) && !property.PropertyType.GetTypeInfo().IsValueType - // select property; + // var properties = from property in input.GetType().GetTypeInfo().DeclaredProperties + // where (property.GetMethod != null) && (property.SetMethod != null) && !property.PropertyType.GetTypeInfo().IsValueType + // select property; //#else var properties = from property in input.GetType().GetProperties() where (property.GetGetMethod() != null) && (property.GetSetMethod() != null) && !property.PropertyType.IsValueType() select property; //#endif - foreach (var property in properties) { if (property.GetValue(input, null) == null) @@ -3647,32 +3642,32 @@ namespace TinyIoC if (!includeUnnamed) registrations = registrations.Where(tr => tr.Name != string.Empty); - return registrations.Select(registration => this.ResolveInternal(registration, NamedParameterOverloads.Default, ResolveOptions.Default)); + return registrations.Select(registration => ResolveInternal(registration, NamedParameterOverloads.Default, ResolveOptions.Default)); } private static bool IsValidAssignment(Type registerType, Type registerImplementation) { //#if NETFX_CORE - // var registerTypeDef = registerType.GetTypeInfo(); - // var registerImplementationDef = registerImplementation.GetTypeInfo(); + // var registerTypeDef = registerType.GetTypeInfo(); + // var registerImplementationDef = registerImplementation.GetTypeInfo(); - // if (!registerTypeDef.IsGenericTypeDefinition) - // { - // if (!registerTypeDef.IsAssignableFrom(registerImplementationDef)) - // return false; - // } - // else - // { - // if (registerTypeDef.IsInterface()) - // { - // if (!registerImplementationDef.ImplementedInterfaces.Any(t => t.GetTypeInfo().Name == registerTypeDef.Name)) - // return false; - // } - // else if (registerTypeDef.IsAbstract() && registerImplementationDef.BaseType() != registerType) - // { - // return false; - // } - // } + // if (!registerTypeDef.IsGenericTypeDefinition) + // { + // if (!registerTypeDef.IsAssignableFrom(registerImplementationDef)) + // return false; + // } + // else + // { + // if (registerTypeDef.IsInterface()) + // { + // if (!registerImplementationDef.ImplementedInterfaces.Any(t => t.GetTypeInfo().Name == registerTypeDef.Name)) + // return false; + // } + // else if (registerTypeDef.IsAbstract() && registerImplementationDef.BaseType() != registerType) + // { + // return false; + // } + // } //#else if (!registerType.IsGenericTypeDefinition()) { @@ -3691,6 +3686,7 @@ namespace TinyIoC return false; } } + //#endif return true; } @@ -3698,7 +3694,7 @@ namespace TinyIoC #endregion #region IDisposable Members - bool disposed = false; + private bool disposed = false; public void Dispose() { if (!disposed) @@ -3713,7 +3709,6 @@ namespace TinyIoC #endregion } - } // reverse shim for WinRT SR changes... @@ -3773,4 +3768,4 @@ namespace System.Reflection } } } -#endif \ No newline at end of file +#endif diff --git a/src/NzbDrone.Console/ConsoleAlerts.cs b/src/NzbDrone.Console/ConsoleAlerts.cs index 4d623fc8e..04893b18a 100644 --- a/src/NzbDrone.Console/ConsoleAlerts.cs +++ b/src/NzbDrone.Console/ConsoleAlerts.cs @@ -12,4 +12,4 @@ namespace NzbDrone.Console System.Console.ReadLine(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Console/ConsoleApp.cs b/src/NzbDrone.Console/ConsoleApp.cs index b74815674..980003ff1 100644 --- a/src/NzbDrone.Console/ConsoleApp.cs +++ b/src/NzbDrone.Console/ConsoleApp.cs @@ -35,6 +35,7 @@ namespace NzbDrone.Console System.Console.WriteLine("NLog Exception: " + ex.ToString()); throw; } + Bootstrap.Start(startupArgs, new ConsoleAlerts()); } catch (LidarrStartupException ex) @@ -85,11 +86,14 @@ namespace NzbDrone.Console if (exitCode == ExitCodes.NonRecoverableFailure) { System.Console.WriteLine("Non-recoverable failure, waiting for user intervention..."); - for (int i = 0; i< 3600; i++) + 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/ArtistStatsTests/ArtistStatisticsFixture.cs b/src/NzbDrone.Core.Test/ArtistStatsTests/ArtistStatisticsFixture.cs index 34a00f50f..7757ddfc1 100644 --- a/src/NzbDrone.Core.Test/ArtistStatsTests/ArtistStatisticsFixture.cs +++ b/src/NzbDrone.Core.Test/ArtistStatsTests/ArtistStatisticsFixture.cs @@ -3,11 +3,11 @@ using System.Linq; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; -using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Qualities; using NzbDrone.Core.ArtistStats; -using NzbDrone.Core.Test.Framework; +using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Music; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.ArtistStatsTests { @@ -27,13 +27,13 @@ namespace NzbDrone.Core.Test.ArtistStatsTests .With(a => a.ArtistMetadataId = 10) .BuildNew(); Db.Insert(_artist); - + _album = Builder.CreateNew() .With(e => e.ReleaseDate = DateTime.Today.AddDays(-5)) .With(e => e.ArtistMetadataId = 10) .BuildNew(); Db.Insert(_album); - + _release = Builder.CreateNew() .With(e => e.AlbumId = _album.Id) .With(e => e.Monitored = true) @@ -51,7 +51,6 @@ namespace NzbDrone.Core.Test.ArtistStatsTests .With(e => e.Album = _album) .With(e => e.Quality = new QualityModel(Quality.MP3_256)) .BuildNew(); - } private void GivenTrackWithFile() @@ -125,6 +124,5 @@ namespace NzbDrone.Core.Test.ArtistStatsTests stats.Should().HaveCount(1); stats.First().SizeOnDisk.Should().Be(_trackFile.Size); } - } } diff --git a/src/NzbDrone.Core.Test/Blacklisting/BlacklistRepositoryFixture.cs b/src/NzbDrone.Core.Test/Blacklisting/BlacklistRepositoryFixture.cs index 946a5ad66..cb04da8f4 100644 --- a/src/NzbDrone.Core.Test/Blacklisting/BlacklistRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/Blacklisting/BlacklistRepositoryFixture.cs @@ -18,13 +18,13 @@ namespace NzbDrone.Core.Test.Blacklisting public void Setup() { _blacklist = new Blacklist - { - ArtistId = 12345, - AlbumIds = new List { 1 }, - Quality = new QualityModel(Quality.FLAC), - SourceTitle = "artist.name.album.title", - Date = DateTime.UtcNow - }; + { + ArtistId = 12345, + AlbumIds = new List { 1 }, + Quality = new QualityModel(Quality.FLAC), + SourceTitle = "artist.name.album.title", + Date = DateTime.UtcNow + }; } [Test] diff --git a/src/NzbDrone.Core.Test/Blacklisting/BlacklistServiceFixture.cs b/src/NzbDrone.Core.Test/Blacklisting/BlacklistServiceFixture.cs index eb4e1fa56..e90f1e710 100644 --- a/src/NzbDrone.Core.Test/Blacklisting/BlacklistServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Blacklisting/BlacklistServiceFixture.cs @@ -18,14 +18,14 @@ namespace NzbDrone.Core.Test.Blacklisting public void Setup() { _event = new DownloadFailedEvent - { - ArtistId = 12345, - AlbumIds = new List {1}, - Quality = new QualityModel(Quality.MP3_320), - SourceTitle = "artist.name.album.title", - DownloadClient = "SabnzbdClient", - DownloadId = "Sabnzbd_nzo_2dfh73k" - }; + { + ArtistId = 12345, + AlbumIds = new List { 1 }, + Quality = new QualityModel(Quality.MP3_320), + SourceTitle = "artist.name.album.title", + 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/Configuration/ConfigCachingFixture.cs b/src/NzbDrone.Core.Test/Configuration/ConfigCachingFixture.cs index 087a854d7..c903cb839 100644 --- a/src/NzbDrone.Core.Test/Configuration/ConfigCachingFixture.cs +++ b/src/NzbDrone.Core.Test/Configuration/ConfigCachingFixture.cs @@ -5,7 +5,6 @@ using NUnit.Framework; using NzbDrone.Core.Configuration; using NzbDrone.Core.Test.Framework; - namespace NzbDrone.Core.Test.Configuration { [TestFixture] @@ -16,7 +15,6 @@ namespace NzbDrone.Core.Test.Configuration { Mocker.GetMock().Setup(c => c.All()) .Returns(new List { new Config { Key = "key1", Value = "Value1" } }); - } [Test] @@ -28,6 +26,5 @@ namespace NzbDrone.Core.Test.Configuration 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 8ad51f1e7..346a2c956 100644 --- a/src/NzbDrone.Core.Test/Configuration/ConfigServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Configuration/ConfigServiceFixture.cs @@ -28,7 +28,6 @@ namespace NzbDrone.Core.Test.Configuration AssertUpsert(key, value); } - [Test] public void Get_value_should_return_default_when_no_value() { diff --git a/src/NzbDrone.Core.Test/Datastore/BasicRepositoryFixture.cs b/src/NzbDrone.Core.Test/Datastore/BasicRepositoryFixture.cs index e4775e037..68f7d9fb5 100644 --- a/src/NzbDrone.Core.Test/Datastore/BasicRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/BasicRepositoryFixture.cs @@ -9,14 +9,12 @@ using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Datastore { - [TestFixture] public class BasicRepositoryFixture : DbTest, ScheduledTask> { private ScheduledTask _basicType; - [SetUp] public void Setup() { @@ -44,10 +42,8 @@ namespace NzbDrone.Core.Test.Datastore Subject.Purge(); AllStoredModels.Should().BeEmpty(); - } - [Test] public void should_be_able_to_delete_model() { @@ -64,7 +60,7 @@ namespace NzbDrone.Core.Test.Datastore 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 @@ namespace NzbDrone.Core.Test.Datastore 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(); - } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/BooleanIntConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/BooleanIntConverterFixture.cs index 649a7303e..50e1b892b 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/BooleanIntConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/BooleanIntConverterFixture.cs @@ -27,9 +27,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters 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 @@ namespace NzbDrone.Core.Test.Datastore.Converters 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 @@ namespace NzbDrone.Core.Test.Datastore.Converters 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 56d42e54e..995cf106f 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/CommandConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/CommandConverterFixture.cs @@ -6,8 +6,8 @@ using Moq; using NUnit.Framework; using NzbDrone.Common.Serializer; using NzbDrone.Core.Datastore.Converters; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music.Commands; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Datastore.Converters { @@ -42,10 +42,10 @@ namespace NzbDrone.Core.Test.Datastore.Converters dataRecordMock.Setup(s => s.GetString(0)).Returns("RefreshArtist"); var context = new ConverterContext - { - DataRecord = dataRecordMock.Object, - DbValue = new RefreshArtistCommand().ToJson() - }; + { + DataRecord = dataRecordMock.Object, + DbValue = new RefreshArtistCommand().ToJson() + }; Subject.FromDB(context).Should().BeOfType(); } @@ -54,9 +54,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters 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 bf4974124..1b5c09c7a 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/DoubleConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/DoubleConverterFixture.cs @@ -36,9 +36,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters var expected = 10.5D; var context = new ConverterContext - { - DbValue = expected - }; + { + DbValue = expected + }; Subject.FromDB(context).Should().Be(expected); } @@ -49,9 +49,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters var expected = 10.5D; var context = new ConverterContext - { - DbValue = $"{expected}" - }; + { + DbValue = $"{expected}" + }; Subject.FromDB(context).Should().Be(expected); } @@ -60,9 +60,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters 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 49bd70074..8f9a23412 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.Converters; using Marr.Data.Mapping; using Moq; using NUnit.Framework; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Datastore.Converters { @@ -35,10 +35,10 @@ namespace NzbDrone.Core.Test.Datastore.Converters var expected = ArtistStatusType.Continuing; var context = new ConverterContext - { - ColumnMap = new ColumnMap(mockMemberInfo.Object) { FieldType = typeof(ArtistStatusType) }, - DbValue = (long)expected - }; + { + ColumnMap = new ColumnMap(mockMemberInfo.Object) { FieldType = typeof(ArtistStatusType) }, + DbValue = (long)expected + }; Subject.FromDB(context).Should().Be(expected); } @@ -47,9 +47,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters 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 8444fa053..2d4a8e530 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/GuidConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/GuidConverterFixture.cs @@ -30,9 +30,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters var guid = Guid.NewGuid(); var context = new ConverterContext - { - DbValue = guid.ToString() - }; + { + DbValue = guid.ToString() + }; Subject.FromDB(context).Should().Be(guid); } @@ -41,9 +41,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters 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 058436b38..db873b76c 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/Int32ConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/Int32ConverterFixture.cs @@ -22,9 +22,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters var i = 5; var context = new ConverterContext - { - DbValue = i - }; + { + DbValue = i + }; Subject.FromDB(context).Should().Be(i); } @@ -35,9 +35,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters var i = 5; var context = new ConverterContext - { - DbValue = i.ToString() - }; + { + DbValue = i.ToString() + }; Subject.FromDB(context).Should().Be(i); } @@ -46,9 +46,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters 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 8dae96853..815430323 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/OsPathConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/OsPathConverterFixture.cs @@ -28,9 +28,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters var osPath = new OsPath(path); var context = new ConverterContext - { - DbValue = path - }; + { + DbValue = path + }; Subject.FromDB(context).Should().Be(osPath); } @@ -39,9 +39,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters 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 9aafbee73..c36758be2 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/ProviderSettingConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/ProviderSettingConverterFixture.cs @@ -15,10 +15,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters public void should_return_null_config_if_config_is_null() { var result = Subject.FromDB(new ConverterContext() - { - DbValue = DBNull.Value - }); - + { + DbValue = DBNull.Value + }); result.Should().Be(NullConfig.Instance); } @@ -32,8 +31,7 @@ namespace NzbDrone.Core.Test.Datastore.Converters DbValue = dbValue }); - result.Should().Be(NullConfig.Instance); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/QualityIntConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/QualityIntConverterFixture.cs index 7809dd10a..ea1a24d78 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/QualityIntConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/QualityIntConverterFixture.cs @@ -37,9 +37,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters var quality = Quality.FLAC; var context = new ConverterContext - { - DbValue = quality.Id - }; + { + DbValue = quality.Id + }; Subject.FromDB(context).Should().Be(quality); } @@ -48,9 +48,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters 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(Quality.Unknown); } diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/TimeSpanConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/TimeSpanConverterFixture.cs index c96848179..a590bbe62 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/TimeSpanConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/TimeSpanConverterFixture.cs @@ -31,9 +31,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters var timeSpan = TimeSpan.FromMinutes(5); var context = new ConverterContext - { - DbValue = timeSpan - }; + { + DbValue = timeSpan + }; Subject.FromDB(context).Should().Be(timeSpan); } @@ -44,9 +44,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters var timeSpan = TimeSpan.FromMinutes(5); var context = new ConverterContext - { - DbValue = timeSpan.ToString("c", CultureInfo.InvariantCulture) - }; + { + DbValue = timeSpan.ToString("c", CultureInfo.InvariantCulture) + }; Subject.FromDB(context).Should().Be(timeSpan); } @@ -55,9 +55,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters public void should_return_time_span_zero_for_db_null_value_when_getting_from_db() { var context = new ConverterContext - { - DbValue = DBNull.Value - }; + { + DbValue = DBNull.Value + }; Subject.FromDB(context).Should().Be(TimeSpan.Zero); } diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/UtcConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/UtcConverterFixture.cs index 904f653d3..51c07a1b3 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/UtcConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/UtcConverterFixture.cs @@ -30,8 +30,8 @@ namespace NzbDrone.Core.Test.Datastore.Converters var dateTime = DateTime.Now.ToUniversalTime(); var context = new ConverterContext - { - DbValue = dateTime + { + DbValue = dateTime }; Subject.FromDB(context).Should().Be(dateTime); @@ -41,9 +41,9 @@ namespace NzbDrone.Core.Test.Datastore.Converters 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/DatabaseFixture.cs b/src/NzbDrone.Core.Test/Datastore/DatabaseFixture.cs index be8b6c7ec..b4dd4aefa 100644 --- a/src/NzbDrone.Core.Test/Datastore/DatabaseFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/DatabaseFixture.cs @@ -3,8 +3,8 @@ using System.Linq; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Datastore; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Datastore { @@ -20,7 +20,6 @@ namespace NzbDrone.Core.Test.Datastore .BeNull(); } - [Test] public void vaccume() { diff --git a/src/NzbDrone.Core.Test/Datastore/DatabaseRelationshipFixture.cs b/src/NzbDrone.Core.Test/Datastore/DatabaseRelationshipFixture.cs index 78a439466..40bc89410 100644 --- a/src/NzbDrone.Core.Test/Datastore/DatabaseRelationshipFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/DatabaseRelationshipFixture.cs @@ -1,12 +1,11 @@ +using System; using System.Linq; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; -using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Music; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; -using System; namespace NzbDrone.Core.Test.Datastore { @@ -54,11 +53,10 @@ namespace NzbDrone.Core.Test.Datastore Db.Single().TrackFile.Value.Should().BeNull(); } - [Test] public void embedded_document_as_json() { - var quality = new QualityModel { Quality = Quality.MP3_320, Revision = new Revision(version: 2 )}; + var quality = new QualityModel { Quality = Quality.MP3_320, Revision = new Revision(version: 2) }; var history = Builder.CreateNew() .With(c => c.Id = 0) @@ -81,7 +79,6 @@ namespace NzbDrone.Core.Test.Datastore history[0].Quality = new QualityModel(Quality.MP3_320, new Revision(version: 2)); history[1].Quality = new QualityModel(Quality.MP3_256, new Revision(version: 2)); - Db.InsertMany(history); var returnedHistory = Db.All(); diff --git a/src/NzbDrone.Core.Test/Datastore/MappingExtentionFixture.cs b/src/NzbDrone.Core.Test/Datastore/MappingExtentionFixture.cs index 7db539fc3..6fdc962af 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 @@ namespace NzbDrone.Core.Test.Datastore 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 9a5fdffe6..29ed98e2e 100644 --- a/src/NzbDrone.Core.Test/Datastore/MarrDataLazyLoadingFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/MarrDataLazyLoadingFixture.cs @@ -1,18 +1,17 @@ -using FizzWare.NBuilder; -using NUnit.Framework; -using NzbDrone.Core.Datastore; -using NzbDrone.Core.Profiles.Qualities; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.MediaFiles; -using Marr.Data.QGen; using System.Collections.Generic; using System.Linq; +using FizzWare.NBuilder; +using Marr.Data.QGen; +using NUnit.Framework; +using NzbDrone.Core.Datastore; +using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Music; +using NzbDrone.Core.Profiles.Qualities; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Datastore { - [TestFixture] public class MarrDataLazyLoadingFixture : DbTest { @@ -60,6 +59,7 @@ namespace NzbDrone.Core.Test.Datastore .With(v => v.ForeignReleaseId = "test" + album.Id) .Build()); } + Db.InsertMany(releases); var trackFiles = Builder.CreateListOfSize(1) @@ -85,9 +85,9 @@ namespace NzbDrone.Core.Test.Datastore public void should_join_artist_when_query_for_albums() { var db = Mocker.Resolve(); - var DataMapper = db.GetDataMapper(); + var dataMapper = db.GetDataMapper(); - var albums = DataMapper.Query() + var albums = dataMapper.Query() .Join(JoinType.Inner, v => v.Artist, (l, r) => l.ArtistMetadataId == r.ArtistMetadataId) .ToList(); @@ -101,9 +101,9 @@ namespace NzbDrone.Core.Test.Datastore public void should_lazy_load_profile_if_not_joined() { var db = Mocker.Resolve(); - var DataMapper = db.GetDataMapper(); + var dataMapper = db.GetDataMapper(); - var tracks = DataMapper.Query() + var tracks = dataMapper.Query() .Join(JoinType.Inner, v => v.AlbumRelease, (l, r) => l.AlbumReleaseId == r.Id) .Join(JoinType.Inner, v => v.Album, (l, r) => l.AlbumId == r.Id) .Join(JoinType.Inner, v => v.Artist, (l, r) => l.ArtistMetadataId == r.ArtistMetadataId) @@ -123,9 +123,9 @@ namespace NzbDrone.Core.Test.Datastore public void should_explicit_load_trackfile_if_joined() { var db = Mocker.Resolve(); - var DataMapper = db.GetDataMapper(); + var dataMapper = db.GetDataMapper(); - var tracks = DataMapper.Query() + var tracks = dataMapper.Query() .Join(JoinType.Inner, v => v.TrackFile, (l, r) => l.TrackFileId == r.Id) .ToList(); @@ -140,9 +140,9 @@ namespace NzbDrone.Core.Test.Datastore public void should_lazy_load_artist_for_track() { var db = Mocker.Resolve(); - var DataMapper = db.GetDataMapper(); + var dataMapper = db.GetDataMapper(); - var tracks = DataMapper.Query() + var tracks = dataMapper.Query() .ToList(); Assert.IsNotEmpty(tracks); @@ -159,9 +159,9 @@ namespace NzbDrone.Core.Test.Datastore public void should_lazy_load_artist_for_trackfile() { var db = Mocker.Resolve(); - var DataMapper = db.GetDataMapper(); + var dataMapper = db.GetDataMapper(); - var tracks = DataMapper.Query() + var tracks = dataMapper.Query() .ToList(); Assert.IsNotEmpty(tracks); @@ -178,9 +178,9 @@ namespace NzbDrone.Core.Test.Datastore public void should_lazy_load_trackfile_if_not_joined() { var db = Mocker.Resolve(); - var DataMapper = db.GetDataMapper(); + var dataMapper = db.GetDataMapper(); - var tracks = DataMapper.Query() + var tracks = dataMapper.Query() .ToList(); foreach (var track in tracks) @@ -195,9 +195,9 @@ namespace NzbDrone.Core.Test.Datastore public void should_explicit_load_everything_if_joined() { var db = Mocker.Resolve(); - var DataMapper = db.GetDataMapper(); + var dataMapper = db.GetDataMapper(); - var files = DataMapper.Query() + var files = dataMapper.Query() .Join(JoinType.Inner, f => f.Tracks, (f, t) => f.Id == t.TrackFileId) .Join(JoinType.Inner, t => t.Album, (t, a) => t.AlbumId == a.Id) .Join(JoinType.Inner, t => t.Artist, (t, a) => t.Album.Value.ArtistMetadataId == a.ArtistMetadataId) @@ -219,9 +219,9 @@ namespace NzbDrone.Core.Test.Datastore public void should_lazy_load_tracks_if_not_joined_to_trackfile() { var db = Mocker.Resolve(); - var DataMapper = db.GetDataMapper(); + var dataMapper = db.GetDataMapper(); - var files = DataMapper.Query() + var files = dataMapper.Query() .Join(JoinType.Inner, t => t.Album, (t, a) => t.AlbumId == a.Id) .Join(JoinType.Inner, t => t.Artist, (t, a) => t.Album.Value.ArtistMetadataId == a.ArtistMetadataId) .Join(JoinType.Inner, a => a.Metadata, (a, m) => a.ArtistMetadataId == m.Id) @@ -244,9 +244,9 @@ namespace NzbDrone.Core.Test.Datastore public void should_lazy_load_tracks_if_not_joined() { var db = Mocker.Resolve(); - var DataMapper = db.GetDataMapper(); + var dataMapper = db.GetDataMapper(); - var release = DataMapper.Query().Where(x => x.Id == 1).SingleOrDefault(); + var release = dataMapper.Query().Where(x => x.Id == 1).SingleOrDefault(); Assert.IsFalse(release.Tracks.IsLoaded); Assert.IsNotNull(release.Tracks.Value); @@ -258,9 +258,9 @@ namespace NzbDrone.Core.Test.Datastore public void should_lazy_load_track_if_not_joined() { var db = Mocker.Resolve(); - var DataMapper = db.GetDataMapper(); + var dataMapper = db.GetDataMapper(); - var tracks = DataMapper.Query() + var tracks = dataMapper.Query() .ToList(); foreach (var track in tracks) @@ -275,9 +275,9 @@ namespace NzbDrone.Core.Test.Datastore public void should_explicit_load_profile_if_joined() { var db = Mocker.Resolve(); - var DataMapper = db.GetDataMapper(); + var dataMapper = db.GetDataMapper(); - var tracks = DataMapper.Query() + var tracks = dataMapper.Query() .Join(JoinType.Inner, v => v.AlbumRelease, (l, r) => l.AlbumReleaseId == r.Id) .Join(JoinType.Inner, v => v.Album, (l, r) => l.AlbumId == r.Id) .Join(JoinType.Inner, v => v.Artist, (l, r) => l.ArtistMetadataId == r.ArtistMetadataId) diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/023_add_release_groups_etcFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/023_add_release_groups_etcFixture.cs index 4eb43de03..233968f4d 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/023_add_release_groups_etcFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/023_add_release_groups_etcFixture.cs @@ -1,12 +1,12 @@ +using System.Collections.Generic; using System.Linq; -using FluentAssertions; using FizzWare.NBuilder; +using FluentAssertions; using NUnit.Framework; +using NzbDrone.Common.Serializer; using NzbDrone.Core.Datastore.Migration; using NzbDrone.Core.Music; using NzbDrone.Core.Test.Framework; -using NzbDrone.Common.Serializer; -using System.Collections.Generic; namespace NzbDrone.Core.Test.Datastore.Migration { @@ -16,38 +16,38 @@ namespace NzbDrone.Core.Test.Datastore.Migration private void GivenArtist(add_release_groups_etc c, int id, string name) { c.Insert.IntoTable("Artists").Row(new - { - Id = id, - ForeignArtistId = id.ToString(), - Name = name, - CleanName = name, - Status = 1, - Images = "", - Path = $"/mnt/data/path/{name}", - Monitored = 1, - AlbumFolder = 1, - LanguageProfileId = 1, - MetadataProfileId = 1 - }); + { + Id = id, + ForeignArtistId = id.ToString(), + Name = name, + CleanName = name, + Status = 1, + Images = "", + Path = $"/mnt/data/path/{name}", + Monitored = 1, + AlbumFolder = 1, + LanguageProfileId = 1, + MetadataProfileId = 1 + }); } private void GivenAlbum(add_release_groups_etc c, int id, int artistId, string title, string currentRelease) { c.Insert.IntoTable("Albums").Row(new - { - Id = id, - ForeignAlbumId = id.ToString(), - ArtistId = artistId, - Title = title, - CleanTitle = title, - Images = "", - Monitored = 1, - AlbumType = "Studio", - Duration = 100, - Media = "", - Releases = "", - CurrentRelease = currentRelease - }); + { + Id = id, + ForeignAlbumId = id.ToString(), + ArtistId = artistId, + Title = title, + CleanTitle = title, + Images = "", + Monitored = 1, + AlbumType = "Studio", + Duration = 100, + Media = "", + Releases = "", + CurrentRelease = currentRelease + }); } private void GivenTracks(add_release_groups_etc c, int artistid, int albumid, int firstId, int count) @@ -56,19 +56,19 @@ namespace NzbDrone.Core.Test.Datastore.Migration { var id = firstId + i; c.Insert.IntoTable("Tracks").Row(new - { - Id = id, - ForeignTrackId = id.ToString(), - ArtistId = artistid, - AlbumId = albumid, - Explicit = 0, - Compilation = 0, - Monitored = 0, - Duration = 100, - MediumNumber = 1, - AbsoluteTrackNumber = i, - TrackNumber = i.ToString() - }); + { + Id = id, + ForeignTrackId = id.ToString(), + ArtistId = artistid, + AlbumId = albumid, + Explicit = 0, + Compilation = 0, + Monitored = 0, + Duration = 100, + MediumNumber = 1, + AbsoluteTrackNumber = i, + TrackNumber = i.ToString() + }); } } @@ -102,14 +102,14 @@ namespace NzbDrone.Core.Test.Datastore.Migration tracks.First().AlbumReleaseId.Should().Be(albumReleaseId); tracks.All(t => t.ArtistMetadataId == album.ArtistMetadataId).Should().BeTrue(); } - + [Test] public void migration_023_simple_case() { var release = Builder .CreateNew() .Build(); - + var db = WithMigrationTestDb(c => { GivenArtist(c, 1, "TestArtist"); @@ -128,7 +128,7 @@ namespace NzbDrone.Core.Test.Datastore.Migration .CreateNew() .With(e => e.MediaCount = 2) .Build(); - + var db = WithMigrationTestDb(c => { GivenArtist(c, 1, "TestArtist"); @@ -138,7 +138,7 @@ namespace NzbDrone.Core.Test.Datastore.Migration var migrated = VerifyAlbumReleases(db); migrated.First().Media.Count.Should().Be(2); - + VerifyTracks(db, 1, 1, 10); } @@ -197,7 +197,7 @@ namespace NzbDrone.Core.Test.Datastore.Migration var release = Builder .CreateNew() .Build(); - + var db = WithMigrationTestDb(c => { GivenArtist(c, 1, "TestArtist"); @@ -205,7 +205,6 @@ namespace NzbDrone.Core.Test.Datastore.Migration GivenTracks(c, 1, 1, 1, 10); GivenAlbum(c, 2, 1, "TestAlbum2", release.ToJson()); GivenTracks(c, 1, 2, 100, 10); - }); VerifyAlbumReleases(db); @@ -221,7 +220,7 @@ namespace NzbDrone.Core.Test.Datastore.Migration .All() .With(e => e.Id = "TestForeignId") .Build(); - + var db = WithMigrationTestDb(c => { GivenArtist(c, 1, "TestArtist"); @@ -229,7 +228,6 @@ namespace NzbDrone.Core.Test.Datastore.Migration GivenTracks(c, 1, 1, 1, 10); GivenAlbum(c, 2, 1, "TestAlbum2", releases[1].ToJson()); GivenTracks(c, 1, 2, 100, 10); - }); VerifyAlbumReleases(db); diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/030_add_mediafilerepository_mtimeFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/030_add_mediafilerepository_mtimeFixture.cs index b79248a61..201b6a99f 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/030_add_mediafilerepository_mtimeFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/030_add_mediafilerepository_mtimeFixture.cs @@ -1,14 +1,14 @@ -using NUnit.Framework; -using NzbDrone.Core.Datastore.Migration; -using NzbDrone.Core.Test.Framework; -using System.Collections.Generic; using System; -using NzbDrone.Core.Qualities; -using NzbDrone.Common.Serializer; -using NzbDrone.Test.Common; +using System.Collections.Generic; +using System.IO; using System.Linq; using FluentAssertions; -using System.IO; +using NUnit.Framework; +using NzbDrone.Common.Serializer; +using NzbDrone.Core.Datastore.Migration; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Datastore.Migration { @@ -16,51 +16,51 @@ namespace NzbDrone.Core.Test.Datastore.Migration public class add_mediafilerepository_mtimeFixture : MigrationTest { private string _artistPath = null; - + private void GivenArtist(add_mediafilerepository_mtime c, int id, string name) { _artistPath = $"/mnt/data/path/{name}".AsOsAgnostic(); c.Insert.IntoTable("Artists").Row(new - { - Id = id, - CleanName = name, - Path = _artistPath, - Monitored = 1, - AlbumFolder = 1, - LanguageProfileId = 1, - MetadataProfileId = 1, - ArtistMetadataId = id - }); + { + Id = id, + CleanName = name, + Path = _artistPath, + Monitored = 1, + AlbumFolder = 1, + LanguageProfileId = 1, + MetadataProfileId = 1, + ArtistMetadataId = id + }); } - + private void GivenAlbum(add_mediafilerepository_mtime c, int id, int artistMetadataId, string title) { c.Insert.IntoTable("Albums").Row(new - { - Id = id, - ForeignAlbumId = id.ToString(), - ArtistMetadataId = artistMetadataId, - Title = title, - CleanTitle = title, - Images = "", - Monitored = 1, - AlbumType = "Studio", - AnyReleaseOk = 1 - }); + { + Id = id, + ForeignAlbumId = id.ToString(), + ArtistMetadataId = artistMetadataId, + Title = title, + CleanTitle = title, + Images = "", + Monitored = 1, + AlbumType = "Studio", + AnyReleaseOk = 1 + }); } private void GivenAlbumRelease(add_mediafilerepository_mtime c, int id, int albumId, bool monitored) { c.Insert.IntoTable("AlbumReleases").Row(new - { - Id = id, - ForeignReleaseId = id.ToString(), - AlbumId = albumId, - Title = "Title", - Status = "Status", - Duration = 0, - Monitored = monitored - }); + { + Id = id, + ForeignReleaseId = id.ToString(), + AlbumId = albumId, + Title = "Title", + Status = "Status", + Duration = 0, + Monitored = monitored + }); } private void GivenTrackFiles(add_mediafilerepository_mtime c, List tracks, int albumReleaseId, int albumId, int firstId = 1, bool addTracks = true) @@ -69,42 +69,42 @@ namespace NzbDrone.Core.Test.Datastore.Migration foreach (var track in tracks) { c.Insert.IntoTable("TrackFiles").Row(new - { - Id = id, - RelativePath = track?.AsOsAgnostic(), - Size = 100, - DateAdded = DateTime.UtcNow, - Quality = new QualityModel(Quality.FLAC).ToJson(), - Language = 1, - AlbumId = albumId - }); - - if (addTracks) + { + Id = id, + RelativePath = track?.AsOsAgnostic(), + Size = 100, + DateAdded = DateTime.UtcNow, + Quality = new QualityModel(Quality.FLAC).ToJson(), + Language = 1, + AlbumId = albumId + }); + + if (addTracks) { c.Insert.IntoTable("Tracks").Row(new - { - Id = id, - ForeignTrackId = id.ToString(), - Explicit = 0, - TrackFileId = id, - Duration = 100, - MediumNumber = 1, - AbsoluteTrackNumber = 1, - ForeignRecordingId = id.ToString(), - AlbumReleaseId = albumReleaseId, - ArtistMetadataId = 0 - }); + { + Id = id, + ForeignTrackId = id.ToString(), + Explicit = 0, + TrackFileId = id, + Duration = 100, + MediumNumber = 1, + AbsoluteTrackNumber = 1, + ForeignRecordingId = id.ToString(), + AlbumReleaseId = albumReleaseId, + ArtistMetadataId = 0 + }); } id++; } } - + private void VerifyTracksFiles(IDirectDataMapper db, int albumId, List expectedPaths) { var tracks = db.Query("SELECT TrackFiles.* FROM TrackFiles " + "WHERE TrackFiles.AlbumId = " + albumId); - + TestLogger.Debug($"Got {tracks.Count} tracks"); tracks.Select(x => x["Path"]).Should().BeEquivalentTo(expectedPaths); @@ -113,209 +113,231 @@ namespace NzbDrone.Core.Test.Datastore.Migration [Test] public void migration_030_simple_case() { - var tracks = new List { + var tracks = new List + { "folder/track1.mp3", "folder/track2.mp3", }; - - var db = WithMigrationTestDb(c => { - GivenArtist(c, 1, "TestArtist"); - GivenAlbum(c, 1, 1, "TestAlbum"); - GivenAlbumRelease(c, 1, 1, true); - GivenTrackFiles(c, tracks, 1, 1); - }); - + + var db = WithMigrationTestDb(c => + { + GivenArtist(c, 1, "TestArtist"); + GivenAlbum(c, 1, 1, "TestAlbum"); + GivenAlbumRelease(c, 1, 1, true); + GivenTrackFiles(c, tracks, 1, 1); + }); + var expected = tracks.Select(x => Path.Combine(_artistPath, x)).ToList(); - + VerifyTracksFiles(db, 1, expected); } [Test] public void migration_030_missing_path() { - var tracks = new List { + var tracks = new List + { "folder/track1.mp3", null, }; - - var db = WithMigrationTestDb(c => { - GivenArtist(c, 1, "TestArtist"); - GivenAlbum(c, 1, 1, "TestAlbum"); - GivenAlbumRelease(c, 1, 1, true); - GivenTrackFiles(c, tracks, 1, 1); - }); - + + var db = WithMigrationTestDb(c => + { + GivenArtist(c, 1, "TestArtist"); + GivenAlbum(c, 1, 1, "TestAlbum"); + GivenAlbumRelease(c, 1, 1, true); + GivenTrackFiles(c, tracks, 1, 1); + }); + var expected = tracks.GetRange(0, 1).Select(x => Path.Combine(_artistPath, x)).ToList(); - + VerifyTracksFiles(db, 1, expected); } - + [Test] public void migration_030_bad_albumrelease_id() { - var tracks = new List { + var tracks = new List + { "folder/track1.mp3", "folder/track2.mp3" }; - - var db = WithMigrationTestDb(c => { - GivenArtist(c, 1, "TestArtist"); - GivenAlbum(c, 1, 1, "TestAlbum"); - GivenAlbumRelease(c, 1, 1, true); - GivenTrackFiles(c, tracks, 2, 1); - }); - + + var db = WithMigrationTestDb(c => + { + GivenArtist(c, 1, "TestArtist"); + GivenAlbum(c, 1, 1, "TestAlbum"); + GivenAlbumRelease(c, 1, 1, true); + GivenTrackFiles(c, tracks, 2, 1); + }); + VerifyTracksFiles(db, 1, new List()); } [Test] public void migration_030_bad_album_id() { - var tracks = new List { + var tracks = new List + { "folder/track1.mp3", "folder/track2.mp3" }; - - var db = WithMigrationTestDb(c => { - GivenArtist(c, 1, "TestArtist"); - GivenAlbum(c, 1, 1, "TestAlbum"); - GivenAlbumRelease(c, 1, 1, true); - GivenTrackFiles(c, tracks, 1, 2); - }); - + + var db = WithMigrationTestDb(c => + { + GivenArtist(c, 1, "TestArtist"); + GivenAlbum(c, 1, 1, "TestAlbum"); + GivenAlbumRelease(c, 1, 1, true); + GivenTrackFiles(c, tracks, 1, 2); + }); + VerifyTracksFiles(db, 1, new List()); } [Test] public void migration_030_bad_artist_metadata_id() { - var tracks = new List { + var tracks = new List + { "folder/track1.mp3", "folder/track2.mp3" }; - - var db = WithMigrationTestDb(c => { - GivenArtist(c, 1, "TestArtist"); - GivenAlbum(c, 1, 2, "TestAlbum"); - GivenAlbumRelease(c, 1, 1, true); - GivenTrackFiles(c, tracks, 1, 1); - }); - + + var db = WithMigrationTestDb(c => + { + GivenArtist(c, 1, "TestArtist"); + GivenAlbum(c, 1, 2, "TestAlbum"); + GivenAlbumRelease(c, 1, 1, true); + GivenTrackFiles(c, tracks, 1, 1); + }); + VerifyTracksFiles(db, 1, new List()); } [Test] public void migration_030_missing_artist() { - var tracks = new List { + var tracks = new List + { "folder/track1.mp3", "folder/track2.mp3" }; - - var db = WithMigrationTestDb(c => { - GivenAlbum(c, 1, 1, "TestAlbum"); - GivenAlbumRelease(c, 1, 1, true); - GivenTrackFiles(c, tracks, 1, 1); - }); - + + var db = WithMigrationTestDb(c => + { + GivenAlbum(c, 1, 1, "TestAlbum"); + GivenAlbumRelease(c, 1, 1, true); + GivenTrackFiles(c, tracks, 1, 1); + }); + VerifyTracksFiles(db, 1, new List()); } [Test] public void migration_030_missing_tracks() { - var tracks = new List { + var tracks = new List + { "folder/track1.mp3", "folder/track2.mp3" }; - - var db = WithMigrationTestDb(c => { - GivenArtist(c, 1, "TestArtist"); - GivenAlbum(c, 1, 1, "TestAlbum"); - GivenAlbumRelease(c, 1, 1, true); - GivenTrackFiles(c, tracks, 1, 1, addTracks: false); - }); - + + var db = WithMigrationTestDb(c => + { + GivenArtist(c, 1, "TestArtist"); + GivenAlbum(c, 1, 1, "TestAlbum"); + GivenAlbumRelease(c, 1, 1, true); + GivenTrackFiles(c, tracks, 1, 1, addTracks: false); + }); + VerifyTracksFiles(db, 1, new List()); } [Test] public void migration_030_duplicate_files() { - var tracks = new List { + var tracks = new List + { "folder/track1.mp3", "folder/track2.mp3", "folder/track1.mp3", }; - - var db = WithMigrationTestDb(c => { - GivenArtist(c, 1, "TestArtist"); - GivenAlbum(c, 1, 1, "TestAlbum"); - GivenAlbumRelease(c, 1, 1, true); - GivenTrackFiles(c, tracks, 1, 1); - }); + + var db = WithMigrationTestDb(c => + { + GivenArtist(c, 1, "TestArtist"); + GivenAlbum(c, 1, 1, "TestAlbum"); + GivenAlbumRelease(c, 1, 1, true); + GivenTrackFiles(c, tracks, 1, 1); + }); var expected = tracks.GetRange(0, 2).Select(x => Path.Combine(_artistPath, x)).ToList(); - + VerifyTracksFiles(db, 1, expected); } [Test] public void migration_030_unmonitored_release_duplicate() { - var monitored_tracks = new List { + var monitored_tracks = new List + { "folder/track1.mp3", "folder/track2.mp3", }; - var unmonitored_tracks = new List { + var unmonitored_tracks = new List + { "folder/track1.mp3", "folder/track2.mp3", }; - - var db = WithMigrationTestDb(c => { - GivenArtist(c, 1, "TestArtist"); - GivenAlbum(c, 1, 1, "TestAlbum"); - GivenAlbumRelease(c, 1, 1, true); - GivenTrackFiles(c, monitored_tracks, 1, 1); + var db = WithMigrationTestDb(c => + { + GivenArtist(c, 1, "TestArtist"); + GivenAlbum(c, 1, 1, "TestAlbum"); - GivenAlbumRelease(c, 2, 1, false); - GivenTrackFiles(c, unmonitored_tracks, 2, 1, firstId: 100); - }); + GivenAlbumRelease(c, 1, 1, true); + GivenTrackFiles(c, monitored_tracks, 1, 1); + + GivenAlbumRelease(c, 2, 1, false); + GivenTrackFiles(c, unmonitored_tracks, 2, 1, firstId: 100); + }); var expected = monitored_tracks.Select(x => Path.Combine(_artistPath, x)).ToList(); - + VerifyTracksFiles(db, 1, expected); } [Test] public void migration_030_unmonitored_release_distinct() { - var monitored_tracks = new List { + var monitored_tracks = new List + { "folder/track1.mp3", "folder/track2.mp3", }; - var unmonitored_tracks = new List { + var unmonitored_tracks = new List + { "folder/track3.mp3", "folder/track4.mp3", }; - - var db = WithMigrationTestDb(c => { - GivenArtist(c, 1, "TestArtist"); - GivenAlbum(c, 1, 1, "TestAlbum"); - GivenAlbumRelease(c, 1, 1, true); - GivenTrackFiles(c, monitored_tracks, 1, 1); + var db = WithMigrationTestDb(c => + { + GivenArtist(c, 1, "TestArtist"); + GivenAlbum(c, 1, 1, "TestAlbum"); - GivenAlbumRelease(c, 2, 1, false); - GivenTrackFiles(c, unmonitored_tracks, 2, 1, firstId: 100); - }); + GivenAlbumRelease(c, 1, 1, true); + GivenTrackFiles(c, monitored_tracks, 1, 1); + + GivenAlbumRelease(c, 2, 1, false); + GivenTrackFiles(c, unmonitored_tracks, 2, 1, firstId: 100); + }); var expected = monitored_tracks.Select(x => Path.Combine(_artistPath, x)).ToList(); - + VerifyTracksFiles(db, 1, expected); } - } + } } diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/031_add_artistmetadataid_constraintFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/031_add_artistmetadataid_constraintFixture.cs index df031267a..4af321c33 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/031_add_artistmetadataid_constraintFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/031_add_artistmetadataid_constraintFixture.cs @@ -1,10 +1,10 @@ -using NUnit.Framework; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Datastore.Migration; -using NzbDrone.Test.Common; +using System.Collections.Generic; using System.Linq; using FluentAssertions; -using System.Collections.Generic; +using NUnit.Framework; +using NzbDrone.Core.Datastore.Migration; +using NzbDrone.Core.Test.Framework; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Datastore.Migration { @@ -16,31 +16,31 @@ namespace NzbDrone.Core.Test.Datastore.Migration private void GivenArtistMetadata(add_artistmetadataid_constraint c, int id, string name) { c.Insert.IntoTable("ArtistMetadata").Row(new - { - Id = id, - ForeignArtistId = id, - Name = name, - Status = 1, - Images = "images" - }); + { + Id = id, + ForeignArtistId = id, + Name = name, + Status = 1, + Images = "images" + }); } - + private void GivenArtist(add_artistmetadataid_constraint c, int id, int artistMetadataId, string name) { _artistPath = $"/mnt/data/path/{name}".AsOsAgnostic(); c.Insert.IntoTable("Artists").Row(new - { - Id = id, - ArtistMetadataId = artistMetadataId, - CleanName = name, - Path = _artistPath, - Monitored = 1, - AlbumFolder = 1, - LanguageProfileId = 1, - MetadataProfileId = 1, - }); + { + Id = id, + ArtistMetadataId = artistMetadataId, + CleanName = name, + Path = _artistPath, + Monitored = 1, + AlbumFolder = 1, + LanguageProfileId = 1, + MetadataProfileId = 1, + }); } - + private void VerifyArtists(IDirectDataMapper db, List ids) { var artists = db.Query("SELECT Artists.* from Artists"); @@ -52,14 +52,15 @@ namespace NzbDrone.Core.Test.Datastore.Migration duplicates.Should().BeEmpty(); } - + [Test] public void migration_031_should_not_remove_unique_artist() { - var db = WithMigrationTestDb(c => { - GivenArtistMetadata(c, 1, "test"); - GivenArtist(c, 1, 1, "test"); - }); + var db = WithMigrationTestDb(c => + { + GivenArtistMetadata(c, 1, "test"); + GivenArtist(c, 1, 1, "test"); + }); VerifyArtists(db, new List { 1 }); } @@ -67,13 +68,14 @@ namespace NzbDrone.Core.Test.Datastore.Migration [Test] public void migration_031_should_not_remove_either_unique_artist() { - var db = WithMigrationTestDb(c => { - GivenArtistMetadata(c, 1, "test"); - GivenArtist(c, 1, 1, "test"); + var db = WithMigrationTestDb(c => + { + GivenArtistMetadata(c, 1, "test"); + GivenArtist(c, 1, 1, "test"); - GivenArtistMetadata(c, 2, "test2"); - GivenArtist(c, 2, 2, "test2"); - }); + GivenArtistMetadata(c, 2, "test2"); + GivenArtist(c, 2, 2, "test2"); + }); VerifyArtists(db, new List { 1, 2 }); } @@ -81,12 +83,13 @@ namespace NzbDrone.Core.Test.Datastore.Migration [Test] public void migration_031_should_remove_duplicate_artist() { - var db = WithMigrationTestDb(c => { - GivenArtistMetadata(c, 1, "test"); - GivenArtist(c, 1, 1, "test"); + var db = WithMigrationTestDb(c => + { + GivenArtistMetadata(c, 1, "test"); + GivenArtist(c, 1, 1, "test"); - GivenArtist(c, 2, 1, "test2"); - }); + GivenArtist(c, 2, 1, "test2"); + }); VerifyArtists(db, new List { 1 }); } @@ -94,18 +97,18 @@ namespace NzbDrone.Core.Test.Datastore.Migration [Test] public void migration_031_should_remove_all_duplicate_artists() { - var db = WithMigrationTestDb(c => { - GivenArtistMetadata(c, 1, "test"); - GivenArtist(c, 1, 1, "test"); - GivenArtist(c, 2, 1, "test"); - GivenArtist(c, 3, 1, "test"); - GivenArtist(c, 4, 1, "test"); + var db = WithMigrationTestDb(c => + { + GivenArtistMetadata(c, 1, "test"); + GivenArtist(c, 1, 1, "test"); + GivenArtist(c, 2, 1, "test"); + GivenArtist(c, 3, 1, "test"); + GivenArtist(c, 4, 1, "test"); - GivenArtistMetadata(c, 2, "test2"); - GivenArtist(c, 5, 2, "test2"); - GivenArtist(c, 6, 2, "test2"); - - }); + GivenArtistMetadata(c, 2, "test2"); + GivenArtist(c, 5, 2, "test2"); + GivenArtist(c, 6, 2, "test2"); + }); VerifyArtists(db, new List { 1, 5 }); } diff --git a/src/NzbDrone.Core.Test/Datastore/ObjectDatabaseFixture.cs b/src/NzbDrone.Core.Test/Datastore/ObjectDatabaseFixture.cs index 84037c050..08577f42a 100644 --- a/src/NzbDrone.Core.Test/Datastore/ObjectDatabaseFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/ObjectDatabaseFixture.cs @@ -22,7 +22,6 @@ namespace NzbDrone.Core.Test.Datastore .CreateNew() .With(s => s.Id = 0) .Build(); - } [Test] @@ -72,13 +71,12 @@ namespace NzbDrone.Core.Test.Datastore _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 @@ namespace NzbDrone.Core.Test.Datastore 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 @@ namespace NzbDrone.Core.Test.Datastore 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 7a39cc708..f98a43623 100644 --- a/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/PagingOffsetFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/PagingOffsetFixture.cs @@ -15,15 +15,14 @@ namespace NzbDrone.Core.Test.Datastore.PagingSpecExtensionsTests public void should_calcuate_expected_offset(int page, int pageSize, int expected) { var pagingSpec = new PagingSpec - { - Page = page, - PageSize = pageSize, - SortDirection = SortDirection.Ascending, - SortKey = "ReleaseDate" - }; + { + Page = page, + PageSize = pageSize, + SortDirection = SortDirection.Ascending, + SortKey = "ReleaseDate" + }; 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 cd70cb4e3..d4b312645 100644 --- a/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/ToSortDirectionFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/ToSortDirectionFixture.cs @@ -26,11 +26,11 @@ namespace NzbDrone.Core.Test.Datastore.PagingSpecExtensionsTests public void should_convert_ascending_to_asc() { var pagingSpec = new PagingSpec - { - Page = 1, - PageSize = 10, - SortDirection = SortDirection.Ascending, - SortKey = "ReleaseDate" + { + Page = 1, + PageSize = 10, + SortDirection = SortDirection.Ascending, + SortKey = "ReleaseDate" }; 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 48a1a3639..810ae5790 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() + { - }*/ - + }*/ } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Datastore/SqliteSchemaDumperTests/SqliteSchemaDumperFixture.cs b/src/NzbDrone.Core.Test/Datastore/SqliteSchemaDumperTests/SqliteSchemaDumperFixture.cs index 218b5e93f..64efa19ba 100644 --- a/src/NzbDrone.Core.Test/Datastore/SqliteSchemaDumperTests/SqliteSchemaDumperFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/SqliteSchemaDumperTests/SqliteSchemaDumperFixture.cs @@ -64,7 +64,7 @@ namespace NzbDrone.Core.Test.Datastore.SqliteSchemaDumperTests result.Columns.First().Name.Should().Be("MyId"); result.Columns.First().Type.Should().BeNull(); } - + [Test] public void should_ignore_unknown_symbols() { @@ -76,7 +76,6 @@ namespace NzbDrone.Core.Test.Datastore.SqliteSchemaDumperTests 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 c07b8d6df..06f3ad8a0 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/AcceptableSizeSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/AcceptableSizeSpecificationFixture.cs @@ -5,10 +5,10 @@ using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -19,18 +19,20 @@ namespace NzbDrone.Core.Test.DecisionEngineTests private const int HIGH_KBPS_BITRATE = 1600; private const int TWENTY_MINUTE_EP_MILLIS = 20 * 60 * 1000; private const int FORTY_FIVE_MINUTE_LP_MILLIS = 45 * 60 * 1000; - private RemoteAlbum parseResultMultiSet; - private RemoteAlbum parseResultMulti; - private RemoteAlbum parseResultSingle; - private Artist artist; - private QualityDefinition qualityType; + private RemoteAlbum _parseResultMultiSet; + private RemoteAlbum _parseResultMulti; + private RemoteAlbum _parseResultSingle; + private Artist _artist; + private QualityDefinition _qualityType; private Album AlbumBuilder(int id = 0) { return new Album { Id = id, - AlbumReleases = new List { new AlbumRelease + AlbumReleases = new List + { + new AlbumRelease { Duration = 0, Monitored = true @@ -42,60 +44,63 @@ namespace NzbDrone.Core.Test.DecisionEngineTests [SetUp] public void Setup() { - artist = Builder.CreateNew() + _artist = Builder.CreateNew() .Build(); - parseResultMultiSet = new RemoteAlbum + _parseResultMultiSet = new RemoteAlbum { - Artist = artist, - Release = new ReleaseInfo(), - ParsedAlbumInfo = new ParsedAlbumInfo { Quality = new QualityModel(Quality.MP3_192, new Revision(version: 2)) }, - Albums = new List { AlbumBuilder(), AlbumBuilder(), AlbumBuilder(), AlbumBuilder(), AlbumBuilder(), AlbumBuilder() } - }; + Artist = _artist, + Release = new ReleaseInfo(), + ParsedAlbumInfo = new ParsedAlbumInfo { Quality = new QualityModel(Quality.MP3_192, new Revision(version: 2)) }, + Albums = new List { AlbumBuilder(), AlbumBuilder(), AlbumBuilder(), AlbumBuilder(), AlbumBuilder(), AlbumBuilder() } + }; - parseResultMulti = new RemoteAlbum + _parseResultMulti = new RemoteAlbum { - Artist = artist, - Release = new ReleaseInfo(), - ParsedAlbumInfo = new ParsedAlbumInfo { Quality = new QualityModel(Quality.MP3_192, new Revision(version: 2)) }, - Albums = new List { AlbumBuilder(), AlbumBuilder() } - }; + Artist = _artist, + Release = new ReleaseInfo(), + ParsedAlbumInfo = new ParsedAlbumInfo { Quality = new QualityModel(Quality.MP3_192, new Revision(version: 2)) }, + Albums = new List { AlbumBuilder(), AlbumBuilder() } + }; - parseResultSingle = new RemoteAlbum + _parseResultSingle = new RemoteAlbum { - Artist = artist, - Release = new ReleaseInfo(), - ParsedAlbumInfo = new ParsedAlbumInfo { Quality = new QualityModel(Quality.MP3_192, new Revision(version: 2)) }, - Albums = new List { AlbumBuilder(2) } - - }; + Artist = _artist, + Release = new ReleaseInfo(), + ParsedAlbumInfo = new ParsedAlbumInfo { Quality = new QualityModel(Quality.MP3_192, new Revision(version: 2)) }, + Albums = new List { AlbumBuilder(2) } + }; Mocker.GetMock() .Setup(v => v.Get(It.IsAny())) .Returns(v => Quality.DefaultQualityDefinitions.First(c => c.Quality == v)); - qualityType = Builder.CreateNew() + _qualityType = Builder.CreateNew() .With(q => q.MinSize = 150) .With(q => q.MaxSize = 210) .With(q => q.Quality = Quality.MP3_192) .Build(); - Mocker.GetMock().Setup(s => s.Get(Quality.MP3_192)).Returns(qualityType); + Mocker.GetMock().Setup(s => s.Get(Quality.MP3_192)).Returns(_qualityType); Mocker.GetMock().Setup( s => s.GetAlbumsByArtist(It.IsAny())) - .Returns(new List() { + .Returns(new List() + { AlbumBuilder(), AlbumBuilder(), AlbumBuilder(), AlbumBuilder(), AlbumBuilder(), - AlbumBuilder(), AlbumBuilder(), AlbumBuilder(), AlbumBuilder(2), AlbumBuilder() }); + AlbumBuilder(), AlbumBuilder(), AlbumBuilder(), AlbumBuilder(2), AlbumBuilder() + }); } private void GivenLastAlbum() { Mocker.GetMock().Setup( s => s.GetAlbumsByArtist(It.IsAny())) - .Returns(new List { + .Returns(new List + { AlbumBuilder(), AlbumBuilder(), AlbumBuilder(), AlbumBuilder(), AlbumBuilder(), - AlbumBuilder(), AlbumBuilder(), AlbumBuilder(), AlbumBuilder(), AlbumBuilder(2) }); + AlbumBuilder(), AlbumBuilder(), AlbumBuilder(), AlbumBuilder(), AlbumBuilder(2) + }); } [TestCase(TWENTY_MINUTE_EP_MILLIS, 20, false)] @@ -106,11 +111,15 @@ namespace NzbDrone.Core.Test.DecisionEngineTests [TestCase(FORTY_FIVE_MINUTE_LP_MILLIS, 75, false)] public void single_album(int runtime, int sizeInMegaBytes, bool expectedResult) { - parseResultSingle.Albums.Select(c => { c.AlbumReleases.Value[0].Duration = runtime; return c; }).ToList(); - parseResultSingle.Artist = artist; - parseResultSingle.Release.Size = sizeInMegaBytes.Megabytes(); + _parseResultSingle.Albums.Select(c => + { + c.AlbumReleases.Value[0].Duration = runtime; + return c; + }).ToList(); + _parseResultSingle.Artist = _artist; + _parseResultSingle.Release.Size = sizeInMegaBytes.Megabytes(); - Subject.IsSatisfiedBy(parseResultSingle, null).Accepted.Should().Be(expectedResult); + Subject.IsSatisfiedBy(_parseResultSingle, null).Accepted.Should().Be(expectedResult); } [TestCase(TWENTY_MINUTE_EP_MILLIS, 20 * 2, false)] @@ -121,11 +130,15 @@ namespace NzbDrone.Core.Test.DecisionEngineTests [TestCase(FORTY_FIVE_MINUTE_LP_MILLIS, 75 * 2, false)] public void multi_album(int runtime, int sizeInMegaBytes, bool expectedResult) { - parseResultMulti.Albums.Select(c => { c.AlbumReleases.Value[0].Duration = runtime; return c; }).ToList(); - parseResultMulti.Artist = artist; - parseResultMulti.Release.Size = sizeInMegaBytes.Megabytes(); + _parseResultMulti.Albums.Select(c => + { + c.AlbumReleases.Value[0].Duration = runtime; + return c; + }).ToList(); + _parseResultMulti.Artist = _artist; + _parseResultMulti.Release.Size = sizeInMegaBytes.Megabytes(); - Subject.IsSatisfiedBy(parseResultMulti, null).Accepted.Should().Be(expectedResult); + Subject.IsSatisfiedBy(_parseResultMulti, null).Accepted.Should().Be(expectedResult); } [TestCase(TWENTY_MINUTE_EP_MILLIS, 20 * 6, false)] @@ -136,49 +149,64 @@ namespace NzbDrone.Core.Test.DecisionEngineTests [TestCase(FORTY_FIVE_MINUTE_LP_MILLIS, 75 * 6, false)] public void multiset_album(int runtime, int sizeInMegaBytes, bool expectedResult) { - parseResultMultiSet.Albums.Select(c => { c.AlbumReleases.Value[0].Duration = runtime; return c; }).ToList(); - parseResultMultiSet.Artist = artist; - parseResultMultiSet.Release.Size = sizeInMegaBytes.Megabytes(); + _parseResultMultiSet.Albums.Select(c => + { + c.AlbumReleases.Value[0].Duration = runtime; + return c; + }).ToList(); + _parseResultMultiSet.Artist = _artist; + _parseResultMultiSet.Release.Size = sizeInMegaBytes.Megabytes(); - Subject.IsSatisfiedBy(parseResultMultiSet, null).Accepted.Should().Be(expectedResult); + Subject.IsSatisfiedBy(_parseResultMultiSet, null).Accepted.Should().Be(expectedResult); } [Test] public void should_return_true_if_size_is_zero() { GivenLastAlbum(); - parseResultSingle.Albums.Select(c => { c.AlbumReleases.Value[0].Duration = TWENTY_MINUTE_EP_MILLIS; return c; }).ToList(); - parseResultSingle.Artist = artist; - parseResultSingle.Release.Size = 0; - qualityType.MinSize = 150; - qualityType.MaxSize = 210; + _parseResultSingle.Albums.Select(c => + { + c.AlbumReleases.Value[0].Duration = TWENTY_MINUTE_EP_MILLIS; + return c; + }).ToList(); + _parseResultSingle.Artist = _artist; + _parseResultSingle.Release.Size = 0; + _qualityType.MinSize = 150; + _qualityType.MaxSize = 210; - Subject.IsSatisfiedBy(parseResultSingle, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_parseResultSingle, null).Accepted.Should().BeTrue(); } [Test] public void should_return_true_if_unlimited_20_minute() { GivenLastAlbum(); - parseResultSingle.Albums.Select(c => { c.AlbumReleases.Value[0].Duration = TWENTY_MINUTE_EP_MILLIS; return c; }).ToList(); - parseResultSingle.Artist = artist; - parseResultSingle.Release.Size = (HIGH_KBPS_BITRATE * 128) * (TWENTY_MINUTE_EP_MILLIS / 1000); - qualityType.MaxSize = null; + _parseResultSingle.Albums.Select(c => + { + c.AlbumReleases.Value[0].Duration = TWENTY_MINUTE_EP_MILLIS; + return c; + }).ToList(); + _parseResultSingle.Artist = _artist; + _parseResultSingle.Release.Size = (HIGH_KBPS_BITRATE * 128) * (TWENTY_MINUTE_EP_MILLIS / 1000); + _qualityType.MaxSize = null; - Subject.IsSatisfiedBy(parseResultSingle, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_parseResultSingle, null).Accepted.Should().BeTrue(); } - + [Test] public void should_return_true_if_unlimited_45_minute() { GivenLastAlbum(); - parseResultSingle.Albums.Select(c => { c.AlbumReleases.Value[0].Duration = FORTY_FIVE_MINUTE_LP_MILLIS; return c; }).ToList(); - parseResultSingle.Artist = artist; - parseResultSingle.Release.Size = (HIGH_KBPS_BITRATE * 128) * (FORTY_FIVE_MINUTE_LP_MILLIS / 1000); - qualityType.MaxSize = null; + _parseResultSingle.Albums.Select(c => + { + c.AlbumReleases.Value[0].Duration = FORTY_FIVE_MINUTE_LP_MILLIS; + return c; + }).ToList(); + _parseResultSingle.Artist = _artist; + _parseResultSingle.Release.Size = (HIGH_KBPS_BITRATE * 128) * (FORTY_FIVE_MINUTE_LP_MILLIS / 1000); + _qualityType.MaxSize = null; - Subject.IsSatisfiedBy(parseResultSingle, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_parseResultSingle, null).Accepted.Should().BeTrue(); } - } } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/AlreadyImportedSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/AlreadyImportedSpecificationFixture.cs index 8342e79e7..4d4295433 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/AlreadyImportedSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/AlreadyImportedSpecificationFixture.cs @@ -1,19 +1,18 @@ using System; using System.Collections.Generic; -using System.Linq; using FizzWare.NBuilder; using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Core.Configuration; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.History; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Music; -using NzbDrone.Core.DecisionEngine.Specifications; -using NzbDrone.Core.Indexers; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.MediaFiles; namespace NzbDrone.Core.Test.DecisionEngineTests { diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/CutoffSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/CutoffSpecificationFixture.cs index 66b8df8aa..a616b2d97 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/CutoffSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/CutoffSpecificationFixture.cs @@ -1,10 +1,10 @@ +using System.Collections.Generic; using FluentAssertions; using NUnit.Framework; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; -using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Test.Framework; -using System.Collections.Generic; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -18,7 +18,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests { Subject.CutoffNotMet( new QualityProfile - { Cutoff = Quality.MP3_256.Id, Items = Qualities.QualityFixture.GetDefaultQualities() @@ -45,7 +44,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests { Subject.CutoffNotMet( new QualityProfile - { Cutoff = Quality.MP3_256.Id, Items = Qualities.QualityFixture.GetDefaultQualities() @@ -59,7 +57,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests { Subject.CutoffNotMet( new QualityProfile - { Cutoff = Quality.MP3_320.Id, Items = Qualities.QualityFixture.GetDefaultQualities() @@ -67,7 +64,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests new List { new QualityModel(Quality.MP3_320, new Revision(version: 1)) }, NoPreferredWordScore, new QualityModel(Quality.MP3_320, new Revision(version: 2))).Should().BeTrue(); - } [Test] @@ -75,7 +71,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests { Subject.CutoffNotMet( new QualityProfile - { Cutoff = Quality.MP3_320.Id, Items = Qualities.QualityFixture.GetDefaultQualities() @@ -88,32 +83,31 @@ namespace NzbDrone.Core.Test.DecisionEngineTests [Test] public void should_return_true_if_cutoffs_are_met_and_score_is_higher() { - QualityProfile _profile = new QualityProfile + QualityProfile profile = new QualityProfile { Cutoff = Quality.MP3_320.Id, Items = Qualities.QualityFixture.GetDefaultQualities(), }; Subject.CutoffNotMet( - _profile, + profile, new List { new QualityModel(Quality.MP3_320, new Revision(version: 2)) }, NoPreferredWordScore, new QualityModel(Quality.FLAC, new Revision(version: 2)), 10).Should().BeTrue(); } - [Test] public void should_return_true_if_cutoffs_are_met_but_is_a_revision_upgrade() { - QualityProfile _profile = new QualityProfile + QualityProfile profile = new QualityProfile { Cutoff = Quality.MP3_320.Id, Items = Qualities.QualityFixture.GetDefaultQualities(), }; Subject.CutoffNotMet( - _profile, + profile, new List { new QualityModel(Quality.FLAC, new Revision(version: 1)) }, NoPreferredWordScore, new QualityModel(Quality.FLAC, new Revision(version: 2)), diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/DiscographySpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/DiscographySpecificationFixture.cs index f12bbaf00..f6a87b092 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/DiscographySpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/DiscographySpecificationFixture.cs @@ -1,14 +1,14 @@ using System; +using System.Collections.Generic; +using System.Linq; +using FizzWare.NBuilder; +using FluentAssertions; +using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using FizzWare.NBuilder; -using System.Linq; -using FluentAssertions; -using NzbDrone.Core.Music; -using Moq; -using System.Collections.Generic; namespace NzbDrone.Core.Test.DecisionEngineTests { diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/DownloadDecisionMakerFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/DownloadDecisionMakerFixture.cs index 8d8c0243f..8b277d35f 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/DownloadDecisionMakerFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/DownloadDecisionMakerFixture.cs @@ -1,18 +1,18 @@ using System.Collections.Generic; using System.Linq; +using FizzWare.NBuilder; using FluentAssertions; +using Marr.Data; using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; using NzbDrone.Test.Common; -using FizzWare.NBuilder; -using Marr.Data; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -48,7 +48,7 @@ namespace NzbDrone.Core.Test.DecisionEngineTests _pass1.Setup(c => c.IsSatisfiedBy(It.IsAny(), null)).Returns(Decision.Accept); _pass2.Setup(c => c.IsSatisfiedBy(It.IsAny(), null)).Returns(Decision.Accept); _pass3.Setup(c => c.IsSatisfiedBy(It.IsAny(), null)).Returns(Decision.Accept); - + _fail1.Setup(c => c.IsSatisfiedBy(It.IsAny(), null)).Returns(Decision.Reject("fail1")); _fail2.Setup(c => c.IsSatisfiedBy(It.IsAny(), null)).Returns(Decision.Reject("fail2")); _fail3.Setup(c => c.IsSatisfiedBy(It.IsAny(), null)).Returns(Decision.Reject("fail3")); @@ -57,7 +57,8 @@ namespace NzbDrone.Core.Test.DecisionEngineTests _failDelayed1.SetupGet(c => c.Priority).Returns(SpecificationPriority.Disk); _reports = new List { new ReleaseInfo { Title = "Coldplay-A Head Full Of Dreams-CD-FLAC-2015-PERFECT" } }; - _remoteAlbum = new RemoteAlbum { + _remoteAlbum = new RemoteAlbum + { Artist = new Artist(), Albums = new List { new Album() } }; @@ -203,9 +204,9 @@ namespace NzbDrone.Core.Test.DecisionEngineTests _reports = new List { - new ReleaseInfo{Title = "Coldplay-A Head Full Of Dreams-CD-FLAC-2015-PERFECT"}, - new ReleaseInfo{Title = "Coldplay-A Head Full Of Dreams-CD-FLAC-2015-PERFECT"}, - new ReleaseInfo{Title = "Coldplay-A Head Full Of Dreams-CD-FLAC-2015-PERFECT"} + new ReleaseInfo { Title = "Coldplay-A Head Full Of Dreams-CD-FLAC-2015-PERFECT" }, + new ReleaseInfo { Title = "Coldplay-A Head Full Of Dreams-CD-FLAC-2015-PERFECT" }, + new ReleaseInfo { Title = "Coldplay-A Head Full Of Dreams-CD-FLAC-2015-PERFECT" } }; Subject.GetRssDecision(_reports); @@ -238,17 +239,17 @@ namespace NzbDrone.Core.Test.DecisionEngineTests .With(v => v.Artist, new LazyLoaded(artist)) .BuildList(); - var criteria = new ArtistSearchCriteria { Albums = albums.Take(1).ToList()}; + var criteria = new ArtistSearchCriteria { Albums = albums.Take(1).ToList() }; - var reports = albums.Select(v => - new ReleaseInfo() - { - Title = string.Format("{0}-{1}[FLAC][2017][DRONE]", artist.Name, v.Title) + var reports = albums.Select(v => + new ReleaseInfo() + { + Title = string.Format("{0}-{1}[FLAC][2017][DRONE]", artist.Name, v.Title) }).ToList(); Mocker.GetMock() .Setup(v => v.Map(It.IsAny(), It.IsAny())) - .Returns((p,c) => + .Returns((p, c) => new RemoteAlbum { DownloadAllowed = true, @@ -307,7 +308,7 @@ namespace NzbDrone.Core.Test.DecisionEngineTests _reports = new List { - new ReleaseInfo{Title = "Alien Ant Farm - TruAnt (FLAC) DRONE"}, + new ReleaseInfo { Title = "Alien Ant Farm - TruAnt (FLAC) DRONE" }, }; Subject.GetRssDecision(_reports).Should().HaveCount(1); diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/EarlyReleaseSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/EarlyReleaseSpecificationFixture.cs index 7a49f3cc2..25304405c 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/EarlyReleaseSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/EarlyReleaseSpecificationFixture.cs @@ -8,8 +8,8 @@ using NzbDrone.Core.Datastore; using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Indexers; using NzbDrone.Core.Indexers.TorrentRss; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Music; +using NzbDrone.Core.Parser.Model; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.DecisionEngineTests @@ -33,7 +33,7 @@ namespace NzbDrone.Core.Test.DecisionEngineTests _remoteAlbum = new RemoteAlbum { Artist = _artist, - Albums = new List{_album1}, + Albums = new List { _album1 }, Release = new TorrentInfo { IndexerId = 1, @@ -50,12 +50,11 @@ namespace NzbDrone.Core.Test.DecisionEngineTests Mocker.GetMock() .Setup(v => v.Get(1)) .Returns(_indexerDefinition); - } private void GivenPublishDateFromToday(int days) { - (_remoteAlbum.Release).PublishDate = DateTime.Today.AddDays(days); + _remoteAlbum.Release.PublishDate = DateTime.Today.AddDays(days); } [Test] @@ -108,7 +107,7 @@ namespace NzbDrone.Core.Test.DecisionEngineTests { GivenPublishDateFromToday(days); - _indexerDefinition.Settings = new TorrentRssIndexerSettings{EarlyReleaseLimit = null}; + _indexerDefinition.Settings = new TorrentRssIndexerSettings { EarlyReleaseLimit = null }; Subject.IsSatisfiedBy(_remoteAlbum, null).Accepted.Should().BeTrue(); } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/HistorySpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/HistorySpecificationFixture.cs index 2f28829ee..b9bfe8b51 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/HistorySpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/HistorySpecificationFixture.cs @@ -5,21 +5,24 @@ using FluentAssertions; 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.Parser.Model; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Music; -using NzbDrone.Core.DecisionEngine.Specifications; -using NzbDrone.Core.Test.Framework; +using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Qualities; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests { [TestFixture] public class HistorySpecificationFixture : CoreTest { + private const int FIRST_ALBUM_ID = 1; + private const int SECOND_ALBUM_ID = 2; + private HistorySpecification _upgradeHistory; private RemoteAlbum _parseResultMulti; @@ -27,8 +30,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests private QualityModel _upgradableQuality; private QualityModel _notupgradableQuality; private Artist _fakeArtist; - private const int FIRST_ALBUM_ID = 1; - private const int SECOND_ALBUM_ID = 2; [SetUp] public void Setup() @@ -37,11 +38,12 @@ namespace NzbDrone.Core.Test.DecisionEngineTests _upgradeHistory = Mocker.Resolve(); var singleAlbumList = new List { new Album { Id = FIRST_ALBUM_ID } }; - var doubleAlbumList = new List { - new Album {Id = FIRST_ALBUM_ID }, - new Album {Id = SECOND_ALBUM_ID }, - new Album {Id = 3 } - }; + var doubleAlbumList = new List + { + new Album { Id = FIRST_ALBUM_ID }, + new Album { Id = SECOND_ALBUM_ID }, + new Album { Id = 3 } + }; _fakeArtist = Builder.CreateNew() .With(c => c.QualityProfile = new QualityProfile @@ -107,13 +109,12 @@ namespace NzbDrone.Core.Test.DecisionEngineTests _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_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/MinimumAgeSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/MinimumAgeSpecificationFixture.cs index 40cc8c941..522e0cc85 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/MinimumAgeSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/MinimumAgeSpecificationFixture.cs @@ -61,4 +61,4 @@ namespace NzbDrone.Core.Test.DecisionEngineTests Subject.IsSatisfiedBy(_remoteAlbum, null).Accepted.Should().BeFalse(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/MonitoredAlbumSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/MonitoredAlbumSpecificationFixture.cs index 5c069fbfa..5a2ff60b1 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/MonitoredAlbumSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/MonitoredAlbumSpecificationFixture.cs @@ -4,8 +4,8 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications.RssSync; using NzbDrone.Core.IndexerSearch.Definitions; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Music; +using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests @@ -34,7 +34,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests _firstAlbum = new Album { Monitored = true }; _secondAlbum = new Album { Monitored = true }; - var singleAlbumList = new List { _firstAlbum }; var doubleAlbumList = new List { _firstAlbum, _secondAlbum }; @@ -122,7 +121,7 @@ namespace NzbDrone.Core.Test.DecisionEngineTests public void should_return_false_if_album_is_not_monitored_and_monitoredEpisodesOnly_flag_is_true() { WithFirstAlbumUnmonitored(); - _monitoredAlbumSpecification.IsSatisfiedBy(_parseResultSingle, new AlbumSearchCriteria{ MonitoredEpisodesOnly = true}).Accepted.Should().BeFalse(); + _monitoredAlbumSpecification.IsSatisfiedBy(_parseResultSingle, new AlbumSearchCriteria { MonitoredEpisodesOnly = true }).Accepted.Should().BeFalse(); } [Test] diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/PrioritizeDownloadDecisionFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/PrioritizeDownloadDecisionFixture.cs index dbce66d24..59102147e 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/PrioritizeDownloadDecisionFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/PrioritizeDownloadDecisionFixture.cs @@ -1,20 +1,20 @@ using System; using System.Collections.Generic; using System.Linq; +using FizzWare.NBuilder; +using FluentAssertions; using Moq; +using NUnit.Framework; +using NzbDrone.Common.Extensions; +using NzbDrone.Core.Configuration; +using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Indexers; -using NzbDrone.Core.Profiles.Delay; using NzbDrone.Core.Music; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Profiles.Delay; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.DecisionEngine; -using NUnit.Framework; -using FluentAssertions; -using FizzWare.NBuilder; -using NzbDrone.Common.Extensions; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Configuration; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -121,7 +121,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests var remoteAlbum1 = GivenRemoteAlbum(new List { GivenAlbum(1) }, new QualityModel(Quality.MP3_256), age: 10); var remoteAlbum2 = GivenRemoteAlbum(new List { GivenAlbum(1) }, new QualityModel(Quality.MP3_256), age: 5); - var decisions = new List(); decisions.Add(new DownloadDecision(remoteAlbum1)); decisions.Add(new DownloadDecision(remoteAlbum2)); @@ -262,7 +261,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests torrentInfo1.Seeders = 10; torrentInfo1.Peers = 10; - var torrentInfo2 = torrentInfo1.JsonClone(); torrentInfo2.Peers = 100; @@ -290,7 +288,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests torrentInfo1.Seeders = 0; torrentInfo1.Peers = 10; - var torrentInfo2 = torrentInfo1.JsonClone(); torrentInfo2.Seeders = 0; torrentInfo2.Peers = 100; @@ -398,7 +395,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests qualifiedReports.First().RemoteAlbum.ParsedAlbumInfo.Quality.Quality.Should().Be(Quality.MP3_320); } - [Test] public void should_prefer_higher_score_over_lower_score() { diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/ProtocolSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/ProtocolSpecificationFixture.cs index 5b9ce36ef..d30d365a5 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/ProtocolSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/ProtocolSpecificationFixture.cs @@ -4,10 +4,10 @@ using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Delay; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -23,7 +23,7 @@ namespace NzbDrone.Core.Test.DecisionEngineTests _remoteAlbum = new RemoteAlbum(); _remoteAlbum.Release = new ReleaseInfo(); _remoteAlbum.Artist = new Artist(); - + _delayProfile = new DelayProfile(); Mocker.GetMock() @@ -72,4 +72,4 @@ namespace NzbDrone.Core.Test.DecisionEngineTests Subject.IsSatisfiedBy(_remoteAlbum, null).Accepted.Should().Be(false); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/QualityAllowedByProfileSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/QualityAllowedByProfileSpecificationFixture.cs index 34f29df7b..90c2cf878 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/QualityAllowedByProfileSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/QualityAllowedByProfileSpecificationFixture.cs @@ -3,10 +3,10 @@ using FluentAssertions; using Marr.Data; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Music; using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests @@ -15,7 +15,7 @@ namespace NzbDrone.Core.Test.DecisionEngineTests public class QualityAllowedByProfileSpecificationFixture : CoreTest { - private RemoteAlbum remoteAlbum; + private RemoteAlbum _remoteAlbum; public static object[] AllowedTestCases = { @@ -35,32 +35,34 @@ namespace NzbDrone.Core.Test.DecisionEngineTests public void Setup() { var fakeArtist = Builder.CreateNew() - .With(c => c.QualityProfile = (LazyLoaded)new QualityProfile { Cutoff = Quality.MP3_320.Id }) + .With(c => c.QualityProfile = new QualityProfile { Cutoff = Quality.MP3_320.Id }) .Build(); - remoteAlbum = new RemoteAlbum + _remoteAlbum = new RemoteAlbum { Artist = fakeArtist, ParsedAlbumInfo = new ParsedAlbumInfo { Quality = new QualityModel(Quality.MP3_192, new Revision(version: 2)) }, }; } - [Test, TestCaseSource(nameof(AllowedTestCases))] + [Test] + [TestCaseSource(nameof(AllowedTestCases))] public void should_allow_if_quality_is_defined_in_profile(Quality qualityType) { - remoteAlbum.ParsedAlbumInfo.Quality.Quality = qualityType; - remoteAlbum.Artist.QualityProfile.Value.Items = Qualities.QualityFixture.GetDefaultQualities(Quality.MP3_192, Quality.MP3_256, Quality.MP3_320); + _remoteAlbum.ParsedAlbumInfo.Quality.Quality = qualityType; + _remoteAlbum.Artist.QualityProfile.Value.Items = Qualities.QualityFixture.GetDefaultQualities(Quality.MP3_192, Quality.MP3_256, Quality.MP3_320); - Subject.IsSatisfiedBy(remoteAlbum, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_remoteAlbum, null).Accepted.Should().BeTrue(); } - [Test, TestCaseSource(nameof(DeniedTestCases))] + [Test] + [TestCaseSource(nameof(DeniedTestCases))] public void should_not_allow_if_quality_is_not_defined_in_profile(Quality qualityType) { - remoteAlbum.ParsedAlbumInfo.Quality.Quality = qualityType; - remoteAlbum.Artist.QualityProfile.Value.Items = Qualities.QualityFixture.GetDefaultQualities(Quality.MP3_192, Quality.MP3_256, Quality.MP3_320); + _remoteAlbum.ParsedAlbumInfo.Quality.Quality = qualityType; + _remoteAlbum.Artist.QualityProfile.Value.Items = Qualities.QualityFixture.GetDefaultQualities(Quality.MP3_192, Quality.MP3_256, Quality.MP3_320); - Subject.IsSatisfiedBy(remoteAlbum, null).Accepted.Should().BeFalse(); + Subject.IsSatisfiedBy(_remoteAlbum, null).Accepted.Should().BeFalse(); } } } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/QueueSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/QueueSpecificationFixture.cs index b03aac44e..263bfa7a0 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/QueueSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/QueueSpecificationFixture.cs @@ -4,11 +4,11 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; using NzbDrone.Core.Queue; -using NzbDrone.Core.Music; using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/RawDiskSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/RawDiskSpecificationFixture.cs index 301566f25..aff2e8850 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/RawDiskSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/RawDiskSpecificationFixture.cs @@ -1,9 +1,9 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.Indexers; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Indexers; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -26,7 +26,7 @@ namespace NzbDrone.Core.Test.DecisionEngineTests { _remoteAlbum.Release.Container = container; } - + [Test] public void should_return_true_if_no_container_specified() { @@ -60,6 +60,5 @@ namespace NzbDrone.Core.Test.DecisionEngineTests WithContainer("vob"); Subject.IsSatisfiedBy(_remoteAlbum, null).Accepted.Should().BeFalse(); } - } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/ReleaseRestrictionsSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/ReleaseRestrictionsSpecificationFixture.cs index 7c7e9e156..4d663038c 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/ReleaseRestrictionsSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/ReleaseRestrictionsSpecificationFixture.cs @@ -3,10 +3,10 @@ using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Releases; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -20,15 +20,15 @@ namespace NzbDrone.Core.Test.DecisionEngineTests { _remoteAlbum = new RemoteAlbum { - Artist = new Artist - { - Tags = new HashSet() - }, - Release = new ReleaseInfo - { - Title = "Dexter.S08E01.EDITED.WEBRip.x264-KYR" - } - }; + Artist = new Artist + { + 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 c8b5e8335..17d49a457 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/RepackSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/RepackSpecificationFixture.cs @@ -2,14 +2,14 @@ using System.Collections.Generic; using System.Linq; using FizzWare.NBuilder; using FluentAssertions; +using Moq; 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.Music; -using Moq; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -84,8 +84,16 @@ namespace NzbDrone.Core.Test.DecisionEngineTests { _parsedAlbumInfo.Quality.Revision.IsRepack = true; - _trackFiles.Select(c => { c.ReleaseGroup = "Lidarr"; return c; }).ToList(); - _trackFiles.Select(c => { c.Quality = new QualityModel(Quality.MP3_256); return c; }).ToList(); + _trackFiles.Select(c => + { + c.ReleaseGroup = "Lidarr"; + return c; + }).ToList(); + _trackFiles.Select(c => + { + c.Quality = new QualityModel(Quality.MP3_256); + return c; + }).ToList(); var remoteAlbum = Builder.CreateNew() .With(e => e.ParsedAlbumInfo = _parsedAlbumInfo) @@ -103,8 +111,16 @@ namespace NzbDrone.Core.Test.DecisionEngineTests { _parsedAlbumInfo.Quality.Revision.IsRepack = true; - _trackFiles.Select(c => { c.ReleaseGroup = "Lidarr"; return c; }).ToList(); - _trackFiles.Select(c => { c.Quality = new QualityModel(Quality.FLAC); return c; }).ToList(); + _trackFiles.Select(c => + { + c.ReleaseGroup = "Lidarr"; + return c; + }).ToList(); + _trackFiles.Select(c => + { + c.Quality = new QualityModel(Quality.FLAC); + return c; + }).ToList(); var remoteAlbum = Builder.CreateNew() .With(e => e.ParsedAlbumInfo = _parsedAlbumInfo) @@ -122,8 +138,16 @@ namespace NzbDrone.Core.Test.DecisionEngineTests { _parsedAlbumInfo.Quality.Revision.IsRepack = true; - _trackFiles.Select(c => { c.ReleaseGroup = "Lidarr"; return c; }).ToList(); - _trackFiles.Select(c => { c.Quality = new QualityModel(Quality.FLAC); return c; }).ToList(); + _trackFiles.Select(c => + { + c.ReleaseGroup = "Lidarr"; + return c; + }).ToList(); + _trackFiles.Select(c => + { + c.Quality = new QualityModel(Quality.FLAC); + return c; + }).ToList(); _trackFiles.First().ReleaseGroup = "NotLidarr"; @@ -138,14 +162,21 @@ namespace NzbDrone.Core.Test.DecisionEngineTests .BeFalse(); } - [Test] public void should_return_false_if_is_a_repack_for_different_group() { _parsedAlbumInfo.Quality.Revision.IsRepack = true; - _trackFiles.Select(c => { c.ReleaseGroup = "NotLidarr"; return c; }).ToList(); - _trackFiles.Select(c => { c.Quality = new QualityModel(Quality.FLAC); return c; }).ToList(); + _trackFiles.Select(c => + { + c.ReleaseGroup = "NotLidarr"; + return c; + }).ToList(); + _trackFiles.Select(c => + { + c.Quality = new QualityModel(Quality.FLAC); + return c; + }).ToList(); var remoteAlbum = Builder.CreateNew() .With(e => e.ParsedAlbumInfo = _parsedAlbumInfo) @@ -158,15 +189,21 @@ namespace NzbDrone.Core.Test.DecisionEngineTests .BeFalse(); } - [Test] public void should_return_false_if_release_group_for_existing_file_is_unknown() { _parsedAlbumInfo.Quality.Revision.IsRepack = true; - _trackFiles.Select(c => { c.ReleaseGroup = ""; return c; }).ToList(); - _trackFiles.Select(c => { c.Quality = new QualityModel(Quality.FLAC); return c; }).ToList(); - + _trackFiles.Select(c => + { + c.ReleaseGroup = ""; + return c; + }).ToList(); + _trackFiles.Select(c => + { + c.Quality = new QualityModel(Quality.FLAC); + return c; + }).ToList(); var remoteAlbum = Builder.CreateNew() .With(e => e.ParsedAlbumInfo = _parsedAlbumInfo) @@ -185,9 +222,17 @@ namespace NzbDrone.Core.Test.DecisionEngineTests _parsedAlbumInfo.Quality.Revision.IsRepack = true; _parsedAlbumInfo.ReleaseGroup = null; - _trackFiles.Select(c => { c.ReleaseGroup = "Lidarr"; return c; }).ToList(); - _trackFiles.Select(c => { c.Quality = new QualityModel(Quality.FLAC); return c; }).ToList(); + _trackFiles.Select(c => + { + c.ReleaseGroup = "Lidarr"; + return c; + }).ToList(); + _trackFiles.Select(c => + { + c.Quality = new QualityModel(Quality.FLAC); + return c; + }).ToList(); var remoteAlbum = Builder.CreateNew() .With(e => e.ParsedAlbumInfo = _parsedAlbumInfo) diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/RetentionSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/RetentionSpecificationFixture.cs index 243f7c740..f3ec183f1 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/RetentionSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/RetentionSpecificationFixture.cs @@ -90,4 +90,4 @@ namespace NzbDrone.Core.Test.DecisionEngineTests Subject.IsSatisfiedBy(_remoteAlbum, null).Accepted.Should().BeTrue(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DelaySpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DelaySpecificationFixture.cs index 4aaf82e1a..9d5b7a40a 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DelaySpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DelaySpecificationFixture.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Linq; using FizzWare.NBuilder; using FluentAssertions; -using Marr.Data; using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; @@ -12,12 +11,12 @@ using NzbDrone.Core.Download.Pending; using NzbDrone.Core.Indexers; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Profiles.Delay; +using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.DecisionEngineTests.RssSync { @@ -34,7 +33,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests.RssSync _profile = Builder.CreateNew() .Build(); - _delayProfile = Builder.CreateNew() .With(d => d.PreferredProtocol = DownloadProtocol.Usenet) .Build(); @@ -77,9 +75,13 @@ namespace NzbDrone.Core.Test.DecisionEngineTests.RssSync { Mocker.GetMock() .Setup(s => s.GetFilesByAlbum(It.IsAny())) - .Returns(new List { new TrackFile { + .Returns(new List + { + new TrackFile + { Quality = quality - } }); + } + }); } private void GivenUpgradeForExistingFile() diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DeletedTrackFileSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DeletedTrackFileSpecificationFixture.cs index d581c5194..38c2cf8fe 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DeletedTrackFileSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DeletedTrackFileSpecificationFixture.cs @@ -2,21 +2,19 @@ using System; using System.Collections.Generic; using FizzWare.NBuilder; using FluentAssertions; +using Moq; using NUnit.Framework; +using NzbDrone.Common.Disk; using NzbDrone.Core.Configuration; using NzbDrone.Core.DecisionEngine.Specifications.RssSync; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Music; -using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Test.Framework; -using NzbDrone.Common.Disk; -using Moq; using NzbDrone.Test.Common; -using System.IO; namespace NzbDrone.Core.Test.DecisionEngineTests.RssSync { @@ -31,27 +29,28 @@ namespace NzbDrone.Core.Test.DecisionEngineTests.RssSync [SetUp] public void Setup() { - _firstFile = - new TrackFile{ - Id = 1, - Path = "/My.Artist.S01E01.mp3", - Quality = new QualityModel(Quality.FLAC, new Revision(version: 1)), - DateAdded = DateTime.Now, - AlbumId = 1 - - }; - _secondFile = - new TrackFile{ - Id = 2, - Path = "/My.Artist.S01E02.mp3", - Quality = new QualityModel(Quality.FLAC, new Revision(version: 1)), - DateAdded = DateTime.Now, - AlbumId = 2 - - }; + _firstFile = + new TrackFile + { + Id = 1, + Path = "/My.Artist.S01E01.mp3", + Quality = new QualityModel(Quality.FLAC, new Revision(version: 1)), + DateAdded = DateTime.Now, + AlbumId = 1 + }; + _secondFile = + new TrackFile + { + Id = 2, + Path = "/My.Artist.S01E02.mp3", + Quality = new QualityModel(Quality.FLAC, new Revision(version: 1)), + DateAdded = DateTime.Now, + AlbumId = 2 + }; var singleAlbumList = new List { new Album { Id = 1 } }; - var doubleAlbumList = new List { + var doubleAlbumList = new List + { new Album { Id = 1 }, new Album { Id = 2 } }; diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/ProperSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/ProperSpecificationFixture.cs index 38768fbd5..0145589dd 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/ProperSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/ProperSpecificationFixture.cs @@ -2,18 +2,17 @@ using System; using System.Collections.Generic; using FizzWare.NBuilder; using FluentAssertions; -using NUnit.Framework; using Moq; +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.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Music; -using NzbDrone.Core.DecisionEngine.Specifications; - using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests.RssSync @@ -35,9 +34,8 @@ namespace NzbDrone.Core.Test.DecisionEngineTests.RssSync _firstFile = new TrackFile { Quality = new QualityModel(Quality.FLAC, new Revision(version: 1)), DateAdded = DateTime.Now }; _secondFile = new TrackFile { Quality = new QualityModel(Quality.FLAC, new Revision(version: 1)), DateAdded = DateTime.Now }; - var singleAlbumList = new List { new Album {}, new Album {} }; - var doubleAlbumList = new List { new Album {}, new Album {}, new Album {} }; - + var singleAlbumList = new List { new Album { }, new Album { } }; + var doubleAlbumList = new List { new Album { }, new Album { }, new Album { } }; var fakeArtist = Builder.CreateNew() .With(c => c.QualityProfile = new QualityProfile { Cutoff = Quality.FLAC.Id }) diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/Search/ArtistSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/Search/ArtistSpecificationFixture.cs index 423d2614f..d0d22d4c8 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/Search/ArtistSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/Search/ArtistSpecificationFixture.cs @@ -3,8 +3,8 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications.Search; using NzbDrone.Core.IndexerSearch.Definitions; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Music; +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 d284f6642..b139c9969 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/Search/TorrentSeedingSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/Search/TorrentSeedingSpecificationFixture.cs @@ -6,9 +6,8 @@ using NzbDrone.Core.Datastore; using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Indexers; using NzbDrone.Core.Indexers.TorrentRss; -using NzbDrone.Core.IndexerSearch.Definitions; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Music; +using NzbDrone.Core.Parser.Model; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.DecisionEngineTests.Search @@ -44,7 +43,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests.Search Mocker.GetMock() .Setup(v => v.Get(1)) .Returns(_indexerDefinition); - } private void GivenReleaseSeeders(int? seeders) diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeAllowedSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeAllowedSpecificationFixture.cs index 716dc0947..43e431245 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeAllowedSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeAllowedSpecificationFixture.cs @@ -1,10 +1,10 @@ +using System.Collections.Generic; using FluentAssertions; using NUnit.Framework; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; -using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Test.Framework; -using System.Collections.Generic; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -22,8 +22,8 @@ namespace NzbDrone.Core.Test.DecisionEngineTests UpgradeAllowed = false }, new List { new QualityModel(Quality.MP3_320) }, - new QualityModel(Quality.FLAC) - ).Should().BeFalse(); + new QualityModel(Quality.FLAC)) + .Should().BeFalse(); } [Test] @@ -37,8 +37,8 @@ namespace NzbDrone.Core.Test.DecisionEngineTests UpgradeAllowed = true }, new List { new QualityModel(Quality.MP3_320) }, - new QualityModel(Quality.FLAC) - ).Should().BeTrue(); + new QualityModel(Quality.FLAC)) + .Should().BeTrue(); } [Test] @@ -52,8 +52,8 @@ namespace NzbDrone.Core.Test.DecisionEngineTests UpgradeAllowed = true }, new List { new QualityModel(Quality.MP3_320) }, - new QualityModel(Quality.MP3_320) - ).Should().BeTrue(); + new QualityModel(Quality.MP3_320)) + .Should().BeTrue(); } [Test] @@ -67,8 +67,8 @@ namespace NzbDrone.Core.Test.DecisionEngineTests UpgradeAllowed = false }, new List { new QualityModel(Quality.MP3_320) }, - new QualityModel(Quality.MP3_320) - ).Should().BeTrue(); + new QualityModel(Quality.MP3_320)) + .Should().BeTrue(); } [Test] @@ -82,8 +82,8 @@ namespace NzbDrone.Core.Test.DecisionEngineTests UpgradeAllowed = true }, new List { new QualityModel(Quality.MP3_320) }, - new QualityModel(Quality.MP3_256) - ).Should().BeTrue(); + new QualityModel(Quality.MP3_256)) + .Should().BeTrue(); } [Test] @@ -96,9 +96,9 @@ namespace NzbDrone.Core.Test.DecisionEngineTests Items = Qualities.QualityFixture.GetDefaultQualities(), UpgradeAllowed = false }, - new List{ new QualityModel(Quality.MP3_320) }, - new QualityModel(Quality.MP3_256) - ).Should().BeTrue(); + new List { new QualityModel(Quality.MP3_320) }, + new QualityModel(Quality.MP3_256)) + .Should().BeTrue(); } } } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeDiskSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeDiskSpecificationFixture.cs index 34aa10365..7fa65e375 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeDiskSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeDiskSpecificationFixture.cs @@ -2,15 +2,14 @@ using System; using System.Collections.Generic; using FizzWare.NBuilder; using FluentAssertions; -using NUnit.Framework; using Moq; +using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Music; -using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests @@ -32,8 +31,8 @@ namespace NzbDrone.Core.Test.DecisionEngineTests _firstFile = new TrackFile { Quality = new QualityModel(Quality.FLAC, new Revision(version: 2)), DateAdded = DateTime.Now }; _secondFile = new TrackFile { Quality = new QualityModel(Quality.FLAC, new Revision(version: 2)), DateAdded = DateTime.Now }; - var singleAlbumList = new List { new Album {}}; - var doubleAlbumList = new List { new Album {}, new Album {}, new Album {} }; + var singleAlbumList = new List { new Album { } }; + var doubleAlbumList = new List { new Album { }, new Album { }, new Album { } }; var fakeArtist = Builder.CreateNew() .With(c => c.QualityProfile = new QualityProfile @@ -65,7 +64,6 @@ namespace NzbDrone.Core.Test.DecisionEngineTests ParsedAlbumInfo = new ParsedAlbumInfo { Quality = new QualityModel(Quality.MP3_256, new Revision(version: 2)) }, Albums = singleAlbumList }; - } private void WithFirstFileUpgradable() diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeSpecificationFixture.cs index ba3c4f80a..f284f9688 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeSpecificationFixture.cs @@ -1,11 +1,11 @@ +using System.Collections.Generic; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Configuration; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; -using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Test.Framework; -using System.Collections.Generic; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -32,7 +32,8 @@ namespace NzbDrone.Core.Test.DecisionEngineTests .Returns(type); } - [Test, TestCaseSource(nameof(IsUpgradeTestCases))] + [Test] + [TestCaseSource(nameof(IsUpgradeTestCases))] public void IsUpgradeTest(Quality current, int currentVersion, Quality newQuality, int newVersion, Quality cutoff, bool expected) { GivenAutoDownloadPropers(ProperDownloadTypes.PreferAndUpgrade); diff --git a/src/NzbDrone.Core.Test/DiskSpace/DiskSpaceServiceFixture.cs b/src/NzbDrone.Core.Test/DiskSpace/DiskSpaceServiceFixture.cs index 2c15d650e..b673d0490 100644 --- a/src/NzbDrone.Core.Test/DiskSpace/DiskSpaceServiceFixture.cs +++ b/src/NzbDrone.Core.Test/DiskSpace/DiskSpaceServiceFixture.cs @@ -1,15 +1,12 @@ -using System; using System.Collections.Generic; using System.Linq; -using System.Text; using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Common.Disk; -using NzbDrone.Core.Configuration; using NzbDrone.Core.DiskSpace; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; +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 ef33627c2..433f38b20 100644 --- a/src/NzbDrone.Core.Test/Download/CompletedDownloadServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Download/CompletedDownloadServiceFixture.cs @@ -4,20 +4,19 @@ using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Common.Disk; -using NzbDrone.Core.Configuration; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.History; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.MediaFiles.TrackImport; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; using NzbDrone.Test.Common; -using NzbDrone.Core.MediaFiles.Events; namespace NzbDrone.Core.Test.Download { @@ -43,7 +42,6 @@ namespace NzbDrone.Core.Test.Download .With(c => c.RemoteAlbum = remoteAlbum) .Build(); - Mocker.GetMock() .SetupGet(c => c.Definition) .Returns(new DownloadClientDefinition { Id = 1, Name = "testClient" }); @@ -59,15 +57,17 @@ namespace NzbDrone.Core.Test.Download Mocker.GetMock() .Setup(s => s.GetArtist("Drone.S01E01.HDTV")) .Returns(remoteAlbum.Artist); - } private Album CreateAlbum(int id, int trackCount) { - return new Album { + return new Album + { Id = id, - AlbumReleases = new List { - new AlbumRelease { + AlbumReleases = new List + { + new AlbumRelease + { Monitored = true, TrackCount = trackCount } @@ -84,7 +84,6 @@ namespace NzbDrone.Core.Test.Download }; } - private void GivenNoGrabbedHistory() { Mocker.GetMock() @@ -102,7 +101,6 @@ namespace NzbDrone.Core.Test.Download }); } - private void GivenABadlyNamedDownload() { _trackedDownload.RemoteAlbum.Artist = null; @@ -169,7 +167,7 @@ namespace NzbDrone.Core.Test.Download [Test] public void should_not_process_if_output_path_is_empty() { - _trackedDownload.DownloadItem.OutputPath = new OsPath(); + _trackedDownload.DownloadItem.OutputPath = default(OsPath); Subject.Process(_trackedDownload); @@ -200,11 +198,11 @@ namespace NzbDrone.Core.Test.Download { new ImportResult( new ImportDecision( - new LocalTrack {Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic()})), + new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() })), - new ImportResult( + new ImportResult( new ImportDecision( - new LocalTrack {Path = @"C:\TestPath\Droned.S01E02.mkv".AsOsAgnostic()})) + new LocalTrack { Path = @"C:\TestPath\Droned.S01E02.mkv".AsOsAgnostic() })) }); Subject.Process(_trackedDownload); @@ -226,11 +224,11 @@ namespace NzbDrone.Core.Test.Download { new ImportResult( new ImportDecision( - new LocalTrack {Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic()})), + new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() })), - new ImportResult( + new ImportResult( new ImportDecision( - new LocalTrack {Path = @"C:\TestPath\Droned.S01E02.mkv".AsOsAgnostic()})) + new LocalTrack { Path = @"C:\TestPath\Droned.S01E02.mkv".AsOsAgnostic() })) }); Subject.Process(_trackedDownload); @@ -247,11 +245,11 @@ namespace NzbDrone.Core.Test.Download { new ImportResult( new ImportDecision( - new LocalTrack {Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic()}, new Rejection("Rejected!")), "Test Failure"), + new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() }, new Rejection("Rejected!")), "Test Failure"), - new ImportResult( + new ImportResult( new ImportDecision( - new LocalTrack {Path = @"C:\TestPath\Droned.S01E02.mkv".AsOsAgnostic()},new Rejection("Rejected!")), "Test Failure") + new LocalTrack { Path = @"C:\TestPath\Droned.S01E02.mkv".AsOsAgnostic() }, new Rejection("Rejected!")), "Test Failure") }); Subject.Process(_trackedDownload); @@ -271,11 +269,11 @@ namespace NzbDrone.Core.Test.Download { new ImportResult( new ImportDecision( - new LocalTrack {Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic()}, new Rejection("Rejected!")), "Test Failure"), + new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() }, new Rejection("Rejected!")), "Test Failure"), - new ImportResult( + new ImportResult( new ImportDecision( - new LocalTrack {Path = @"C:\TestPath\Droned.S01E02.mkv".AsOsAgnostic()},new Rejection("Rejected!")), "Test Failure") + new LocalTrack { Path = @"C:\TestPath\Droned.S01E02.mkv".AsOsAgnostic() }, new Rejection("Rejected!")), "Test Failure") }); _trackedDownload.RemoteAlbum.Albums.Clear(); @@ -292,11 +290,10 @@ namespace NzbDrone.Core.Test.Download .Setup(v => v.ProcessPath(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new List { - new ImportResult(new ImportDecision(new LocalTrack {Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic()}),"Test Failure"), - new ImportResult(new ImportDecision(new LocalTrack {Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic()}),"Test Failure") + new ImportResult(new ImportDecision(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() }), "Test Failure"), + new ImportResult(new ImportDecision(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() }), "Test Failure") }); - Subject.Process(_trackedDownload); AssertImportIncomplete(); @@ -316,10 +313,10 @@ namespace NzbDrone.Core.Test.Download .Setup(v => v.ProcessPath(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new List { - new ImportResult(new ImportDecision(new LocalTrack {Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic()})), - new ImportResult(new ImportDecision(new LocalTrack {Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic()})), - new ImportResult(new ImportDecision(new LocalTrack {Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic()})), - new ImportResult(new ImportDecision(new LocalTrack {Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic()}), "Test Failure") + new ImportResult(new ImportDecision(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() })), + new ImportResult(new ImportDecision(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() })), + new ImportResult(new ImportDecision(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() })), + new ImportResult(new ImportDecision(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() }), "Test Failure") }); Subject.Process(_trackedDownload); @@ -341,14 +338,13 @@ namespace NzbDrone.Core.Test.Download .Setup(v => v.ProcessPath(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new List { - new ImportResult(new ImportDecision(new LocalTrack {Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic()})), - new ImportResult(new ImportDecision(new LocalTrack {Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic()})), - new ImportResult(new ImportDecision(new LocalTrack {Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic()})), - new ImportResult(new ImportDecision(new LocalTrack {Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic()}), "Test Failure"), - new ImportResult(new ImportDecision(new LocalTrack {Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic()}), "Test Failure") + new ImportResult(new ImportDecision(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() })), + new ImportResult(new ImportDecision(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() })), + new ImportResult(new ImportDecision(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() })), + new ImportResult(new ImportDecision(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() }), "Test Failure"), + new ImportResult(new ImportDecision(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() }), "Test Failure") }); - Subject.Process(_trackedDownload); AssertImportIncomplete(); @@ -363,7 +359,7 @@ namespace NzbDrone.Core.Test.Download .Setup(v => v.ProcessPath(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new List { - new ImportResult(new ImportDecision(new LocalTrack {Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic()})) + new ImportResult(new ImportDecision(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() })) }); Mocker.GetMock() @@ -384,7 +380,7 @@ namespace NzbDrone.Core.Test.Download .Setup(v => v.ProcessPath(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new List { - new ImportResult(new ImportDecision(new LocalTrack {Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic()})) + new ImportResult(new ImportDecision(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() })) }); Mocker.GetMock() @@ -420,7 +416,7 @@ namespace NzbDrone.Core.Test.Download .Setup(v => v.ProcessPath(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new List { - new ImportResult(new ImportDecision(new LocalTrack {Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic()})) + new ImportResult(new ImportDecision(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() })) }); 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 088b00ddf..8d774ec36 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadApprovedReportsTests/DownloadApprovedFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadApprovedReportsTests/DownloadApprovedFixture.cs @@ -10,11 +10,11 @@ using NzbDrone.Core.Download.Clients; using NzbDrone.Core.Download.Pending; using NzbDrone.Core.Exceptions; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadApprovedReportsTests @@ -89,13 +89,11 @@ namespace NzbDrone.Core.Test.Download.DownloadApprovedReportsTests { var remoteAlbum1 = GetRemoteAlbum( new List { GetAlbum(1) }, - new QualityModel(Quality.MP3_192) - ); + new QualityModel(Quality.MP3_192)); var remoteAlbum2 = GetRemoteAlbum( new List { GetAlbum(1), GetAlbum(2) }, - new QualityModel(Quality.MP3_192) - ); + new QualityModel(Quality.MP3_192)); var decisions = new List(); decisions.Add(new DownloadDecision(remoteAlbum1)); @@ -122,13 +120,11 @@ namespace NzbDrone.Core.Test.Download.DownloadApprovedReportsTests { var remoteAlbum1 = GetRemoteAlbum( new List { GetAlbum(1) }, - new QualityModel(Quality.MP3_192) - ); + new QualityModel(Quality.MP3_192)); var remoteAlbum2 = GetRemoteAlbum( new List { GetAlbum(2) }, - new QualityModel(Quality.MP3_192) - ); + new QualityModel(Quality.MP3_192)); var decisions = new List(); decisions.Add(new DownloadDecision(remoteAlbum1)); @@ -142,18 +138,15 @@ namespace NzbDrone.Core.Test.Download.DownloadApprovedReportsTests { var remoteAlbum1 = GetRemoteAlbum( new List { GetAlbum(1) }, - new QualityModel(Quality.MP3_192) - ); + new QualityModel(Quality.MP3_192)); var remoteAlbum2 = GetRemoteAlbum( new List { GetAlbum(2) }, - new QualityModel(Quality.MP3_192) - ); + new QualityModel(Quality.MP3_192)); var remoteAlbum3 = GetRemoteAlbum( new List { GetAlbum(2) }, - new QualityModel(Quality.MP3_192) - ); + new QualityModel(Quality.MP3_192)); var decisions = new List(); decisions.Add(new DownloadDecision(remoteAlbum1)); diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientProviderFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientProviderFixture.cs index 27fe13b81..1387ec3fd 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientProviderFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientProviderFixture.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; using FizzWare.NBuilder; using FluentAssertions; using Moq; diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/Blackhole/ScanWatchFolderFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/Blackhole/ScanWatchFolderFixture.cs index 227102792..dcd7fdf19 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/Blackhole/ScanWatchFolderFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/Blackhole/ScanWatchFolderFixture.cs @@ -21,7 +21,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.Blackhole { protected readonly string _title = "Radiohead - Scotch Mist [2008-FLAC-Lossless]"; protected string _completedDownloadFolder = @"c:\blackhole\completed".AsOsAgnostic(); - + protected void GivenCompletedItem() { var targetDir = Path.Combine(_completedDownloadFolder, _title); @@ -39,7 +39,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.Blackhole Mocker.GetMock().Setup(c => c.FilterFiles(It.IsAny(), It.IsAny>())) .Returns>((b, s) => s.ToList()); - + Mocker.GetMock().Setup(c => c.FilterFiles(It.IsAny(), It.IsAny>())) .Returns>((b, s) => s.ToList()); } @@ -52,7 +52,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.Blackhole .Setup(c => c.GetFileSize(It.IsAny())) .Returns(currentSize + 1); } - + private void VerifySingleItem(DownloadItemStatus status) { var items = Subject.GetItems(_completedDownloadFolder, TimeSpan.FromMilliseconds(50)).ToList(); diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/Blackhole/UsenetBlackholeFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/Blackhole/UsenetBlackholeFixture.cs index 04786acbc..5a7b39945 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; @@ -17,7 +16,6 @@ using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.Blackhole { - [TestFixture] public class UsenetBlackholeFixture : DownloadClientFixtureBase { @@ -101,7 +99,6 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.Blackhole 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 622e65708..e7c14527b 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,56 +31,56 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DelugeTests }; _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() @@ -119,7 +119,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DelugeTests .Returns("CBC2F069FE8BB2F544EAE707D75BCD3DE9DCF951".ToLower()) .Callback(PrepareClientToReturnQueuedItem); } - + protected virtual void GivenTorrents(List torrents) { if (torrents == null) @@ -134,7 +134,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DelugeTests protected void PrepareClientToReturnQueuedItem() { - GivenTorrents(new List + GivenTorrents(new List { _queued }); @@ -142,7 +142,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DelugeTests protected void PrepareClientToReturnDownloadingItem() { - GivenTorrents(new List + GivenTorrents(new List { _downloading }); @@ -150,7 +150,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DelugeTests protected void PrepareClientToReturnFailedItem() { - GivenTorrents(new List + GivenTorrents(new List { _failed }); diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadClientFixtureBase.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadClientFixtureBase.cs index 1f0dfd4c0..02d657396 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadClientFixtureBase.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadClientFixtureBase.cs @@ -1,18 +1,18 @@ using System; using System.Collections.Generic; +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.Music; -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.Music; +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 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests .Returns(30); Mocker.GetMock() - .Setup(s => s.Map(It.IsAny(), (SearchCriteriaBase)null)) + .Setup(s => s.Map(It.IsAny(), null)) .Returns(() => CreateRemoteAlbum()); Mocker.GetMock() @@ -70,6 +70,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests { VerifyIdentifiable(downloadClientItem); downloadClientItem.RemainingSize.Should().NotBe(0); + //downloadClientItem.RemainingTime.Should().NotBe(TimeSpan.Zero); //downloadClientItem.OutputPath.Should().NotBeNullOrEmpty(); downloadClientItem.Status.Should().Be(DownloadItemStatus.Queued); @@ -80,6 +81,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests VerifyIdentifiable(downloadClientItem); downloadClientItem.RemainingSize.Should().NotBe(0); + //downloadClientItem.RemainingTime.Should().NotBe(TimeSpan.Zero); //downloadClientItem.OutputPath.Should().NotBeNullOrEmpty(); downloadClientItem.Status.Should().Be(DownloadItemStatus.Paused); @@ -90,6 +92,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests VerifyIdentifiable(downloadClientItem); downloadClientItem.RemainingSize.Should().NotBe(0); + //downloadClientItem.RemainingTime.Should().NotBe(TimeSpan.Zero); //downloadClientItem.OutputPath.Should().NotBeNullOrEmpty(); downloadClientItem.Status.Should().Be(DownloadItemStatus.Downloading); @@ -111,6 +114,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests 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 2c3897e34..ae3ba0932 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/TorrentDownloadStationFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/TorrentDownloadStationFixture.cs @@ -33,7 +33,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests protected DownloadStationTask _multipleFilesCompleted; protected string _serialNumber = "SERIALNUMBER"; - protected string _category ="lidarr"; + protected string _category = "lidarr"; protected string _musicDirectory = @"music/Artist"; protected string _defaultDestination = "somepath"; protected OsPath _physicalPath = new OsPath("/mnt/sdb1/mydata"); @@ -68,13 +68,13 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { 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" } } } @@ -92,13 +92,13 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { 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" } }, } @@ -116,13 +116,13 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { 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" } } } @@ -140,13 +140,13 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { 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" } } } @@ -164,13 +164,13 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { 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" } } } @@ -188,13 +188,13 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { 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" } } } @@ -212,13 +212,13 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { 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" } } } @@ -236,13 +236,13 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { 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" } } } @@ -260,13 +260,13 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { 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" } } } @@ -649,7 +649,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests items.Should().HaveCount(1); var item = items.First(); - + item.CanBeRemoved.Should().Be(canBeRemovedExpected); item.CanMoveFiles.Should().Be(canMoveFilesExpected); } diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/UsenetDownloadStationFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/UsenetDownloadStationFixture.cs index 385aa6fdd..386775bb6 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/UsenetDownloadStationFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/UsenetDownloadStationFixture.cs @@ -7,12 +7,12 @@ using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Common.Http; using NzbDrone.Core.Download; +using NzbDrone.Core.Download.Clients; 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; -using NzbDrone.Core.Download.Clients; namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { @@ -65,12 +65,12 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", FileNameBuilder.CleanFileName(_remoteAlbum.Release.Title) + ".nzb" } }, Transfer = new Dictionary { - { "size_downloaded", "0"}, + { "size_downloaded", "0" }, { "speed_download", "0" } } } @@ -88,12 +88,12 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", FileNameBuilder.CleanFileName(_remoteAlbum.Release.Title) + ".nzb" } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, + { "size_downloaded", "1000" }, { "speed_download", "0" } }, } @@ -111,12 +111,12 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", FileNameBuilder.CleanFileName(_remoteAlbum.Release.Title) + ".nzb" } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, + { "size_downloaded", "1000" }, { "speed_download", "0" } } } @@ -134,12 +134,12 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", FileNameBuilder.CleanFileName(_remoteAlbum.Release.Title) + ".nzb" } }, Transfer = new Dictionary { - { "size_downloaded", "100"}, + { "size_downloaded", "100" }, { "speed_download", "50" } } } @@ -157,12 +157,12 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", FileNameBuilder.CleanFileName(_remoteAlbum.Release.Title) + ".nzb" } }, Transfer = new Dictionary { - { "size_downloaded", "10"}, + { "size_downloaded", "10" }, { "speed_download", "0" } } } @@ -200,7 +200,6 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests .Returns((path, setttings, serial) => _physicalPath); } - protected void GivenSerialNumber() { Mocker.GetMock() @@ -244,7 +243,6 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests .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); @@ -385,7 +383,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests Mocker.GetMock() .Verify(v => v.AddTaskFromUrl(It.IsAny(), null, _settings), Times.Never()); } - + [Test] public void GetStatus_should_map_outputpath_when_using_default() { diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/HadoukenTests/HadoukenFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/HadoukenTests/HadoukenFixture.cs index 92bb41460..8fade99fc 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/HadoukenTests/HadoukenFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/HadoukenTests/HadoukenFixture.cs @@ -1,3 +1,7 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Common.Http; @@ -5,10 +9,6 @@ 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 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.HadoukenTests }; Mocker.GetMock() - .Setup(s => s.GetHashFromTorrentFile(It.IsAny())) + .Setup(s => s.GetHashFromTorrentFile(It.IsAny())) .Returns("CBC2F069FE8BB2F544EAE707D75BCD3DE9DCF951"); Mocker.GetMock() @@ -210,7 +210,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.HadoukenTests [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()); @@ -301,7 +301,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.HadoukenTests .Returns("hash"); var result = Subject.Download(remoteAlbum); - + Assert.IsFalse(result.Any(c => char.IsLower(c))); } diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbVortexTests/NzbVortexFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbVortexTests/NzbVortexFixture.cs index bffb73e31..7203f163d 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 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.NzbVortexTests { Subject.Definition = new DownloadClientDefinition(); Subject.Definition.Settings = new NzbVortexSettings - { - Host = "127.0.0.1", - Port = 2222, - ApiKey = "1234-ABCD", - MusicCategory = "Music", - RecentTvPriority = (int)NzbgetPriority.High - }; + { + Host = "127.0.0.1", + Port = 2222, + ApiKey = "1234-ABCD", + MusicCategory = "Music", + RecentTvPriority = (int)NzbgetPriority.High + }; _queued = new NzbVortexQueueItem - { - Id = RandomNumber, - DownloadedSize = 1000, - TotalDownloadSize = 10, - GroupName = "Music", - UiTitle = "Fall Out Boy-Make America Psycho Again-CD-FLAC-2015-FORSAKEN" + { + Id = RandomNumber, + DownloadedSize = 1000, + TotalDownloadSize = 10, + GroupName = "Music", + UiTitle = "Fall Out Boy-Make America Psycho Again-CD-FLAC-2015-FORSAKEN" }; _failed = new NzbVortexQueueItem - { - DownloadedSize = 1000, - TotalDownloadSize = 1000, - GroupName = "Music", - UiTitle = "Fall Out Boy-Make America Psycho Again-CD-FLAC-2015-FORSAKEN", - DestinationPath = "somedirectory", - State = NzbVortexStateType.UncompressFailed, - }; + { + DownloadedSize = 1000, + TotalDownloadSize = 1000, + GroupName = "Music", + UiTitle = "Fall Out Boy-Make America Psycho Again-CD-FLAC-2015-FORSAKEN", + DestinationPath = "somedirectory", + State = NzbVortexStateType.UncompressFailed, + }; _completed = new NzbVortexQueueItem - { - DownloadedSize = 1000, - TotalDownloadSize = 1000, - GroupName = "Music", - UiTitle = "Fall Out Boy-Make America Psycho Again-CD-FLAC-2015-FORSAKEN", - DestinationPath = "/remote/mount/music/Fall Out Boy-Make America Psycho Again-CD-FLAC-2015-FORSAKEN", - State = NzbVortexStateType.Done - }; + { + DownloadedSize = 1000, + TotalDownloadSize = 1000, + GroupName = "Music", + UiTitle = "Fall Out Boy-Make America Psycho Again-CD-FLAC-2015-FORSAKEN", + DestinationPath = "/remote/mount/music/Fall Out Boy-Make America Psycho Again-CD-FLAC-2015-FORSAKEN", + State = NzbVortexStateType.Done + }; } protected void GivenFailedDownload() @@ -103,7 +103,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.NzbVortexTests public void queued_item_should_have_required_properties() { GivenQueue(_queued); - + var result = Subject.GetItems().Single(); VerifyQueued(result); diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbgetTests/NzbgetFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbgetTests/NzbgetFixture.cs index 11777f6d1..0d37a3767 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 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.NzbgetTests { Subject.Definition = new DownloadClientDefinition(); Subject.Definition.Settings = new NzbgetSettings - { - Host = "127.0.0.1", - Port = 2222, - Username = "admin", - Password = "pass", - MusicCategory = "music", - RecentTvPriority = (int)NzbgetPriority.High - }; + { + Host = "127.0.0.1", + Port = 2222, + Username = "admin", + Password = "pass", + MusicCategory = "music", + RecentTvPriority = (int)NzbgetPriority.High + }; _queued = new NzbgetQueueItem - { - FileSizeLo = 1000, - RemainingSizeLo = 10, - Category = "music", - NzbName = "Fall Out Boy-Make America Psycho Again-CD-FLAC-2015-FORSAKEN", - Parameters = new List { new NzbgetParameter { Name = "drone", Value = "id" } } - }; + { + FileSizeLo = 1000, + RemainingSizeLo = 10, + Category = "music", + NzbName = "Fall Out Boy-Make America Psycho Again-CD-FLAC-2015-FORSAKEN", + Parameters = new List { new NzbgetParameter { Name = "drone", Value = "id" } } + }; _failed = new NzbgetHistoryItem - { - FileSizeLo = 1000, - Category = "music", - Name = "Fall Out Boy-Make America Psycho Again-CD-FLAC-2015-FORSAKEN", - 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 = "music", + Name = "Fall Out Boy-Make America Psycho Again-CD-FLAC-2015-FORSAKEN", + 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 = "music", - Name = "Fall Out Boy-Make America Psycho Again-CD-FLAC-2015-FORSAKEN", - DestDir = "/remote/mount/music/Fall Out Boy-Make America Psycho Again-CD-FLAC-2015-FORSAKEN", - Parameters = new List { new NzbgetParameter { Name = "drone", Value = "id" } }, - ParStatus = "SUCCESS", - UnpackStatus = "NONE", - MoveStatus = "SUCCESS", - ScriptStatus = "NONE", - DeleteStatus = "NONE", - MarkStatus = "NONE" - }; + { + FileSizeLo = 1000, + Category = "music", + Name = "Fall Out Boy-Make America Psycho Again-CD-FLAC-2015-FORSAKEN", + DestDir = "/remote/mount/music/Fall Out Boy-Make America Psycho Again-CD-FLAC-2015-FORSAKEN", + 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())) @@ -168,7 +168,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.NzbgetTests GivenQueue(_queued); GivenHistory(null); - + var result = Subject.GetItems().Single(); VerifyQueued(result); @@ -320,7 +320,6 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.NzbgetTests { // 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/QBittorrentTests/QBittorrentFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/QBittorrentTests/QBittorrentFixture.cs index 0f0e27339..93dca86cc 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/QBittorrentTests/QBittorrentFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/QBittorrentTests/QBittorrentFixture.cs @@ -7,9 +7,9 @@ using NUnit.Framework; using NzbDrone.Common.Http; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.QBittorrent; +using NzbDrone.Core.Exceptions; using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Test.Common; -using NzbDrone.Core.Exceptions; namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests { @@ -63,7 +63,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests 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() @@ -299,7 +299,6 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests [Test] public void Download_should_accept_magnet_if_trackers_provided_and_dht_is_disabled() { - Mocker.GetMock() .Setup(s => s.GetConfig(It.IsAny())) .Returns(new QBittorrentPreferences { DhtEnabled = false }); @@ -308,7 +307,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests remoteAlbum.Release.DownloadUrl = "magnet:?xt=urn:btih:ZPBPA2P6ROZPKRHK44D5OW6NHXU5Z6KR&tr=udp://abc"; Assert.DoesNotThrow(() => Subject.Download(remoteAlbum)); - + Mocker.GetMock() .Verify(s => s.AddTorrentFromUrl(It.IsAny(), It.IsAny()), Times.Once()); } @@ -417,8 +416,10 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests 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 { @@ -502,7 +503,6 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests item.CanMoveFiles.Should().BeFalse(); } - [Test] public void should_not_be_removable_and_should_not_allow_move_files_if_max_seedingtime_reached_and_not_paused() { @@ -567,7 +567,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests var item = Subject.GetItems().Single(); item.CanBeRemoved.Should().BeFalse(); item.CanMoveFiles.Should().BeFalse(); - + var item2 = Subject.GetItems().Single(); Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/RTorrentTests/RTorrentFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/RTorrentTests/RTorrentFixture.cs index 1ef20907b..f1a8a920e 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 { @@ -25,26 +25,26 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.RTorrentTests }; _downloading = new RTorrentTorrent - { - Hash = "HASH", - IsFinished = false, - IsOpen = true, - IsActive = true, - Name = _title, - TotalSize = 1000, - RemainingSize = 500, - Path = "somepath" - }; + { + Hash = "HASH", + IsFinished = false, + IsOpen = true, + IsActive = true, + Name = _title, + TotalSize = 1000, + RemainingSize = 500, + Path = "somepath" + }; _completed = new RTorrentTorrent - { - Hash = "HASH", - IsFinished = true, - Name = _title, - TotalSize = 1000, - RemainingSize = 0, - Path = "somepath" - }; + { + Hash = "HASH", + IsFinished = true, + Name = _title, + TotalSize = 1000, + RemainingSize = 0, + Path = "somepath" + }; Mocker.GetMock() .Setup(s => s.GetHashFromTorrentFile(It.IsAny())) @@ -61,7 +61,6 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.RTorrentTests .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 1b9dc4bb6..0532dbff9 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 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.SabnzbdTests.JsonConve [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 dfe7225e7..ebb8a30fb 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/SabnzbdFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/SabnzbdFixture.cs @@ -1,18 +1,18 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FizzWare.NBuilder; 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.Core.Music; -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 { @@ -30,20 +30,20 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.SabnzbdTests { Subject.Definition = new DownloadClientDefinition(); Subject.Definition.Settings = new SabnzbdSettings - { - Host = "127.0.0.1", - Port = 2222, - ApiKey = "5c770e3197e4fe763423ee7c392c25d1", - Username = "admin", - Password = "pass", - MusicCategory = "tv", - RecentTvPriority = (int)SabnzbdPriority.High - }; + { + Host = "127.0.0.1", + Port = 2222, + ApiKey = "5c770e3197e4fe763423ee7c392c25d1", + Username = "admin", + Password = "pass", + MusicCategory = "tv", + RecentTvPriority = (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 { @@ -56,11 +56,11 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.SabnzbdTests Title = "Droned.S01E01.Pilot.1080p.WEB-DL-DRONE" } } - }; + }; _failed = new SabnzbdHistory - { - Items = new List() + { + Items = new List() { new SabnzbdHistoryItem { @@ -71,11 +71,11 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.SabnzbdTests Title = "Droned.S01E01.Pilot.1080p.WEB-DL-DRONE" } } - }; + }; _completed = new SabnzbdHistory - { - Items = new List() + { + Items = new List() { new SabnzbdHistoryItem { @@ -87,19 +87,19 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.SabnzbdTests Storage = "/remote/mount/vv/Droned.S01E01.Pilot.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 = "tv", Dir = "vv" } } - }; + }; Mocker.GetMock() .Setup(v => v.GetVersion(It.IsAny())) @@ -110,9 +110,9 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.SabnzbdTests .Returns(_config); _fullStatus = new SabnzbdFullStatus - { - CompleteDir = @"Y:\nzbget\root\complete".AsOsAgnostic() - }; + { + CompleteDir = @"Y:\nzbget\root\complete".AsOsAgnostic() + }; Mocker.GetMock() .Setup(s => s.GetFullStatus(It.IsAny())) @@ -163,7 +163,9 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.SabnzbdTests 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 0534dfcf9..ae6f4f84e 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 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.TransmissionTests 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 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.TransmissionTests 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 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.TransmissionTests 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 8afa3d57b..a29dbbd3e 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 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.TransmissionTests Mocker.GetMock() .Setup(v => v.GetConfig(It.IsAny())) .Returns(() => Json.Deserialize(_transmissionConfigItems.ToJson())); - } protected void GivenMusicCategory() @@ -144,7 +143,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.TransmissionTests .Setup(s => s.AddTorrentFromData(It.IsAny(), It.IsAny(), It.IsAny())) .Callback(PrepareClientToReturnQueuedItem); } - + protected virtual void GivenTorrents(List torrents) { if (torrents == null) @@ -159,7 +158,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.TransmissionTests protected void PrepareClientToReturnQueuedItem() { - GivenTorrents(new List + GivenTorrents(new List { _queued }); @@ -167,7 +166,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.TransmissionTests protected void PrepareClientToReturnDownloadingItem() { - GivenTorrents(new List + GivenTorrents(new List { _downloading }); @@ -175,7 +174,7 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.TransmissionTests protected void PrepareClientToReturnFailedItem() { - GivenTorrents(new List + GivenTorrents(new List { _failed }); @@ -184,7 +183,10 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.TransmissionTests 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 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.TransmissionTests } } - 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 060ca7be4..17c8bc952 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 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.UTorrentTests { Subject.Definition = new DownloadClientDefinition(); Subject.Definition.Settings = new UTorrentSettings - { - Host = "127.0.0.1", - Port = 2222, - Username = "admin", - Password = "pass", - MusicCategory = "lidarr" + { + Host = "127.0.0.1", + Port = 2222, + Username = "admin", + Password = "pass", + MusicCategory = "lidarr" }; _queued = new UTorrentTorrent - { - Hash = "HASH", - Status = UTorrentTorrentStatus.Queued | UTorrentTorrentStatus.Loaded, - Name = _title, - Size = 1000, - Remaining = 1000, - Progress = 0, - Label = "lidarr", - DownloadUrl = _downloadUrl, - RootDownloadPath = "somepath" - }; + { + Hash = "HASH", + Status = UTorrentTorrentStatus.Queued | UTorrentTorrentStatus.Loaded, + Name = _title, + Size = 1000, + Remaining = 1000, + Progress = 0, + Label = "lidarr", + DownloadUrl = _downloadUrl, + RootDownloadPath = "somepath" + }; _downloading = new UTorrentTorrent - { - Hash = "HASH", - Status = UTorrentTorrentStatus.Started | UTorrentTorrentStatus.Loaded, - Name = _title, - Size = 1000, - Remaining = 100, - Progress = 0.9, - Label = "lidarr", - DownloadUrl = _downloadUrl, - RootDownloadPath = "somepath" - }; + { + Hash = "HASH", + Status = UTorrentTorrentStatus.Started | UTorrentTorrentStatus.Loaded, + Name = _title, + Size = 1000, + Remaining = 100, + Progress = 0.9, + Label = "lidarr", + DownloadUrl = _downloadUrl, + RootDownloadPath = "somepath" + }; _failed = new UTorrentTorrent - { - Hash = "HASH", - Status = UTorrentTorrentStatus.Error, - Name = _title, - Size = 1000, - Remaining = 100, - Progress = 0.9, - Label = "lidarr", - DownloadUrl = _downloadUrl, - RootDownloadPath = "somepath" - }; + { + Hash = "HASH", + Status = UTorrentTorrentStatus.Error, + Name = _title, + Size = 1000, + Remaining = 100, + Progress = 0.9, + Label = "lidarr", + DownloadUrl = _downloadUrl, + RootDownloadPath = "somepath" + }; _completed = new UTorrentTorrent - { - Hash = "HASH", - Status = UTorrentTorrentStatus.Checked | UTorrentTorrentStatus.Loaded, - Name = _title, - Size = 1000, - Remaining = 0, - Progress = 1.0, - Label = "lidarr", - DownloadUrl = _downloadUrl, - RootDownloadPath = "somepath" - }; + { + Hash = "HASH", + Status = UTorrentTorrentStatus.Checked | UTorrentTorrentStatus.Loaded, + Name = _title, + Size = 1000, + Remaining = 0, + Progress = 1.0, + Label = "lidarr", + 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 40af0116a..5da147c62 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 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.VuzeTests 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 4ba13fd85..3fd0da73b 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadServiceFixture.cs @@ -10,10 +10,9 @@ using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients; using NzbDrone.Core.Exceptions; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; -using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download { @@ -82,7 +81,7 @@ namespace NzbDrone.Core.Test.Download { var mock = WithUsenetClient(); mock.Setup(s => s.Download(It.IsAny())); - + Subject.DownloadReport(_parseResult); VerifyEventPublished(); @@ -93,7 +92,7 @@ namespace NzbDrone.Core.Test.Download { var mock = WithUsenetClient(); mock.Setup(s => s.Download(It.IsAny())); - + Subject.DownloadReport(_parseResult); mock.Verify(s => s.Download(It.IsAny()), Times.Once()); @@ -116,8 +115,9 @@ namespace NzbDrone.Core.Test.Download { var mock = WithUsenetClient(); mock.Setup(s => s.Download(It.IsAny())) - .Callback(v => { - throw new ReleaseDownloadException(v.Release, "Error", new WebException()); + .Callback(v => + { + throw new ReleaseDownloadException(v.Release, "Error", new WebException()); }); Assert.Throws(() => Subject.DownloadReport(_parseResult)); @@ -135,8 +135,9 @@ namespace NzbDrone.Core.Test.Download var mock = WithUsenetClient(); mock.Setup(s => s.Download(It.IsAny())) - .Callback(v => { - throw new ReleaseDownloadException(v.Release, "Error", new TooManyRequestsException(request, response)); + .Callback(v => + { + throw new ReleaseDownloadException(v.Release, "Error", new TooManyRequestsException(request, response)); }); Assert.Throws(() => Subject.DownloadReport(_parseResult)); @@ -184,7 +185,8 @@ namespace NzbDrone.Core.Test.Download { 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 420647de4..36b61ce42 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; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.History; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download @@ -44,11 +44,9 @@ namespace NzbDrone.Core.Test.Download .With(c => c.RemoteAlbum = remoteAlbum) .Build(); - Mocker.GetMock() .Setup(s => s.Find(_trackedDownload.DownloadItem.DownloadId, HistoryEventType.Grabbed)) .Returns(_grabHistory); - } private void GivenNoGrabbedHistory() @@ -131,7 +129,6 @@ namespace NzbDrone.Core.Test.Download _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 84264ce70..2fdf45413 100644 --- a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/AddFixture.cs +++ b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/AddFixture.cs @@ -8,12 +8,12 @@ using NUnit.Framework; using NzbDrone.Common.Extensions; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download.Pending; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests { @@ -39,16 +39,16 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests .Build(); _profile = new QualityProfile - { - Name = "Test", - Cutoff = Quality.MP3_256.Id, - Items = new List + { + Name = "Test", + Cutoff = Quality.MP3_256.Id, + Items = new List { new QualityProfileQualityItem { Allowed = true, Quality = Quality.MP3_256 }, new QualityProfileQualityItem { Allowed = true, Quality = Quality.MP3_320 }, new QualityProfileQualityItem { Allowed = true, Quality = Quality.MP3_320 } }, - }; + }; _artist.QualityProfile = new LazyLoaded(_profile); @@ -58,11 +58,11 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests _parsedAlbumInfo.Quality = new QualityModel(Quality.MP3_256); _remoteAlbum = new RemoteAlbum(); - _remoteAlbum.Albums = new List{ _album }; + _remoteAlbum.Albums = new List { _album }; _remoteAlbum.Artist = _artist; _remoteAlbum.ParsedAlbumInfo = _parsedAlbumInfo; _remoteAlbum.Release = _release; - + _temporarilyRejected = new DownloadDecision(_remoteAlbum, new Rejection("Temp Rejected", RejectionType.Temporary)); _heldReleases = new List(); @@ -85,7 +85,7 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests Mocker.GetMock() .Setup(s => s.GetAlbums(It.IsAny(), _artist, null)) - .Returns(new List {_album}); + .Returns(new List { _album }); Mocker.GetMock() .Setup(s => s.PrioritizeDecisions(It.IsAny>())) @@ -98,7 +98,6 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests release.Indexer = indexer; release.PublishDate = publishDate; - var heldReleases = Builder.CreateListOfSize(1) .All() .With(h => h.ArtistId = _artist.Id) diff --git a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/PendingReleaseServiceFixture.cs b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/PendingReleaseServiceFixture.cs index 8ff0f0ea0..5933db2e4 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.Download.Pending; 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 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests { Mocker.GetMock() .Setup(v => v.All()) - .Returns(new List { + .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 350bf47d2..e62ca5fa3 100644 --- a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveGrabbedFixture.cs +++ b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveGrabbedFixture.cs @@ -8,12 +8,12 @@ using NzbDrone.Common.Extensions; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Pending; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests { @@ -39,16 +39,16 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests .Build(); _profile = new QualityProfile - { - Name = "Test", - Cutoff = Quality.MP3_256.Id, - Items = new List + { + Name = "Test", + Cutoff = Quality.MP3_256.Id, + Items = new List { new QualityProfileQualityItem { Allowed = true, Quality = Quality.MP3_256 }, new QualityProfileQualityItem { Allowed = true, Quality = Quality.MP3_320 }, new QualityProfileQualityItem { Allowed = true, Quality = Quality.FLAC } }, - }; + }; _artist.QualityProfile = new LazyLoaded(_profile); @@ -58,11 +58,11 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests _parsedAlbumInfo.Quality = new QualityModel(Quality.MP3_256); _remoteAlbum = new RemoteAlbum(); - _remoteAlbum.Albums = new List{ _album }; + _remoteAlbum.Albums = new List { _album }; _remoteAlbum.Artist = _artist; _remoteAlbum.ParsedAlbumInfo = _parsedAlbumInfo; _remoteAlbum.Release = _release; - + _temporarilyRejected = new DownloadDecision(_remoteAlbum, new Rejection("Temp Rejected", RejectionType.Temporary)); _heldReleases = new List(); @@ -85,7 +85,7 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests Mocker.GetMock() .Setup(s => s.GetAlbums(It.IsAny(), _artist, null)) - .Returns(new List {_album}); + .Returns(new List { _album }); Mocker.GetMock() .Setup(s => s.PrioritizeDecisions(It.IsAny>())) diff --git a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemovePendingFixture.cs b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemovePendingFixture.cs index 642547e36..0784006ac 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 Moq; using NUnit.Framework; using NzbDrone.Common.Crypto; using NzbDrone.Core.Download.Pending; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests { @@ -32,7 +32,7 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests Mocker.GetMock() .Setup(s => s.All()) - .Returns( _pending); + .Returns(_pending); Mocker.GetMock() .Setup(s => s.GetArtist(It.IsAny())) @@ -44,22 +44,22 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests Mocker.GetMock() .Setup(s => s.GetAlbums(It.IsAny(), It.IsAny(), null)) - .Returns(new List{ _album }); + .Returns(new List { _album }); } private void AddPending(int id, string album) { _pending.Add(new PendingRelease - { - Id = id, - ParsedAlbumInfo = new ParsedAlbumInfo { AlbumTitle = album} - }); + { + Id = id, + ParsedAlbumInfo = new ParsedAlbumInfo { AlbumTitle = album } + }); } [Test] public void should_remove_same_release() { - AddPending(id: 1, album: "Album" ); + AddPending(id: 1, album: "Album"); var queueId = HashConverter.GetHashInt31(string.Format("pending-{0}-album{1}", 1, _album.Id)); @@ -67,7 +67,7 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests AssertRemoved(1); } - + [Test] public void should_remove_multiple_releases_release() { @@ -97,11 +97,10 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests AssertRemoved(1, 2); } - + 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 6889c6800..91cb93c2b 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.DecisionEngine; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Pending; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests { @@ -39,16 +39,16 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests .Build(); _profile = new QualityProfile - { - Name = "Test", - Cutoff = Quality.MP3_192.Id, - Items = new List + { + Name = "Test", + Cutoff = Quality.MP3_192.Id, + Items = new List { new QualityProfileQualityItem { Allowed = true, Quality = Quality.MP3_192 }, new QualityProfileQualityItem { Allowed = true, Quality = Quality.MP3_256 }, new QualityProfileQualityItem { Allowed = true, Quality = Quality.MP3_320 } }, - }; + }; _artist.QualityProfile = new LazyLoaded(_profile); @@ -58,7 +58,7 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests _parsedAlbumInfo.Quality = new QualityModel(Quality.MP3_192); _remoteAlbum = new RemoteAlbum(); - _remoteAlbum.Albums = new List{ _album }; + _remoteAlbum.Albums = new List { _album }; _remoteAlbum.Artist = _artist; _remoteAlbum.ParsedAlbumInfo = _parsedAlbumInfo; _remoteAlbum.Release = _release; @@ -79,7 +79,7 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests Mocker.GetMock() .Setup(s => s.GetAlbums(It.IsAny(), _artist, null)) - .Returns(new List {_album}); + .Returns(new List { _album }); Mocker.GetMock() .Setup(s => s.PrioritizeDecisions(It.IsAny>())) @@ -92,7 +92,6 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests release.Indexer = indexer; release.PublishDate = publishDate; - var heldReleases = Builder.CreateListOfSize(1) .All() .With(h => h.ArtistId = _artist.Id) diff --git a/src/NzbDrone.Core.Test/Download/RedownloadFailedDownloadServiceFixture.cs b/src/NzbDrone.Core.Test/Download/RedownloadFailedDownloadServiceFixture.cs index a907d7ed5..a870f32f2 100644 --- a/src/NzbDrone.Core.Test/Download/RedownloadFailedDownloadServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Download/RedownloadFailedDownloadServiceFixture.cs @@ -1,13 +1,13 @@ -using NUnit.Framework; -using NzbDrone.Core.Download; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Messaging.Commands; -using Moq; using System.Collections.Generic; -using NzbDrone.Core.Music; using FizzWare.NBuilder; +using Moq; +using NUnit.Framework; using NzbDrone.Core.Configuration; +using NzbDrone.Core.Download; using NzbDrone.Core.IndexerSearch; +using NzbDrone.Core.Messaging.Commands; +using NzbDrone.Core.Music; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Download { @@ -29,7 +29,8 @@ namespace NzbDrone.Core.Test.Download [Test] public void should_skip_redownload_if_event_has_skipredownload_set() { - var failedEvent = new DownloadFailedEvent { + var failedEvent = new DownloadFailedEvent + { ArtistId = 1, AlbumIds = new List { 1 }, SkipReDownload = true @@ -45,7 +46,8 @@ namespace NzbDrone.Core.Test.Download [Test] public void should_skip_redownload_if_redownload_failed_disabled() { - var failedEvent = new DownloadFailedEvent { + var failedEvent = new DownloadFailedEvent + { ArtistId = 1, AlbumIds = new List { 1 } }; @@ -64,7 +66,8 @@ namespace NzbDrone.Core.Test.Download [Test] public void should_redownload_album_on_failure() { - var failedEvent = new DownloadFailedEvent { + var failedEvent = new DownloadFailedEvent + { ArtistId = 1, AlbumIds = new List { 2 } }; @@ -74,7 +77,8 @@ namespace NzbDrone.Core.Test.Download Mocker.GetMock() .Verify(x => x.Push(It.Is(c => c.AlbumIds.Count == 1 && c.AlbumIds[0] == 2), - It.IsAny(), It.IsAny()), + It.IsAny(), + It.IsAny()), Times.Once()); Mocker.GetMock() @@ -85,7 +89,8 @@ namespace NzbDrone.Core.Test.Download [Test] public void should_redownload_multiple_albums_on_failure() { - var failedEvent = new DownloadFailedEvent { + var failedEvent = new DownloadFailedEvent + { ArtistId = 1, AlbumIds = new List { 2, 3 } }; @@ -96,7 +101,8 @@ namespace NzbDrone.Core.Test.Download .Verify(x => x.Push(It.Is(c => c.AlbumIds.Count == 2 && c.AlbumIds[0] == 2 && c.AlbumIds[1] == 3), - It.IsAny(), It.IsAny()), + It.IsAny(), + It.IsAny()), Times.Once()); Mocker.GetMock() @@ -108,7 +114,8 @@ namespace NzbDrone.Core.Test.Download public void should_redownload_artist_on_failure() { // note that artist is set to have 3 albums in setup - var failedEvent = new DownloadFailedEvent { + var failedEvent = new DownloadFailedEvent + { ArtistId = 2, AlbumIds = new List { 1, 2, 3 } }; @@ -117,7 +124,8 @@ namespace NzbDrone.Core.Test.Download Mocker.GetMock() .Verify(x => x.Push(It.Is(c => c.ArtistId == failedEvent.ArtistId), - It.IsAny(), It.IsAny()), + It.IsAny(), + It.IsAny()), Times.Once()); Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/Download/TrackedDownloads/TrackedDownloadServiceFixture.cs b/src/NzbDrone.Core.Test/Download/TrackedDownloads/TrackedDownloadServiceFixture.cs index 23b9006b4..9246c195d 100644 --- a/src/NzbDrone.Core.Test/Download/TrackedDownloads/TrackedDownloadServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Download/TrackedDownloads/TrackedDownloadServiceFixture.cs @@ -1,17 +1,17 @@ using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Core.Download; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.History; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.Music; +using NzbDrone.Core.Music.Events; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; -using NzbDrone.Core.Indexers; -using System.Linq; -using NzbDrone.Core.Music.Events; namespace NzbDrone.Core.Test.Download.TrackedDownloads { @@ -22,13 +22,15 @@ namespace NzbDrone.Core.Test.Download.TrackedDownloads { Mocker.GetMock() .Setup(s => s.FindByDownloadId(It.Is(sr => sr == "35238"))) - .Returns(new List(){ - new History.History(){ + .Returns(new List() + { + new History.History() + { DownloadId = "35238", SourceTitle = "Audio Artist - Audio Album [2018 - FLAC]", ArtistId = 5, AlbumId = 4, - } + } }); } 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 7df4a0804..a5fdc7988 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 FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Extras.Metadata; using NzbDrone.Core.Extras.Metadata.Consumers.Roksbox; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; +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 64c56396c..d0ae5ef5c 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 FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Extras.Metadata; using NzbDrone.Core.Extras.Metadata.Consumers.Wdtv; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; +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 dd335843e..d7dcbba93 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 Moq; using NUnit.Framework; using NzbDrone.Core.Extras.Metadata; using NzbDrone.Core.Extras.Metadata.Consumers.Xbmc; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; +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 752dff23f..a17f142e3 100644 --- a/src/NzbDrone.Core.Test/FluentTest.cs +++ b/src/NzbDrone.Core.Test/FluentTest.cs @@ -9,7 +9,7 @@ using NzbDrone.Test.Common; namespace NzbDrone.Core.Test { [TestFixture] - + public class FluentTest : CoreTest { [TestCase(null, "def", "def")] @@ -87,11 +87,7 @@ namespace NzbDrone.Core.Test [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 @@ namespace NzbDrone.Core.Test [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 @@ namespace NzbDrone.Core.Test [Test] public void MaxOrDefault_should_return_zero_when_collection_is_null() { - List list = null; - var result = list.MaxOrDefault(); //Resolve @@ -126,10 +118,8 @@ namespace NzbDrone.Core.Test [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 @@ namespace NzbDrone.Core.Test [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 @@ namespace NzbDrone.Core.Test [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 @@ namespace NzbDrone.Core.Test [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 @@ namespace NzbDrone.Core.Test [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 17cee0e69..d9b2a7388 100644 --- a/src/NzbDrone.Core.Test/Framework/CoreTest.cs +++ b/src/NzbDrone.Core.Test/Framework/CoreTest.cs @@ -5,12 +5,12 @@ 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.MetadataSource; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Framework { @@ -19,8 +19,8 @@ namespace NzbDrone.Core.Test.Framework protected void UseRealHttp() { Mocker.GetMock().SetupGet(c => c.Version).Returns(new Version("3.0.0")); - Mocker.GetMock().SetupGet(c=>c.Version).Returns("1.0.0"); - Mocker.GetMock().SetupGet(c=>c.Name).Returns("TestOS"); + Mocker.GetMock().SetupGet(c => c.Version).Returns("1.0.0"); + Mocker.GetMock().SetupGet(c => c.Name).Returns("TestOS"); Mocker.SetConstant(new HttpProxySettingsProvider(Mocker.Resolve())); Mocker.SetConstant(new ManagedWebProxyFactory(Mocker.Resolve())); @@ -31,7 +31,8 @@ namespace NzbDrone.Core.Test.Framework } } - public abstract class CoreTest : CoreTest where TSubject : class + public abstract class CoreTest : CoreTest + where TSubject : class { private TSubject _subject; @@ -52,7 +53,6 @@ namespace NzbDrone.Core.Test.Framework return _subject; } - } } } diff --git a/src/NzbDrone.Core.Test/Framework/DbTest.cs b/src/NzbDrone.Core.Test/Framework/DbTest.cs index d24d288ed..f548c2c41 100644 --- a/src/NzbDrone.Core.Test/Framework/DbTest.cs +++ b/src/NzbDrone.Core.Test/Framework/DbTest.cs @@ -1,9 +1,7 @@ using System; using System.Collections.Generic; using System.Data.SQLite; -using System.IO; using System.Linq; -using FluentMigrator.Runner; using Marr.Data; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -43,7 +41,6 @@ namespace NzbDrone.Core.Test.Framework return _subject; } - } } @@ -59,7 +56,9 @@ namespace NzbDrone.Core.Test.Framework 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; } @@ -80,6 +79,7 @@ namespace NzbDrone.Core.Test.Framework Mocker.SetConstant(mainDb); break; } + case MigrationType.Log: { var logDb = new LogDatabase(database); @@ -87,6 +87,7 @@ namespace NzbDrone.Core.Test.Framework Mocker.SetConstant(logDb); break; } + default: { throw new ArgumentException("Invalid MigrationType"); @@ -128,7 +129,7 @@ namespace NzbDrone.Core.Test.Framework GC.Collect(); GC.WaitForPendingFinalizers(); SQLiteConnection.ClearAllPools(); - + if (TestFolderInfo != null) { DeleteTempFolder(TestFolderInfo.AppDataFolder); diff --git a/src/NzbDrone.Core.Test/Framework/DirectDataMapper.cs b/src/NzbDrone.Core.Test/Framework/DirectDataMapper.cs index ccc469e21..481d46fb1 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(); T QueryScalar(string sql); } @@ -56,7 +57,8 @@ namespace NzbDrone.Core.Test.Framework 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); @@ -94,7 +96,8 @@ namespace NzbDrone.Core.Test.Framework return item; } - protected T MapToObject(DataRow dataRow) where T : new() + protected T MapToObject(DataRow dataRow) + where T : new() { var item = new T(); @@ -117,7 +120,6 @@ namespace NzbDrone.Core.Test.Framework object value = MapValue(dataRow, i, propertyType); - propertyInfo.SetValue(item, value, null); } diff --git a/src/NzbDrone.Core.Test/Framework/FileSystemTest.cs b/src/NzbDrone.Core.Test/Framework/FileSystemTest.cs index 6d37ea2d3..8790355c9 100644 --- a/src/NzbDrone.Core.Test/Framework/FileSystemTest.cs +++ b/src/NzbDrone.Core.Test/Framework/FileSystemTest.cs @@ -1,11 +1,12 @@ -using NUnit.Framework; -using System.IO.Abstractions.TestingHelpers; +using System.IO.Abstractions.TestingHelpers; +using NUnit.Framework; using NzbDrone.Common.Disk; using Unity.Resolution; namespace NzbDrone.Core.Test.Framework { - public abstract class FileSystemTest : CoreTest where TSubject : class + public abstract class FileSystemTest : CoreTest + where TSubject : class { protected MockFileSystem FileSystem { get; private set; } protected IDiskProvider DiskProvider { get; private set; } @@ -15,9 +16,10 @@ namespace NzbDrone.Core.Test.Framework { FileSystem = new MockFileSystem(); - DiskProvider = Mocker.Resolve("ActualDiskProvider", new ResolverOverride[] { + DiskProvider = Mocker.Resolve("ActualDiskProvider", new ResolverOverride[] + { new ParameterOverride("fileSystem", FileSystem) - }); + }); } } } diff --git a/src/NzbDrone.Core.Test/Framework/MigrationTest.cs b/src/NzbDrone.Core.Test/Framework/MigrationTest.cs index 492d068e6..7a59c837b 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 338e73302..9394ba74b 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)); } - } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Framework/TestDatabase.cs b/src/NzbDrone.Core.Test/Framework/TestDatabase.cs index 30fb2be0c..4215a66c6 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 @@ namespace NzbDrone.Core.Test.Framework _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 16639271d..6c0f70cc2 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.Configuration; using NzbDrone.Core.Extras.Metadata; using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.Housekeeping.Housekeepers; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.HealthCheck.Checks @@ -30,7 +30,6 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks .With(c => c.Path = "C:\\Music\\".AsOsAgnostic()) .Build().ToList(); - _metadata = Builder.CreateListOfSize(1) .Build().ToList(); @@ -38,16 +37,13 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks .Setup(c => c.GetAllArtists()) .Returns(_artist); - Mocker.GetMock() .Setup(c => c.GetFilesByArtist(_artist.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 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks Subject.Clean(); Mocker.GetMock().Verify(c => c.OpenReadStream(It.IsAny()), Times.Never()); - } [Test] @@ -70,8 +65,6 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks Mocker.GetMock().Verify(c => c.OpenReadStream(It.IsAny()), Times.Never()); } - - [Test] public void should_not_run_if_flag_is_false() { @@ -85,7 +78,6 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks AssertImageWasNotRemoved(); } - [Test] public void should_set_clean_flag_to_false() { @@ -96,11 +88,9 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks Mocker.GetMock().VerifySet(c => c.CleanupMetadataImages = false, Times.Once()); } - [Test] public void should_delete_html_images() { - var imagePath = "C:\\Music\\Album\\image.jpg".AsOsAgnostic(); _metadata.First().LastUpdated = new DateTime(2014, 12, 29); _metadata.First().RelativePath = "Album\\image.jpg".AsOsAgnostic(); @@ -110,19 +100,15 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks .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:\\Music\\Album\\image.jpg".AsOsAgnostic(); _metadata.First().LastUpdated = new DateTime(2014, 12, 29); _metadata.First().Type = MetadataType.AlbumImage; @@ -132,18 +118,15 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks .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:\\Music\\Album\\image.jpg".AsOsAgnostic(); _metadata.First().LastUpdated = new DateTime(2014, 12, 29); _metadata.First().RelativePath = "Album\\image.jpg".AsOsAgnostic(); @@ -152,7 +135,6 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks .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 56f83e0a9..e95c03f65 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/DownloadClientCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/DownloadClientCheckFixture.cs @@ -4,7 +4,6 @@ using NUnit.Framework; using NzbDrone.Core.Download; using NzbDrone.Core.HealthCheck.Checks; using NzbDrone.Core.Test.Framework; -using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.HealthCheck.Checks { @@ -25,7 +24,7 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks 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/ImportListStatusCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/ImportListStatusCheckFixture.cs index a69efdfb1..e0110c2ae 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/ImportListStatusCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/ImportListStatusCheckFixture.cs @@ -38,19 +38,18 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks if (backoffHours != 0.0) { _blockedImportLists.Add(new ImportListStatus - { - 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 mockImportList; } - [Test] public void should_not_return_error_when_no_import_lists() { diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/ImportMechanismCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/ImportMechanismCheckFixture.cs index 050eeadbb..f243fbf56 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/ImportMechanismCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/ImportMechanismCheckFixture.cs @@ -8,7 +8,6 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks [TestFixture] public class ImportMechanismCheckFixture : CoreTest { - private void GivenCompletedDownloadHandling(bool? enabled = null) { if (enabled.HasValue) @@ -23,10 +22,10 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks public void should_return_warning_when_completeddownloadhandling_false() { GivenCompletedDownloadHandling(false); - + Subject.Check().ShouldBeWarning(); } - + [Test] public void should_return_ok_when_no_issues_found() { diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerStatusCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerStatusCheckFixture.cs index 1d71d3a80..a77eecf13 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerStatusCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerStatusCheckFixture.cs @@ -39,19 +39,18 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks 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/RemotePathMappingCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/RemotePathMappingCheckFixture.cs index d16924ceb..3f40ce639 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/RemotePathMappingCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/RemotePathMappingCheckFixture.cs @@ -20,14 +20,15 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks [TestFixture] public class RemotePathMappingCheckFixture : CoreTest { - private string downloadRootPath = @"c:\Test".AsOsAgnostic(); - private string downloadItemPath = @"c:\Test\item".AsOsAgnostic(); + private string _downloadRootPath = @"c:\Test".AsOsAgnostic(); + private string _downloadItemPath = @"c:\Test\item".AsOsAgnostic(); - private DownloadClientInfo clientStatus; - private DownloadClientItem downloadItem; - private Mock downloadClient; - - static Exception[] DownloadClientExceptions = { + private DownloadClientInfo _clientStatus; + private DownloadClientItem _downloadItem; + private Mock _downloadClient; + + private static Exception[] DownloadClientExceptions = + { new DownloadClientUnavailableException("error"), new DownloadClientAuthenticationException("error"), new DownloadClientException("error") @@ -36,44 +37,48 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks [SetUp] public void Setup() { - downloadItem = new DownloadClientItem { - DownloadClient = "Test", - DownloadId = "TestId", - OutputPath = new OsPath(downloadItemPath) + _downloadItem = new DownloadClientItem + { + DownloadClient = "Test", + DownloadId = "TestId", + OutputPath = new OsPath(_downloadItemPath) }; - clientStatus = new DownloadClientInfo { - IsLocalhost = true, - OutputRootFolders = new List { new OsPath(downloadRootPath) } + _clientStatus = new DownloadClientInfo + { + IsLocalhost = true, + OutputRootFolders = new List { new OsPath(_downloadRootPath) } }; - downloadClient = Mocker.GetMock(); - downloadClient.Setup(s => s.Definition) + _downloadClient = Mocker.GetMock(); + _downloadClient.Setup(s => s.Definition) .Returns(new DownloadClientDefinition { Name = "Test" }); - downloadClient.Setup(s => s.GetItems()) - .Returns(new List { downloadItem }); + _downloadClient.Setup(s => s.GetItems()) + .Returns(new List { _downloadItem }); - downloadClient.Setup(s => s.GetStatus()) - .Returns(clientStatus); + _downloadClient.Setup(s => s.GetStatus()) + .Returns(_clientStatus); Mocker.GetMock() .Setup(s => s.GetDownloadClients()) - .Returns(new IDownloadClient[] { downloadClient.Object }); + .Returns(new IDownloadClient[] { _downloadClient.Object }); Mocker.GetMock() .Setup(x => x.FolderExists(It.IsAny())) - .Returns((string path) => { - Ensure.That(path, () => path).IsValidPath(); - return false; - }); + .Returns((string path) => + { + Ensure.That(path, () => path).IsValidPath(); + return false; + }); Mocker.GetMock() .Setup(x => x.FileExists(It.IsAny())) - .Returns((string path) => { - Ensure.That(path, () => path).IsValidPath(); - return false; - }); + .Returns((string path) => + { + Ensure.That(path, () => path).IsValidPath(); + return false; + }); } private void GivenFolderExists(string folder) @@ -90,7 +95,6 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks .Returns(true); } - private void GivenDocker() { Mocker.GetMock() @@ -101,7 +105,7 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks [Test] public void should_return_ok_if_setup_correctly() { - GivenFolderExists(downloadRootPath); + GivenFolderExists(_downloadRootPath); Subject.Check().ShouldBeOk(); } @@ -115,8 +119,8 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks [Test] public void should_return_mapping_error_if_remote_client_root_path_invalid() { - clientStatus.IsLocalhost = false; - clientStatus.OutputRootFolders = new List { new OsPath("An invalid path") }; + _clientStatus.IsLocalhost = false; + _clientStatus.OutputRootFolders = new List { new OsPath("An invalid path") }; Subject.Check().ShouldBeError(wikiFragment: "bad-remote-path-mapping"); } @@ -124,8 +128,8 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks [Test] public void should_return_download_client_error_if_local_client_root_path_invalid() { - clientStatus.IsLocalhost = true; - clientStatus.OutputRootFolders = new List { new OsPath("An invalid path") }; + _clientStatus.IsLocalhost = true; + _clientStatus.OutputRootFolders = new List { new OsPath("An invalid path") }; Subject.Check().ShouldBeError(wikiFragment: "bad-download-client-settings"); } @@ -133,19 +137,20 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks [Test] public void should_return_path_mapping_error_if_remote_client_download_root_missing() { - clientStatus.IsLocalhost = false; + _clientStatus.IsLocalhost = false; Subject.Check().ShouldBeError(wikiFragment: "bad-remote-path-mapping"); } - [Test, TestCaseSource("DownloadClientExceptions")] + [Test] + [TestCaseSource("DownloadClientExceptions")] public void should_return_ok_if_client_throws_downloadclientexception(Exception ex) { - downloadClient.Setup(s => s.GetStatus()) + _downloadClient.Setup(s => s.GetStatus()) .Throws(ex); - + Subject.Check().ShouldBeOk(); - + ExceptionVerification.ExpectedErrors(0); } @@ -153,24 +158,25 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks public void should_return_docker_path_mapping_error_if_on_docker_and_root_missing() { GivenDocker(); - + Subject.Check().ShouldBeError(wikiFragment: "docker-bad-remote-path-mapping"); } [Test] public void should_return_ok_on_track_imported_event() { - GivenFolderExists(downloadRootPath); + GivenFolderExists(_downloadRootPath); var importEvent = new TrackImportedEvent(new LocalTrack(), new TrackFile(), new List(), true, new DownloadClientItem()); Subject.Check(importEvent).ShouldBeOk(); } - + [Test] public void should_return_permissions_error_on_track_import_failed_event_if_file_exists() { - var localTrack = new LocalTrack { - Path = Path.Combine(downloadItemPath, "file.mp3") + var localTrack = new LocalTrack + { + Path = Path.Combine(_downloadItemPath, "file.mp3") }; GivenFileExists(localTrack.Path); @@ -182,9 +188,9 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks [Test] public void should_return_permissions_error_on_track_import_failed_event_if_folder_exists() { - GivenFolderExists(downloadItemPath); + GivenFolderExists(_downloadItemPath); - var importEvent = new TrackImportFailedEvent(null, null, true, downloadItem); + var importEvent = new TrackImportFailedEvent(null, null, true, _downloadItem); Subject.Check(importEvent).ShouldBeError(wikiFragment: "permissions-error"); } @@ -192,7 +198,7 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks [Test] public void should_return_permissions_error_on_track_import_failed_event_for_local_client_if_folder_does_not_exist() { - var importEvent = new TrackImportFailedEvent(null, null, true, downloadItem); + var importEvent = new TrackImportFailedEvent(null, null, true, _downloadItem); Subject.Check(importEvent).ShouldBeError(wikiFragment: "permissions-error"); } @@ -200,8 +206,8 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks [Test] public void should_return_mapping_error_on_track_import_failed_event_for_remote_client_if_folder_does_not_exist() { - clientStatus.IsLocalhost = false; - var importEvent = new TrackImportFailedEvent(null, null, true, downloadItem); + _clientStatus.IsLocalhost = false; + var importEvent = new TrackImportFailedEvent(null, null, true, _downloadItem); Subject.Check(importEvent).ShouldBeError(wikiFragment: "bad-remote-path-mapping"); } @@ -209,9 +215,9 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks [Test] public void should_return_mapping_error_on_track_import_failed_event_for_remote_client_if_path_invalid() { - clientStatus.IsLocalhost = false; - downloadItem.OutputPath = new OsPath("an invalid path"); - var importEvent = new TrackImportFailedEvent(null, null, true, downloadItem); + _clientStatus.IsLocalhost = false; + _downloadItem.OutputPath = new OsPath("an invalid path"); + var importEvent = new TrackImportFailedEvent(null, null, true, _downloadItem); Subject.Check(importEvent).ShouldBeError(wikiFragment: "bad-remote-path-mapping"); } @@ -219,9 +225,9 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks [Test] public void should_return_download_client_error_on_track_import_failed_event_for_remote_client_if_path_invalid() { - clientStatus.IsLocalhost = true; - downloadItem.OutputPath = new OsPath("an invalid path"); - var importEvent = new TrackImportFailedEvent(null, null, true, downloadItem); + _clientStatus.IsLocalhost = true; + _downloadItem.OutputPath = new OsPath("an invalid path"); + var importEvent = new TrackImportFailedEvent(null, null, true, _downloadItem); Subject.Check(importEvent).ShouldBeError(wikiFragment: "bad-download-client-settings"); } @@ -230,21 +236,22 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks public void should_return_docker_mapping_error_on_track_import_failed_event_inside_docker_if_folder_does_not_exist() { GivenDocker(); - - clientStatus.IsLocalhost = false; - var importEvent = new TrackImportFailedEvent(null, null, true, downloadItem); + + _clientStatus.IsLocalhost = false; + var importEvent = new TrackImportFailedEvent(null, null, true, _downloadItem); Subject.Check(importEvent).ShouldBeError(wikiFragment: "docker-bad-remote-path-mapping"); } - [Test, TestCaseSource("DownloadClientExceptions")] + [Test] + [TestCaseSource("DownloadClientExceptions")] public void should_return_ok_on_import_failed_event_if_client_throws_downloadclientexception(Exception ex) { - downloadClient.Setup(s => s.GetStatus()) + _downloadClient.Setup(s => s.GetStatus()) .Throws(ex); - - var importEvent = new TrackImportFailedEvent(null, null, true, downloadItem); - + + var importEvent = new TrackImportFailedEvent(null, null, true, _downloadItem); + Subject.Check(importEvent).ShouldBeOk(); ExceptionVerification.ExpectedErrors(0); diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/RootFolderCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/RootFolderCheckFixture.cs index bad299f2e..2ba2d8206 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/RootFolderCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/RootFolderCheckFixture.cs @@ -6,8 +6,8 @@ using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Core.HealthCheck.Checks; using NzbDrone.Core.ImportLists; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; +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 92355343e..bf149409d 100644 --- a/src/NzbDrone.Core.Test/HistoryTests/HistoryRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/HistoryTests/HistoryRepositoryFixture.cs @@ -2,15 +2,14 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.History; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.HistoryTests { [TestFixture] public class HistoryRepositoryFixture : DbTest { - [Test] public void should_read_write_dictionary() { @@ -26,7 +25,6 @@ namespace NzbDrone.Core.Test.HistoryTests StoredModel.Data.Should().HaveCount(2); } - [Test] public void should_get_download_history() { @@ -49,6 +47,5 @@ namespace NzbDrone.Core.Test.HistoryTests downloadHistory.Should().HaveCount(1); } - } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/HistoryTests/HistoryServiceFixture.cs b/src/NzbDrone.Core.Test/HistoryTests/HistoryServiceFixture.cs index ee95f14fa..051cc98cf 100644 --- a/src/NzbDrone.Core.Test/HistoryTests/HistoryServiceFixture.cs +++ b/src/NzbDrone.Core.Test/HistoryTests/HistoryServiceFixture.cs @@ -1,19 +1,19 @@ +using System.Collections.Generic; using System.IO; using System.Linq; using FizzWare.NBuilder; using Moq; using NUnit.Framework; +using NzbDrone.Core.Download; +using NzbDrone.Core.History; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Qualities; -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 NzbDrone.Core.Download; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.HistoryTests { @@ -32,11 +32,9 @@ namespace NzbDrone.Core.Test.HistoryTests }; _profileCustom = new QualityProfile - { Cutoff = Quality.MP3_320.Id, Items = QualityFixture.GetDefaultQualities(Quality.MP3_256), - }; } @@ -59,11 +57,11 @@ namespace NzbDrone.Core.Test.HistoryTests }; var downloadClientItem = new DownloadClientItem - { - DownloadClient = "sab", - DownloadId = "abcd" - }; - + { + DownloadClient = "sab", + DownloadId = "abcd" + }; + Subject.Handle(new TrackImportedEvent(localTrack, trackFile, new List(), true, downloadClientItem)); Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupAdditionalNamingSpecsFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupAdditionalNamingSpecsFixture.cs index 52134d539..657ec78ef 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupAdditionalNamingSpecsFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupAdditionalNamingSpecsFixture.cs @@ -34,4 +34,4 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers AllStoredModels.Should().HaveCount(1); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupAdditionalUsersFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupAdditionalUsersFixture.cs index 065b9d375..aea416ef1 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupAdditionalUsersFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupAdditionalUsersFixture.cs @@ -34,4 +34,4 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers AllStoredModels.Should().HaveCount(1); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedAlbumsFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedAlbumsFixture.cs index aeac11da6..df0282a29 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedAlbumsFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedAlbumsFixture.cs @@ -2,8 +2,8 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Housekeeping.Housekeepers; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { @@ -25,7 +25,7 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers public void should_not_delete_unorphaned_albums() { var artist = Builder.CreateNew() - .With(e => e.Metadata = new ArtistMetadata {Id = 1}) + .With(e => e.Metadata = new ArtistMetadata { Id = 1 }) .BuildNew(); Db.Insert(artist); diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedBlacklistFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedBlacklistFixture.cs index 37fe1cff6..bf35194c1 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedBlacklistFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedBlacklistFixture.cs @@ -1,12 +1,12 @@ -using FizzWare.NBuilder; +using System.Collections.Generic; +using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Blacklisting; using NzbDrone.Core.Housekeeping.Housekeepers; +using NzbDrone.Core.Music; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; -using System.Collections.Generic; namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedHistoryItemsFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedHistoryItemsFixture.cs index a118e4696..5994b0792 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedHistoryItemsFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedHistoryItemsFixture.cs @@ -2,9 +2,9 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Housekeeping.Housekeepers; +using NzbDrone.Core.Music; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedIndexerStatusFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedIndexerStatusFixture.cs index c5e757188..c7418960c 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedIndexerStatusFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedIndexerStatusFixture.cs @@ -51,4 +51,4 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers AllStoredModels.Should().Contain(h => h.ProviderId == _indexer.Id); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedMetadataFilesFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedMetadataFilesFixture.cs index 78a0515f8..6a0cb4db2 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedMetadataFilesFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedMetadataFilesFixture.cs @@ -5,9 +5,9 @@ using NzbDrone.Core.Extras.Metadata; using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.Housekeeping.Housekeepers; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Music; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedPendingReleasesFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedPendingReleasesFixture.cs index c0d7aea4d..bf4ff402b 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedPendingReleasesFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedPendingReleasesFixture.cs @@ -3,9 +3,9 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Download.Pending; using NzbDrone.Core.Housekeeping.Housekeepers; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedTrackFilesFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedTrackFilesFixture.cs index fa3fbcae9..021975573 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedTrackFilesFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedTrackFilesFixture.cs @@ -4,9 +4,9 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Housekeeping.Housekeepers; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { @@ -45,7 +45,7 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers Subject.Clean(); AllStoredModels.Where(x => x.AlbumId == 1).Should().HaveCount(1); - + Db.All().Should().Contain(e => e.TrackFileId == AllStoredModels.First().Id); } } diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedTracksFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedTracksFixture.cs index 7c46f932b..c40e757ab 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedTracksFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedTracksFixture.cs @@ -2,8 +2,8 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Housekeeping.Housekeepers; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; +using NzbDrone.Core.Test.Framework; 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 70f3582e6..cb2297989 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupUnusedTagsFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupUnusedTagsFixture.cs @@ -2,9 +2,9 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Housekeeping.Housekeepers; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Tags; using NzbDrone.Core.Profiles.Releases; +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 cc563e065..56ddfba3e 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureDownloadClientStatusTimesFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureDownloadClientStatusTimesFixture.cs @@ -35,9 +35,7 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers 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 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers 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 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers 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 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers 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/FixFutureImportListStatusTimesFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureImportListStatusTimesFixture.cs index 77197ad34..777d55bfe 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureImportListStatusTimesFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureImportListStatusTimesFixture.cs @@ -35,9 +35,7 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers 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 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers 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 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers 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 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers 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 fe7b61cc6..30d0148d7 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureIndexerStatusTimesFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureIndexerStatusTimesFixture.cs @@ -35,9 +35,7 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers 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 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers 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 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers 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 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers 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/UpdateCleanTitleForArtistFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/UpdateCleanTitleForArtistFixture.cs index a7cf09a07..1ef06450c 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/UpdateCleanTitleForArtistFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/UpdateCleanTitleForArtistFixture.cs @@ -1,10 +1,9 @@ using FizzWare.NBuilder; -using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Core.Housekeeping.Housekeepers; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { diff --git a/src/NzbDrone.Core.Test/Http/HttpProxySettingsProviderFixture.cs b/src/NzbDrone.Core.Test/Http/HttpProxySettingsProviderFixture.cs index 2e7759397..067149904 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 6273c7ef8..f92d8728a 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/ImportListTests/ImportListServiceFixture.cs b/src/NzbDrone.Core.Test/ImportListTests/ImportListServiceFixture.cs index 086821da0..0be3a49cd 100644 --- a/src/NzbDrone.Core.Test/ImportListTests/ImportListServiceFixture.cs +++ b/src/NzbDrone.Core.Test/ImportListTests/ImportListServiceFixture.cs @@ -31,7 +31,7 @@ namespace NzbDrone.Core.Test.ImportListTests Mocker.SetConstant(repo); var existingImportLists = Builder.CreateNew().BuildNew(); - existingImportLists.ConfigContract = typeof (LidarrListsSettings).Name; + existingImportLists.ConfigContract = typeof(LidarrListsSettings).Name; repo.Insert(existingImportLists); diff --git a/src/NzbDrone.Core.Test/ImportListTests/ImportListSyncServiceFixture.cs b/src/NzbDrone.Core.Test/ImportListTests/ImportListSyncServiceFixture.cs index 9baafa8dc..c0c486aa4 100644 --- a/src/NzbDrone.Core.Test/ImportListTests/ImportListSyncServiceFixture.cs +++ b/src/NzbDrone.Core.Test/ImportListTests/ImportListSyncServiceFixture.cs @@ -1,13 +1,13 @@ -using System.Linq; using System.Collections.Generic; +using System.Linq; using Moq; using NUnit.Framework; using NzbDrone.Core.ImportLists; +using NzbDrone.Core.ImportLists.Exclusions; using NzbDrone.Core.MetadataSource; using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.ImportLists.Exclusions; namespace NzbDrone.Core.Test.ImportListTests { @@ -23,7 +23,7 @@ namespace NzbDrone.Core.Test.ImportListTests Artist = "Linkin Park" }; - _importListReports = new List{importListItem1}; + _importListReports = new List { importListItem1 }; Mocker.GetMock() .Setup(v => v.Fetch()) @@ -39,7 +39,7 @@ namespace NzbDrone.Core.Test.ImportListTests Mocker.GetMock() .Setup(v => v.Get(It.IsAny())) - .Returns(new ImportListDefinition{ ShouldMonitor = ImportListMonitorType.SpecificAlbum }); + .Returns(new ImportListDefinition { ShouldMonitor = ImportListMonitorType.SpecificAlbum }); Mocker.GetMock() .Setup(v => v.Fetch()) @@ -69,22 +69,24 @@ namespace NzbDrone.Core.Test.ImportListTests { Mocker.GetMock() .Setup(v => v.FindById(_importListReports.First().ArtistMusicBrainzId)) - .Returns(new Artist{ForeignArtistId = _importListReports.First().ArtistMusicBrainzId }); + .Returns(new Artist { ForeignArtistId = _importListReports.First().ArtistMusicBrainzId }); } private void WithExistingAlbum() { Mocker.GetMock() .Setup(v => v.FindById(_importListReports.First().AlbumMusicBrainzId)) - .Returns(new Album{ForeignAlbumId = _importListReports.First().AlbumMusicBrainzId }); + .Returns(new Album { ForeignAlbumId = _importListReports.First().AlbumMusicBrainzId }); } private void WithExcludedArtist() { Mocker.GetMock() .Setup(v => v.All()) - .Returns(new List { - new ImportListExclusion { + .Returns(new List + { + new ImportListExclusion + { ForeignId = "f59c5520-5f46-4d2c-b2c4-822eabf53419" } }); @@ -94,8 +96,10 @@ namespace NzbDrone.Core.Test.ImportListTests { Mocker.GetMock() .Setup(v => v.All()) - .Returns(new List { - new ImportListExclusion { + .Returns(new List + { + new ImportListExclusion + { ForeignId = "09474d62-17dd-3a4f-98fb-04c65f38a479" } }); @@ -105,7 +109,7 @@ namespace NzbDrone.Core.Test.ImportListTests { Mocker.GetMock() .Setup(v => v.Get(It.IsAny())) - .Returns(new ImportListDefinition{ ShouldMonitor = monitor }); + .Returns(new ImportListDefinition { ShouldMonitor = monitor }); } [Test] @@ -172,7 +176,7 @@ namespace NzbDrone.Core.Test.ImportListTests Subject.Execute(new ImportListSyncCommand()); Mocker.GetMock() - .Verify(v => v.AddArtists(It.Is>(t=>t.Count == 0))); + .Verify(v => v.AddArtists(It.Is>(t => t.Count == 0))); } [Test] @@ -184,7 +188,7 @@ namespace NzbDrone.Core.Test.ImportListTests Subject.Execute(new ImportListSyncCommand()); Mocker.GetMock() - .Verify(v => v.AddArtists(It.Is>(t=>t.Count == 0))); + .Verify(v => v.AddArtists(It.Is>(t => t.Count == 0))); } [Test] @@ -196,10 +200,9 @@ namespace NzbDrone.Core.Test.ImportListTests Subject.Execute(new ImportListSyncCommand()); Mocker.GetMock() - .Verify(v => v.AddAlbums(It.Is>(t=>t.Count == 1))); + .Verify(v => v.AddAlbums(It.Is>(t => t.Count == 1))); } - [TestCase(ImportListMonitorType.None, false)] [TestCase(ImportListMonitorType.SpecificAlbum, true)] [TestCase(ImportListMonitorType.EntireArtist, true)] diff --git a/src/NzbDrone.Core.Test/ImportListTests/Spotify/SpotifyFollowedArtistsFixture.cs b/src/NzbDrone.Core.Test/ImportListTests/Spotify/SpotifyFollowedArtistsFixture.cs index 9c3627761..d293b4ec4 100644 --- a/src/NzbDrone.Core.Test/ImportListTests/Spotify/SpotifyFollowedArtistsFixture.cs +++ b/src/NzbDrone.Core.Test/ImportListTests/Spotify/SpotifyFollowedArtistsFixture.cs @@ -13,7 +13,7 @@ namespace NzbDrone.Core.Test.ImportListTests public class SpotifyFollowedArtistsFixture : CoreTest { // placeholder, we don't use real API - private readonly SpotifyWebAPI api = null; + private readonly SpotifyWebAPI _api = null; [Test] public void should_not_throw_if_followed_is_null() @@ -23,7 +23,7 @@ namespace NzbDrone.Core.Test.ImportListTests It.IsAny())) .Returns(default(FollowedArtists)); - var result = Subject.Fetch(api); + var result = Subject.Fetch(_api); result.Should().BeEmpty(); } @@ -31,7 +31,8 @@ namespace NzbDrone.Core.Test.ImportListTests [Test] public void should_not_throw_if_followed_artists_is_null() { - var followed = new FollowedArtists { + var followed = new FollowedArtists + { Artists = null }; @@ -40,7 +41,7 @@ namespace NzbDrone.Core.Test.ImportListTests It.IsAny())) .Returns(followed); - var result = Subject.Fetch(api); + var result = Subject.Fetch(_api); result.Should().BeEmpty(); } @@ -48,8 +49,10 @@ namespace NzbDrone.Core.Test.ImportListTests [Test] public void should_not_throw_if_followed_artist_items_is_null() { - var followed = new FollowedArtists { - Artists = new CursorPaging { + var followed = new FollowedArtists + { + Artists = new CursorPaging + { Items = null } }; @@ -59,18 +62,21 @@ namespace NzbDrone.Core.Test.ImportListTests It.IsAny())) .Returns(followed); - var result = Subject.Fetch(api); + var result = Subject.Fetch(_api); result.Should().BeEmpty(); - Subject.Fetch(api); + Subject.Fetch(_api); } [Test] public void should_not_throw_if_artist_is_null() { - var followed = new FollowedArtists { - Artists = new CursorPaging { - Items = new List { + var followed = new FollowedArtists + { + Artists = new CursorPaging + { + Items = new List + { null } } @@ -81,19 +87,23 @@ namespace NzbDrone.Core.Test.ImportListTests It.IsAny())) .Returns(followed); - var result = Subject.Fetch(api); + var result = Subject.Fetch(_api); result.Should().BeEmpty(); - Subject.Fetch(api); + Subject.Fetch(_api); } [Test] public void should_parse_followed_artist() { - var followed = new FollowedArtists { - Artists = new CursorPaging { - Items = new List { - new FullArtist { + var followed = new FollowedArtists + { + Artists = new CursorPaging + { + Items = new List + { + new FullArtist + { Name = "artist" } } @@ -105,7 +115,7 @@ namespace NzbDrone.Core.Test.ImportListTests It.IsAny())) .Returns(followed); - var result = Subject.Fetch(api); + var result = Subject.Fetch(_api); result.Should().HaveCount(1); } @@ -113,10 +123,14 @@ namespace NzbDrone.Core.Test.ImportListTests [Test] public void should_not_throw_if_get_next_page_returns_null() { - var followed = new FollowedArtists { - Artists = new CursorPaging { - Items = new List { - new FullArtist { + var followed = new FollowedArtists + { + Artists = new CursorPaging + { + Items = new List + { + new FullArtist + { Name = "artist" } }, @@ -135,7 +149,7 @@ namespace NzbDrone.Core.Test.ImportListTests It.IsAny())) .Returns(default(FollowedArtists)); - var result = Subject.Fetch(api); + var result = Subject.Fetch(_api); result.Should().HaveCount(1); @@ -150,10 +164,14 @@ namespace NzbDrone.Core.Test.ImportListTests [TestCase("")] public void should_skip_bad_artist_names(string name) { - var followed = new FollowedArtists { - Artists = new CursorPaging { - Items = new List { - new FullArtist { + var followed = new FollowedArtists + { + Artists = new CursorPaging + { + Items = new List + { + new FullArtist + { Name = name } } @@ -165,7 +183,7 @@ namespace NzbDrone.Core.Test.ImportListTests It.IsAny())) .Returns(followed); - var result = Subject.Fetch(api); + var result = Subject.Fetch(_api); result.Should().BeEmpty(); } diff --git a/src/NzbDrone.Core.Test/ImportListTests/Spotify/SpotifyMappingFixture.cs b/src/NzbDrone.Core.Test/ImportListTests/Spotify/SpotifyMappingFixture.cs index 0e4e3ead2..af4ebb1ac 100644 --- a/src/NzbDrone.Core.Test/ImportListTests/Spotify/SpotifyMappingFixture.cs +++ b/src/NzbDrone.Core.Test/ImportListTests/Spotify/SpotifyMappingFixture.cs @@ -16,6 +16,7 @@ using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.ImportListTests { [TestFixture] + // the base import list class is abstract so use the followed artists one public class SpotifyMappingFixture : CoreTest { @@ -146,7 +147,6 @@ namespace NzbDrone.Core.Test.ImportListTests Artist = "Adele" }; - Subject.MapAlbumItem(data); data.Should().NotBeNull(); data.Artist.Should().Be("Adele"); @@ -299,7 +299,6 @@ namespace NzbDrone.Core.Test.ImportListTests .Setup(x => x.Get(It.IsAny())) .Throws(new Exception("Dummy exception")); - var result = Subject.MapSpotifyReleases(data); result.Should().NotBeNull(); ExceptionVerification.ExpectedErrors(2); diff --git a/src/NzbDrone.Core.Test/ImportListTests/Spotify/SpotifyPlaylistFixture.cs b/src/NzbDrone.Core.Test/ImportListTests/Spotify/SpotifyPlaylistFixture.cs index 6b82d43cb..a9f9c5bef 100644 --- a/src/NzbDrone.Core.Test/ImportListTests/Spotify/SpotifyPlaylistFixture.cs +++ b/src/NzbDrone.Core.Test/ImportListTests/Spotify/SpotifyPlaylistFixture.cs @@ -13,7 +13,7 @@ namespace NzbDrone.Core.Test.ImportListTests public class SpotifyPlaylistFixture : CoreTest { // placeholder, we don't use real API - private readonly SpotifyWebAPI api = null; + private readonly SpotifyWebAPI _api = null; [Test] public void should_not_throw_if_playlist_tracks_is_null() @@ -25,7 +25,7 @@ namespace NzbDrone.Core.Test.ImportListTests It.IsAny())) .Returns(default(Paging)); - var result = Subject.Fetch(api, "playlistid"); + var result = Subject.Fetch(_api, "playlistid"); result.Should().BeEmpty(); } @@ -33,7 +33,8 @@ namespace NzbDrone.Core.Test.ImportListTests [Test] public void should_not_throw_if_playlist_tracks_items_is_null() { - var playlistTracks = new Paging { + var playlistTracks = new Paging + { Items = null }; @@ -44,7 +45,7 @@ namespace NzbDrone.Core.Test.ImportListTests It.IsAny())) .Returns(playlistTracks); - var result = Subject.Fetch(api, "playlistid"); + var result = Subject.Fetch(_api, "playlistid"); result.Should().BeEmpty(); } @@ -52,8 +53,10 @@ namespace NzbDrone.Core.Test.ImportListTests [Test] public void should_not_throw_if_playlist_track_is_null() { - var playlistTracks = new Paging { - Items = new List { + var playlistTracks = new Paging + { + Items = new List + { null } }; @@ -65,7 +68,7 @@ namespace NzbDrone.Core.Test.ImportListTests It.IsAny())) .Returns(playlistTracks); - var result = Subject.Fetch(api, "playlistid"); + var result = Subject.Fetch(_api, "playlistid"); result.Should().BeEmpty(); } @@ -73,20 +76,29 @@ namespace NzbDrone.Core.Test.ImportListTests [Test] public void should_use_album_artist_when_it_exists() { - var playlistTracks = new Paging { - Items = new List { - new PlaylistTrack { - Track = new FullTrack { - Album = new SimpleAlbum { + var playlistTracks = new Paging + { + Items = new List + { + new PlaylistTrack + { + Track = new FullTrack + { + Album = new SimpleAlbum + { Name = "Album", - Artists = new List { - new SimpleArtist { + Artists = new List + { + new SimpleArtist + { Name = "AlbumArtist" } } }, - Artists = new List { - new SimpleArtist { + Artists = new List + { + new SimpleArtist + { Name = "TrackArtist" } } @@ -102,7 +114,7 @@ namespace NzbDrone.Core.Test.ImportListTests It.IsAny())) .Returns(playlistTracks); - var result = Subject.Fetch(api, "playlistid"); + var result = Subject.Fetch(_api, "playlistid"); result.Should().HaveCount(1); result[0].Artist.Should().Be("AlbumArtist"); @@ -111,20 +123,29 @@ namespace NzbDrone.Core.Test.ImportListTests [Test] public void should_fall_back_to_track_artist_if_album_artist_missing() { - var playlistTracks = new Paging { - Items = new List { - new PlaylistTrack { - Track = new FullTrack { - Album = new SimpleAlbum { + var playlistTracks = new Paging + { + Items = new List + { + new PlaylistTrack + { + Track = new FullTrack + { + Album = new SimpleAlbum + { Name = "Album", - Artists = new List { - new SimpleArtist { + Artists = new List + { + new SimpleArtist + { Name = null } } }, - Artists = new List { - new SimpleArtist { + Artists = new List + { + new SimpleArtist + { Name = "TrackArtist" } } @@ -140,32 +161,40 @@ namespace NzbDrone.Core.Test.ImportListTests It.IsAny())) .Returns(playlistTracks); - var result = Subject.Fetch(api, "playlistid"); + var result = Subject.Fetch(_api, "playlistid"); result.Should().HaveCount(1); result[0].Artist.Should().Be("TrackArtist"); } - [TestCase(null, null, "Album")] [TestCase("AlbumArtist", null, null)] [TestCase(null, "TrackArtist", null)] public void should_skip_bad_artist_or_album_names(string albumArtistName, string trackArtistName, string albumName) { - var playlistTracks = new Paging { - Items = new List { - new PlaylistTrack { - Track = new FullTrack { - Album = new SimpleAlbum { + var playlistTracks = new Paging + { + Items = new List + { + new PlaylistTrack + { + Track = new FullTrack + { + Album = new SimpleAlbum + { Name = albumName, - Artists = new List { - new SimpleArtist { + Artists = new List + { + new SimpleArtist + { Name = albumArtistName } } }, - Artists = new List { - new SimpleArtist { + Artists = new List + { + new SimpleArtist + { Name = trackArtistName } } @@ -181,7 +210,7 @@ namespace NzbDrone.Core.Test.ImportListTests It.IsAny())) .Returns(playlistTracks); - var result = Subject.Fetch(api, "playlistid"); + var result = Subject.Fetch(_api, "playlistid"); result.Should().BeEmpty(); } @@ -189,20 +218,29 @@ namespace NzbDrone.Core.Test.ImportListTests [Test] public void should_not_throw_if_get_next_page_returns_null() { - var playlistTracks = new Paging { - Items = new List { - new PlaylistTrack { - Track = new FullTrack { - Album = new SimpleAlbum { + var playlistTracks = new Paging + { + Items = new List + { + new PlaylistTrack + { + Track = new FullTrack + { + Album = new SimpleAlbum + { Name = "Album", - Artists = new List { - new SimpleArtist { + Artists = new List + { + new SimpleArtist + { Name = null } } }, - Artists = new List { - new SimpleArtist { + Artists = new List + { + new SimpleArtist + { Name = "TrackArtist" } } @@ -225,7 +263,7 @@ namespace NzbDrone.Core.Test.ImportListTests It.IsAny>())) .Returns(default(Paging)); - var result = Subject.Fetch(api, "playlistid"); + var result = Subject.Fetch(_api, "playlistid"); result.Should().HaveCount(1); diff --git a/src/NzbDrone.Core.Test/ImportListTests/Spotify/SpotifySavedAlbumsFixture.cs b/src/NzbDrone.Core.Test/ImportListTests/Spotify/SpotifySavedAlbumsFixture.cs index 1444b08bf..4f1371f5d 100644 --- a/src/NzbDrone.Core.Test/ImportListTests/Spotify/SpotifySavedAlbumsFixture.cs +++ b/src/NzbDrone.Core.Test/ImportListTests/Spotify/SpotifySavedAlbumsFixture.cs @@ -13,7 +13,7 @@ namespace NzbDrone.Core.Test.ImportListTests public class SpotifySavedAlbumsFixture : CoreTest { // placeholder, we don't use real API - private readonly SpotifyWebAPI api = null; + private readonly SpotifyWebAPI _api = null; [Test] public void should_not_throw_if_saved_albums_is_null() @@ -23,7 +23,7 @@ namespace NzbDrone.Core.Test.ImportListTests It.IsAny())) .Returns(default(Paging)); - var result = Subject.Fetch(api); + var result = Subject.Fetch(_api); result.Should().BeEmpty(); } @@ -31,7 +31,8 @@ namespace NzbDrone.Core.Test.ImportListTests [Test] public void should_not_throw_if_saved_album_items_is_null() { - var savedAlbums = new Paging { + var savedAlbums = new Paging + { Items = null }; @@ -40,7 +41,7 @@ namespace NzbDrone.Core.Test.ImportListTests It.IsAny())) .Returns(savedAlbums); - var result = Subject.Fetch(api); + var result = Subject.Fetch(_api); result.Should().BeEmpty(); } @@ -48,8 +49,10 @@ namespace NzbDrone.Core.Test.ImportListTests [Test] public void should_not_throw_if_saved_album_is_null() { - var savedAlbums = new Paging { - Items = new List { + var savedAlbums = new Paging + { + Items = new List + { null } }; @@ -59,7 +62,7 @@ namespace NzbDrone.Core.Test.ImportListTests It.IsAny())) .Returns(savedAlbums); - var result = Subject.Fetch(api); + var result = Subject.Fetch(_api); result.Should().BeEmpty(); } @@ -67,13 +70,19 @@ namespace NzbDrone.Core.Test.ImportListTests [TestCase("Artist", "Album")] public void should_parse_saved_album(string artistName, string albumName) { - var savedAlbums = new Paging { - Items = new List { - new SavedAlbum { - Album = new FullAlbum { + var savedAlbums = new Paging + { + Items = new List + { + new SavedAlbum + { + Album = new FullAlbum + { Name = albumName, - Artists = new List { - new SimpleArtist { + Artists = new List + { + new SimpleArtist + { Name = artistName } } @@ -87,7 +96,7 @@ namespace NzbDrone.Core.Test.ImportListTests It.IsAny())) .Returns(savedAlbums); - var result = Subject.Fetch(api); + var result = Subject.Fetch(_api); result.Should().HaveCount(1); } @@ -95,13 +104,19 @@ namespace NzbDrone.Core.Test.ImportListTests [Test] public void should_not_throw_if_get_next_page_returns_null() { - var savedAlbums = new Paging { - Items = new List { - new SavedAlbum { - Album = new FullAlbum { + var savedAlbums = new Paging + { + Items = new List + { + new SavedAlbum + { + Album = new FullAlbum + { Name = "Album", - Artists = new List { - new SimpleArtist { + Artists = new List + { + new SimpleArtist + { Name = "Artist" } } @@ -122,7 +137,7 @@ namespace NzbDrone.Core.Test.ImportListTests It.IsAny>())) .Returns(default(Paging)); - var result = Subject.Fetch(api); + var result = Subject.Fetch(_api); result.Should().HaveCount(1); @@ -138,13 +153,19 @@ namespace NzbDrone.Core.Test.ImportListTests [TestCase(null, null)] public void should_skip_bad_artist_or_album_names(string artistName, string albumName) { - var savedAlbums = new Paging { - Items = new List { - new SavedAlbum { - Album = new FullAlbum { + var savedAlbums = new Paging + { + Items = new List + { + new SavedAlbum + { + Album = new FullAlbum + { Name = albumName, - Artists = new List { - new SimpleArtist { + Artists = new List + { + new SimpleArtist + { Name = artistName } } @@ -158,7 +179,7 @@ namespace NzbDrone.Core.Test.ImportListTests It.IsAny())) .Returns(savedAlbums); - var result = Subject.Fetch(api); + var result = Subject.Fetch(_api); result.Should().BeEmpty(); } diff --git a/src/NzbDrone.Core.Test/IndexerSearchTests/ArtistSearchServiceFixture.cs b/src/NzbDrone.Core.Test/IndexerSearchTests/ArtistSearchServiceFixture.cs index 422ad17e3..bcad5015a 100644 --- a/src/NzbDrone.Core.Test/IndexerSearchTests/ArtistSearchServiceFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerSearchTests/ArtistSearchServiceFixture.cs @@ -1,14 +1,13 @@ using System.Collections.Generic; using System.Linq; -using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; using NzbDrone.Core.IndexerSearch; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Music; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.IndexerSearchTests { @@ -32,8 +31,7 @@ namespace NzbDrone.Core.Test.IndexerSearchTests Mocker.GetMock() .Setup(s => s.ProcessDecisions(It.IsAny>())) - .Returns(new ProcessedDecisions(new List(), new List(), - new List())); + .Returns(new ProcessedDecisions(new List(), new List(), new List())); } [Test] @@ -41,11 +39,11 @@ namespace NzbDrone.Core.Test.IndexerSearchTests { _artist.Albums = new List { - new Album {Monitored = false}, - new Album {Monitored = true} + new Album { Monitored = false }, + new Album { Monitored = true } }; - Subject.Execute(new ArtistSearchCommand {ArtistId = _artist.Id, Trigger = CommandTrigger.Manual}); + Subject.Execute(new ArtistSearchCommand { ArtistId = _artist.Id, Trigger = CommandTrigger.Manual }); Mocker.GetMock() .Verify(v => v.ArtistSearch(_artist.Id, false, true, false), diff --git a/src/NzbDrone.Core.Test/IndexerSearchTests/SearchDefinitionFixture.cs b/src/NzbDrone.Core.Test/IndexerSearchTests/SearchDefinitionFixture.cs index d2b04848f..a0a921ce8 100644 --- a/src/NzbDrone.Core.Test/IndexerSearchTests/SearchDefinitionFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerSearchTests/SearchDefinitionFixture.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; -using System.Linq; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.IndexerSearch.Definitions; @@ -7,7 +5,7 @@ using NzbDrone.Core.Music; using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.IndexerSearchTests -{ +{ public class AlbumSearchDefinitionFixture : CoreTest { [TestCase("Mötley Crüe", "Motley+Crue")] @@ -29,7 +27,7 @@ namespace NzbDrone.Core.Test.IndexerSearchTests Subject.AlbumTitle = album; Subject.AlbumQuery.Should().Be(expected); } - + [TestCase("+", "+")] public void should_not_replace_some_special_characters_if_result_empty_string(string album, string expected) { diff --git a/src/NzbDrone.Core.Test/IndexerTests/GazelleTests/GazelleFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/GazelleTests/GazelleFixture.cs index 7e8c11e90..eece75042 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/GazelleTests/GazelleFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/GazelleTests/GazelleFixture.cs @@ -36,7 +36,7 @@ namespace NzbDrone.Core.Test.IndexerTests.GazelleTests Mocker.GetMock() .Setup(o => o.Execute(It.Is(v => v.Method == HttpMethod.GET && v.Url.FullUri.Contains("ajax.php?action=browse")))) - .Returns(r => new HttpResponse(r, new HttpHeader{ContentType = "application/json" }, recentFeed)); + .Returns(r => new HttpResponse(r, new HttpHeader { ContentType = "application/json" }, recentFeed)); Mocker.GetMock() .Setup(o => o.Execute(It.Is(v => v.Method == HttpMethod.POST && v.Url.FullUri.Contains("ajax.php?action=index")))) diff --git a/src/NzbDrone.Core.Test/IndexerTests/HeadphonesTests/HeadphonesFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/HeadphonesTests/HeadphonesFixture.cs index f1b30ad42..88678f923 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/HeadphonesTests/HeadphonesFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/HeadphonesTests/HeadphonesFixture.cs @@ -20,15 +20,15 @@ namespace NzbDrone.Core.Test.IndexerTests.HeadphonesTests public void Setup() { Subject.Definition = new IndexerDefinition() + { + Name = "Headphones VIP", + Settings = new HeadphonesSettings() { - Name = "Headphones VIP", - Settings = new HeadphonesSettings() - { - Categories = new int[] { 3000 }, - Username = "user", - Password = "pass" - } - }; + Categories = new int[] { 3000 }, + Username = "user", + Password = "pass" + } + }; _caps = new HeadphonesCapabilities(); Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/IndexerTests/IPTorrentsTests/IPTorrentsFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/IPTorrentsTests/IPTorrentsFixture.cs index 08204e6a7..cabc82040 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; 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 @@ namespace NzbDrone.Core.Test.IndexerTests.IPTorrentsTests 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 @@ namespace NzbDrone.Core.Test.IndexerTests.IPTorrentsTests 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 @@ namespace NzbDrone.Core.Test.IndexerTests.IPTorrentsTests 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 @@ namespace NzbDrone.Core.Test.IndexerTests.IPTorrentsTests 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 7d4509d8f..4cc12f77b 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/IndexerServiceFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/IndexerServiceFixture.cs @@ -33,7 +33,7 @@ namespace NzbDrone.Core.Test.IndexerTests 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 9504a4d99..a8cf68024 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/IntegrationTests/IndexerIntegrationTests.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/IntegrationTests/IndexerIntegrationTests.cs @@ -4,11 +4,9 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Common.Extensions; using NzbDrone.Core.Indexers; -using NzbDrone.Core.Indexers.Nyaa; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.ThingiProvider; using NzbDrone.Test.Common.Categories; namespace NzbDrone.Core.Test.IndexerTests.IntegrationTests @@ -24,8 +22,8 @@ namespace NzbDrone.Core.Test.IndexerTests.IntegrationTests UseRealHttp(); _albumSearchCriteria = new AlbumSearchCriteria() - { - }; + { + }; } private void ValidateTorrentResult(IList reports, bool hasSize = false, bool hasInfoUrl = false, bool hasMagnet = false) @@ -60,6 +58,5 @@ namespace NzbDrone.Core.Test.IndexerTests.IntegrationTests 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 0c79b67d2..3d244f5fe 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabFixture.cs @@ -21,15 +21,15 @@ namespace NzbDrone.Core.Test.IndexerTests.NewznabTests 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() @@ -45,7 +45,7 @@ namespace NzbDrone.Core.Test.IndexerTests.NewznabTests Mocker.GetMock() .Setup(o => o.Execute(It.Is(v => v.Method == HttpMethod.GET))) .Returns(r => new HttpResponse(r, new HttpHeader(), recentFeed)); - + var releases = Subject.FetchRecent(); releases.Should().HaveCount(100); @@ -93,5 +93,5 @@ namespace NzbDrone.Core.Test.IndexerTests.NewznabTests ExceptionVerification.ExpectedWarns(1); } -} + } } diff --git a/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabRequestGeneratorFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabRequestGeneratorFixture.cs index ddbd94bd2..39bd839a0 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabRequestGeneratorFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabRequestGeneratorFixture.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using System.Linq; using FluentAssertions; using Moq; @@ -19,16 +18,15 @@ namespace NzbDrone.Core.Test.IndexerTests.NewznabTests { Subject.Settings = new NewznabSettings() { - BaseUrl = "http://127.0.0.1:1234/", - Categories = new [] { 1, 2 }, - ApiKey = "abcd", + BaseUrl = "http://127.0.0.1:1234/", + Categories = new[] { 1, 2 }, + ApiKey = "abcd", }; _singleAlbumSearchCriteria = new AlbumSearchCriteria { Artist = new Music.Artist { Name = "Alien Ant Farm" }, AlbumTitle = "TruANT" - }; _capabilities = new NewznabCapabilities(); @@ -53,7 +51,7 @@ namespace NzbDrone.Core.Test.IndexerTests.NewznabTests [Test] public void should_search_by_artist_and_album_if_supported() { - _capabilities.SupportedAudioSearchParameters = new[] { "q", "artist", "album"}; + _capabilities.SupportedAudioSearchParameters = new[] { "q", "artist", "album" }; var results = Subject.GetSearchRequests(_singleAlbumSearchCriteria); results.GetTier(0).Should().HaveCount(1); diff --git a/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabSettingFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabSettingFixture.cs index bb5bc782c..33eee6e54 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 @@ namespace NzbDrone.Core.Test.IndexerTests.NewznabTests BaseUrl = url }; - setting.Validate().IsValid.Should().BeFalse(); setting.Validate().Errors.Should().Contain(c => c.PropertyName == "ApiKey"); - } [TestCase("")] @@ -35,14 +32,11 @@ namespace NzbDrone.Core.Test.IndexerTests.NewznabTests 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 @@ namespace NzbDrone.Core.Test.IndexerTests.NewznabTests 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 3ceb43a55..f04f8a571 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/NyaaTests/NyaaFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/NyaaTests/NyaaFixture.cs @@ -18,10 +18,10 @@ namespace NzbDrone.Core.Test.IndexerTests.NyaaTests public void Setup() { Subject.Definition = new IndexerDefinition() - { - Name = "Nyaa", - Settings = new NyaaSettings() - }; + { + Name = "Nyaa", + Settings = new NyaaSettings() + }; } [Test] @@ -50,7 +50,7 @@ namespace NzbDrone.Core.Test.IndexerTests.NyaaTests 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 c5542b943..1b19fd7f1 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/OmgwtfnzbsTests/OmgwtfnzbsFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/OmgwtfnzbsTests/OmgwtfnzbsFixture.cs @@ -17,14 +17,14 @@ namespace NzbDrone.Core.Test.IndexerTests.OmgwtfnzbsTests 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] @@ -35,7 +35,7 @@ namespace NzbDrone.Core.Test.IndexerTests.OmgwtfnzbsTests Mocker.GetMock() .Setup(o => o.Execute(It.Is(v => v.Method == HttpMethod.GET))) .Returns(r => new HttpResponse(r, new HttpHeader(), recentFeed)); - + var releases = Subject.FetchRecent(); releases.Should().HaveCount(100); diff --git a/src/NzbDrone.Core.Test/IndexerTests/RarbgTests/RarbgFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/RarbgTests/RarbgFixture.cs index 3b23dfc82..c640c07e3 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/RarbgTests/RarbgFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/RarbgTests/RarbgFixture.cs @@ -19,10 +19,10 @@ namespace NzbDrone.Core.Test.IndexerTests.RarbgTests 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 a4c3a05d4..2b73b3b73 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TestIndexer.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TestIndexer.cs @@ -18,7 +18,6 @@ namespace NzbDrone.Core.Test.IndexerTests 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/TestIndexerSettings.cs b/src/NzbDrone.Core.Test/IndexerTests/TestIndexerSettings.cs index 7fcefb7de..fe99e8d1e 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TestIndexerSettings.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TestIndexerSettings.cs @@ -1,6 +1,5 @@ using System; using NzbDrone.Core.Indexers; -using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; namespace NzbDrone.Core.Test.IndexerTests diff --git a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TestTorrentRssIndexer.cs b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TestTorrentRssIndexer.cs index ce7ec77b5..110db4ec2 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 @@ namespace NzbDrone.Core.Test.IndexerTests.TorrentRssIndexerTests 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; } @@ -31,13 +31,13 @@ namespace NzbDrone.Core.Test.IndexerTests.TorrentRssIndexerTests /// private void SetupNLog() { - // Step 1. Create configuration object + // Step 1. Create configuration object var config = new LoggingConfiguration(); var fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); - // Step 3. Set target properties + // Step 3. Set target properties fileTarget.FileName = "${basedir}/log.txt"; fileTarget.Layout = GetStandardLayout(); diff --git a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssIndexerFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssIndexerFixture.cs index 169d40888..506e8ad18 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssIndexerFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssIndexerFixture.cs @@ -5,7 +5,6 @@ using Moq; using NUnit.Framework; using NzbDrone.Common.Http; using NzbDrone.Core.Indexers; -using NzbDrone.Core.Indexers.Exceptions; using NzbDrone.Core.Indexers.TorrentRss; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; @@ -13,7 +12,6 @@ using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.IndexerTests.TorrentRssIndexerTests { - [TestFixture] public class TorrentRssIndexerFixture : CoreTest { @@ -220,7 +218,7 @@ namespace NzbDrone.Core.Test.IndexerTests.TorrentRssIndexerTests 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(); @@ -288,7 +286,7 @@ namespace NzbDrone.Core.Test.IndexerTests.TorrentRssIndexerTests torrentInfo.Seeders.Should().NotHaveValue(); } - [Test] + [Test] public void should_record_indexer_failure_if_unsupported_feed() { GivenRecentFeedResponse("TorrentRss/invalid/TorrentDay_NoPubDate.xml"); diff --git a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssParserFactoryFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssParserFactoryFixture.cs index 0ed86b3c1..e506c2978 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 a25cae5f7..a0fa004eb 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssSettingsDetectorFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssSettingsDetectorFixture.cs @@ -5,7 +5,6 @@ using NzbDrone.Common.Http; using NzbDrone.Core.Indexers.Exceptions; using NzbDrone.Core.Indexers.TorrentRss; using NzbDrone.Core.Test.Framework; -using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.IndexerTests.TorrentRssIndexerTests { @@ -38,14 +37,14 @@ namespace NzbDrone.Core.Test.IndexerTests.TorrentRssIndexerTests 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/TorrentleechTests/TorrentleechFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/TorrentleechTests/TorrentleechFixture.cs index 8ecb58144..691abd0a4 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TorrentleechTests/TorrentleechFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TorrentleechTests/TorrentleechFixture.cs @@ -1,13 +1,13 @@ -using Moq; +using System; +using System.Linq; +using FluentAssertions; +using Moq; using NUnit.Framework; using NzbDrone.Common.Http; using NzbDrone.Core.Indexers; using NzbDrone.Core.Indexers.Torrentleech; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using System; -using System.Linq; -using FluentAssertions; namespace NzbDrone.Core.Test.IndexerTests.TorrentleechTests { @@ -18,10 +18,10 @@ namespace NzbDrone.Core.Test.IndexerTests.TorrentleechTests public void Setup() { Subject.Definition = new IndexerDefinition() - { - Name = "Torrentleech", - Settings = new TorrentleechSettings() - }; + { + Name = "Torrentleech", + Settings = new TorrentleechSettings() + }; } [Test] @@ -50,7 +50,7 @@ namespace NzbDrone.Core.Test.IndexerTests.TorrentleechTests torrentInfo.Size.Should().Be(0); torrentInfo.InfoHash.Should().Be(null); torrentInfo.MagnetUrl.Should().Be(null); - torrentInfo.Peers.Should().Be(7+1); + torrentInfo.Peers.Should().Be(7 + 1); torrentInfo.Seeders.Should().Be(1); } } diff --git a/src/NzbDrone.Core.Test/IndexerTests/TorznabTests/TorznabFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/TorznabTests/TorznabFixture.cs index 4c22d22bb..93ab571d0 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TorznabTests/TorznabFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TorznabTests/TorznabFixture.cs @@ -21,14 +21,14 @@ namespace NzbDrone.Core.Test.IndexerTests.TorznabTests 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/IndexerTests/WafflesTests/WafflesFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/WafflesTests/WafflesFixture.cs index c606a632c..eb313b1ef 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/WafflesTests/WafflesFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/WafflesTests/WafflesFixture.cs @@ -17,14 +17,14 @@ namespace NzbDrone.Core.Test.IndexerTests.WafflesTests public void Setup() { Subject.Definition = new IndexerDefinition() + { + Name = "Waffles", + Settings = new WafflesSettings() { - Name = "Waffles", - Settings = new WafflesSettings() - { - UserId = "xxx", - RssPasskey = "123456789" - } - }; + UserId = "xxx", + RssPasskey = "123456789" + } + }; } [Test] @@ -35,7 +35,7 @@ namespace NzbDrone.Core.Test.IndexerTests.WafflesTests Mocker.GetMock() .Setup(o => o.Execute(It.Is(v => v.Method == HttpMethod.GET))) .Returns(r => new HttpResponse(r, new HttpHeader(), recentFeed)); - + var releases = Subject.FetchRecent(); releases.Should().HaveCount(15); diff --git a/src/NzbDrone.Core.Test/Instrumentation/DatabaseTargetFixture.cs b/src/NzbDrone.Core.Test/Instrumentation/DatabaseTargetFixture.cs index c575e3fdd..ba5c84236 100644 --- a/src/NzbDrone.Core.Test/Instrumentation/DatabaseTargetFixture.cs +++ b/src/NzbDrone.Core.Test/Instrumentation/DatabaseTargetFixture.cs @@ -18,7 +18,7 @@ namespace NzbDrone.Core.Test.Instrumentation public class DatabaseTargetFixture : DbTest { private static string _uniqueMessage; - Logger _logger; + private Logger _logger; protected override MigrationType MigrationType => MigrationType.Log; @@ -64,7 +64,6 @@ namespace NzbDrone.Core.Test.Instrumentation VerifyLog(StoredModel, LogLevel.Info); } - [Test] [Explicit] [ManualTest] @@ -126,7 +125,6 @@ namespace NzbDrone.Core.Test.Instrumentation epFile.Path.Should().BeNull(); } - [TearDown] public void Teardown() { @@ -136,7 +134,7 @@ namespace NzbDrone.Core.Test.Instrumentation 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/MediaCoverTests/CoverExistsSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaCoverTests/CoverExistsSpecificationFixture.cs index f66210c91..7fe7185aa 100644 --- a/src/NzbDrone.Core.Test/MediaCoverTests/CoverExistsSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaCoverTests/CoverExistsSpecificationFixture.cs @@ -1,10 +1,10 @@ +using System; using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Core.MediaCover; using NzbDrone.Core.Test.Framework; -using System; namespace NzbDrone.Core.Test.MediaCoverTests { @@ -54,7 +54,6 @@ namespace NzbDrone.Core.Test.MediaCoverTests Subject.AlreadyExists(givenDate, 999, "c:\\file.exe").Should().BeFalse(); } - [Test] public void should_return_true_if_file_exists_and_date_header_is_null_but_has_length_header() { @@ -70,6 +69,5 @@ namespace NzbDrone.Core.Test.MediaCoverTests Subject.AlreadyExists(DateTime.Now, 1000, "c:\\file.exe").Should().BeTrue(); } - } } diff --git a/src/NzbDrone.Core.Test/MediaCoverTests/MediaCoverServiceFixture.cs b/src/NzbDrone.Core.Test/MediaCoverTests/MediaCoverServiceFixture.cs index f05bb6406..38ffd8436 100644 --- a/src/NzbDrone.Core.Test/MediaCoverTests/MediaCoverServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaCoverTests/MediaCoverServiceFixture.cs @@ -9,17 +9,17 @@ using NzbDrone.Common.Disk; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Common.Http; using NzbDrone.Core.MediaCover; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; using NzbDrone.Core.Music.Events; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.MediaCoverTests { [TestFixture] public class MediaCoverServiceFixture : CoreTest { - Artist _artist; - Album _album; + private Artist _artist; + private Album _album; private HttpResponse _httpResponse; [SetUp] @@ -62,7 +62,6 @@ namespace NzbDrone.Core.Test.MediaCoverTests Subject.ConvertToLocalUrls(12, MediaCoverEntity.Artist, covers); - covers.Single().Url.Should().Be("/MediaCover/12/banner" + extension + "?lastWrite=1234"); } @@ -111,7 +110,6 @@ namespace NzbDrone.Core.Test.MediaCoverTests Subject.ConvertToLocalUrls(6, MediaCoverEntity.Album, covers); - covers.Single().Url.Should().Be("/MediaCover/Albums/6/disc" + extension + "?lastWrite=1234"); } @@ -128,10 +126,8 @@ namespace NzbDrone.Core.Test.MediaCoverTests } }; - Subject.ConvertToLocalUrls(12, MediaCoverEntity.Artist, covers); - covers.Single().Url.Should().Be("/MediaCover/12/banner" + extension); } diff --git a/src/NzbDrone.Core.Test/MediaFiles/AudioTagServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/AudioTagServiceFixture.cs index 0e5c85e90..b461298f4 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/AudioTagServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/AudioTagServiceFixture.cs @@ -1,18 +1,18 @@ +using System; +using System.Collections; +using System.Collections.Generic; using System.IO; -using NUnit.Framework; +using System.Linq; +using FizzWare.NBuilder; using FluentAssertions; +using NUnit.Framework; +using NzbDrone.Common.Disk; +using NzbDrone.Common.Extensions; +using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Music; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Configuration; -using FizzWare.NBuilder; -using System; -using System.Collections; -using System.Linq; -using NzbDrone.Common.Extensions; -using System.Collections.Generic; using NzbDrone.Test.Common; -using NzbDrone.Common.Disk; namespace NzbDrone.Core.Test.MediaFiles.AudioTagServiceFixture { @@ -21,11 +21,12 @@ namespace NzbDrone.Core.Test.MediaFiles.AudioTagServiceFixture { public static class TestCaseFactory { - private static readonly string[] MediaFiles = new [] { "nin.mp2", "nin.mp3", "nin.flac", "nin.m4a", "nin.wma", "nin.ape", "nin.opus" }; + private static readonly string[] MediaFiles = new[] { "nin.mp2", "nin.mp3", "nin.flac", "nin.m4a", "nin.wma", "nin.ape", "nin.opus" }; - private static readonly string[] SkipProperties = new [] { "IsValid", "Duration", "Quality", "MediaInfo", "ImageFile" }; - private static readonly Dictionary SkipPropertiesByFile = new Dictionary { - { "nin.mp2", new [] {"OriginalReleaseDate"} } + private static readonly string[] SkipProperties = new[] { "IsValid", "Duration", "Quality", "MediaInfo", "ImageFile" }; + private static readonly Dictionary SkipPropertiesByFile = new Dictionary + { + { "nin.mp2", new[] { "OriginalReleaseDate" } } }; public static IEnumerable TestCases @@ -39,33 +40,34 @@ namespace NzbDrone.Core.Test.MediaFiles.AudioTagServiceFixture { toSkip = toSkip.Union(SkipPropertiesByFile[file]).ToArray(); } + yield return new TestCaseData(file, toSkip).SetName($"{{m}}_{file.Replace("nin.", "")}"); } } } } - private readonly string testdir = Path.Combine(TestContext.CurrentContext.TestDirectory, "Files", "Media"); - private string copiedFile; - private AudioTag testTags; + private readonly string _testdir = Path.Combine(TestContext.CurrentContext.TestDirectory, "Files", "Media"); + private string _copiedFile; + private AudioTag _testTags; private IDiskProvider _diskProvider; - + [SetUp] public void Setup() { _diskProvider = Mocker.Resolve("ActualDiskProvider"); Mocker.SetConstant(_diskProvider); - + Mocker.GetMock() .Setup(x => x.WriteAudioTags) .Returns(WriteAudioTagsType.Sync); - var imageFile = Path.Combine(testdir, "nin.png"); + var imageFile = Path.Combine(_testdir, "nin.png"); var imageSize = _diskProvider.GetFileSize(imageFile); // have to manually set the arrays of string parameters and integers to values > 1 - testTags = Builder.CreateNew() + _testTags = Builder.CreateNew() .With(x => x.Track = 2) .With(x => x.TrackCount = 33) .With(x => x.Disc = 44) @@ -74,9 +76,9 @@ namespace NzbDrone.Core.Test.MediaFiles.AudioTagServiceFixture .With(x => x.Year = 2019) .With(x => x.OriginalReleaseDate = new DateTime(2009, 4, 1)) .With(x => x.OriginalYear = 2009) - .With(x => x.Performers = new [] { "Performer1" }) - .With(x => x.AlbumArtists = new [] { "방탄소년단" }) - .With(x => x.Genres = new [] { "Genre1", "Genre2" }) + .With(x => x.Performers = new[] { "Performer1" }) + .With(x => x.AlbumArtists = new[] { "방탄소년단" }) + .With(x => x.Genres = new[] { "Genre1", "Genre2" }) .With(x => x.ImageFile = imageFile) .With(x => x.ImageSize = imageSize) .Build(); @@ -85,19 +87,19 @@ namespace NzbDrone.Core.Test.MediaFiles.AudioTagServiceFixture [TearDown] public void Cleanup() { - if (File.Exists(copiedFile)) + if (File.Exists(_copiedFile)) { - File.Delete(copiedFile); + File.Delete(_copiedFile); } } private void GivenFileCopy(string filename) { - var original = Path.Combine(testdir, filename); + var original = Path.Combine(_testdir, filename); var tempname = $"temp_{Path.GetRandomFileName()}{Path.GetExtension(filename)}"; - copiedFile = Path.Combine(testdir, tempname); + _copiedFile = Path.Combine(_testdir, tempname); - File.Copy(original, copiedFile); + File.Copy(original, _copiedFile); } private void VerifyDifferent(AudioTag a, AudioTag b, string[] skipProperties) @@ -108,7 +110,7 @@ namespace NzbDrone.Core.Test.MediaFiles.AudioTagServiceFixture { continue; } - + if (property.CanRead) { if (property.PropertyType.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IEquatable<>)) || @@ -120,8 +122,8 @@ namespace NzbDrone.Core.Test.MediaFiles.AudioTagServiceFixture } else if (typeof(IEnumerable).IsAssignableFrom(property.PropertyType)) { - var val1 = (IEnumerable) property.GetValue(a, null); - var val2 = (IEnumerable) property.GetValue(b, null); + var val1 = (IEnumerable)property.GetValue(a, null); + var val2 = (IEnumerable)property.GetValue(b, null); if (val1 != null && val2 != null) { @@ -152,9 +154,9 @@ namespace NzbDrone.Core.Test.MediaFiles.AudioTagServiceFixture } else if (typeof(IEnumerable).IsAssignableFrom(property.PropertyType)) { - var val1 = (IEnumerable) property.GetValue(a, null); - var val2 = (IEnumerable) property.GetValue(b, null); - + var val1 = (IEnumerable)property.GetValue(a, null); + var val2 = (IEnumerable)property.GetValue(b, null); + if (val1 != null || val2 != null) { val1.Should().BeEquivalentTo(val2, $"{property.Name} should be equal"); @@ -164,48 +166,52 @@ namespace NzbDrone.Core.Test.MediaFiles.AudioTagServiceFixture } } - [Test, TestCaseSource(typeof(TestCaseFactory), "TestCases")] + [Test] + [TestCaseSource(typeof(TestCaseFactory), "TestCases")] public void should_read_duration(string filename, string[] ignored) { - var path = Path.Combine(testdir, filename); + var path = Path.Combine(_testdir, filename); var tags = Subject.ReadTags(path); tags.Duration.Should().BeCloseTo(new TimeSpan(0, 0, 1, 25, 130), 100); } - [Test, TestCaseSource(typeof(TestCaseFactory), "TestCases")] + [Test] + [TestCaseSource(typeof(TestCaseFactory), "TestCases")] public void should_read_write_tags(string filename, string[] skipProperties) { GivenFileCopy(filename); - var path = copiedFile; + var path = _copiedFile; var initialtags = Subject.ReadAudioTag(path); - VerifyDifferent(initialtags, testTags, skipProperties); + VerifyDifferent(initialtags, _testTags, skipProperties); - testTags.Write(path); + _testTags.Write(path); var writtentags = Subject.ReadAudioTag(path); - VerifySame(writtentags, testTags, skipProperties); + VerifySame(writtentags, _testTags, skipProperties); } - [Test, TestCaseSource(typeof(TestCaseFactory), "TestCases")] + [Test] + [TestCaseSource(typeof(TestCaseFactory), "TestCases")] public void should_remove_mb_tags(string filename, string[] skipProperties) { GivenFileCopy(filename); - var path = copiedFile; + var path = _copiedFile; - var track = new TrackFile { + var track = new TrackFile + { Path = path }; - testTags.Write(path); + _testTags.Write(path); var withmb = Subject.ReadAudioTag(path); - VerifySame(withmb, testTags, skipProperties); + VerifySame(withmb, _testTags, skipProperties); Subject.RemoveMusicBrainzTags(track); @@ -222,17 +228,19 @@ namespace NzbDrone.Core.Test.MediaFiles.AudioTagServiceFixture tag.MusicBrainzAlbumComment.Should().BeNull(); tag.MusicBrainzReleaseTrackId.Should().BeNull(); } - - [Test, TestCaseSource(typeof(TestCaseFactory), "TestCases")] + + [Test] + [TestCaseSource(typeof(TestCaseFactory), "TestCases")] public void should_read_audiotag_from_file_with_no_tags(string filename, string[] skipProperties) { GivenFileCopy(filename); - var path = copiedFile; + var path = _copiedFile; Subject.RemoveAllTags(path); var tag = Subject.ReadAudioTag(path); - var expected = new AudioTag() { + var expected = new AudioTag() + { Performers = new string[0], AlbumArtists = new string[0], Genres = new string[0] @@ -242,12 +250,13 @@ namespace NzbDrone.Core.Test.MediaFiles.AudioTagServiceFixture tag.Quality.Should().NotBeNull(); tag.MediaInfo.Should().NotBeNull(); } - - [Test, TestCaseSource(typeof(TestCaseFactory), "TestCases")] + + [Test] + [TestCaseSource(typeof(TestCaseFactory), "TestCases")] public void should_read_parsedtrackinfo_from_file_with_no_tags(string filename, string[] skipProperties) { GivenFileCopy(filename); - var path = copiedFile; + var path = _copiedFile; Subject.RemoveAllTags(path); @@ -256,8 +265,9 @@ namespace NzbDrone.Core.Test.MediaFiles.AudioTagServiceFixture tag.Quality.Should().NotBeNull(); tag.MediaInfo.Should().NotBeNull(); } - - [Test, TestCaseSource(typeof(TestCaseFactory), "TestCases")] + + [Test] + [TestCaseSource(typeof(TestCaseFactory), "TestCases")] public void should_set_quality_and_mediainfo_for_corrupt_file(string filename, string[] skipProperties) { // use missing to simulate corrupt @@ -267,44 +277,46 @@ namespace NzbDrone.Core.Test.MediaFiles.AudioTagServiceFixture VerifySame(tag, expected, skipProperties); tag.Quality.Should().NotBeNull(); tag.MediaInfo.Should().NotBeNull(); - + ExceptionVerification.ExpectedErrors(1); } - - [Test, TestCaseSource(typeof(TestCaseFactory), "TestCases")] + + [Test] + [TestCaseSource(typeof(TestCaseFactory), "TestCases")] public void should_read_file_with_only_title_tag(string filename, string[] ignored) { GivenFileCopy(filename); - var path = copiedFile; + var path = _copiedFile; Subject.RemoveAllTags(path); - + var nametag = new AudioTag(); nametag.Title = "test"; nametag.Write(path); var tag = Subject.ReadTags(path); tag.Title.Should().Be("test"); - + tag.Quality.Should().NotBeNull(); tag.MediaInfo.Should().NotBeNull(); } - - [Test, TestCaseSource(typeof(TestCaseFactory), "TestCases")] + + [Test] + [TestCaseSource(typeof(TestCaseFactory), "TestCases")] public void should_remove_date_from_tags_when_not_in_metadata(string filename, string[] ignored) { GivenFileCopy(filename); - var path = copiedFile; - - testTags.Write(path); - - testTags.Date = null; - testTags.OriginalReleaseDate = null; - - testTags.Write(path); - + var path = _copiedFile; + + _testTags.Write(path); + + _testTags.Date = null; + _testTags.OriginalReleaseDate = null; + + _testTags.Write(path); + var onDisk = Subject.ReadAudioTag(path); - + onDisk.Date.HasValue.Should().BeFalse(); onDisk.OriginalReleaseDate.HasValue.Should().BeFalse(); } @@ -314,14 +326,14 @@ namespace NzbDrone.Core.Test.MediaFiles.AudioTagServiceFixture { GivenFileCopy("nin.mp2"); - using(var file = TagLib.File.Create(copiedFile)) + using (var file = TagLib.File.Create(_copiedFile)) { - var id3tag = (TagLib.Id3v2.Tag) file.GetTag(TagLib.TagTypes.Id3v2); + var id3tag = (TagLib.Id3v2.Tag)file.GetTag(TagLib.TagTypes.Id3v2); id3tag.SetTextFrame("TORY", "0"); file.Save(); } - var tag = Subject.ReadAudioTag(copiedFile); + var tag = Subject.ReadAudioTag(_copiedFile); tag.OriginalReleaseDate.HasValue.Should().BeFalse(); } @@ -331,7 +343,7 @@ namespace NzbDrone.Core.Test.MediaFiles.AudioTagServiceFixture var artist = Builder.CreateNew() .With(x => x.Metadata = meta) .Build(); - + var album = Builder.CreateNew() .With(x => x.Artist = artist) .Build(); @@ -345,7 +357,7 @@ namespace NzbDrone.Core.Test.MediaFiles.AudioTagServiceFixture .With(x => x.Country = new List()) .With(x => x.Label = new List()) .Build(); - + var tracks = Builder.CreateListOfSize(10) .All() .With(x => x.AlbumRelease = release) @@ -370,7 +382,7 @@ namespace NzbDrone.Core.Test.MediaFiles.AudioTagServiceFixture { var file = GivenPopulatedTrackfile(0); var tag = Subject.GetTrackMetadata(file); - + tag.MusicBrainzReleaseCountry.Should().BeNull(); } @@ -379,7 +391,6 @@ namespace NzbDrone.Core.Test.MediaFiles.AudioTagServiceFixture { // make sure that we aren't relying on index of items in // Media being the same as the medium number - var file = GivenPopulatedTrackfile(100); var tag = Subject.GetTrackMetadata(file); @@ -397,7 +408,7 @@ namespace NzbDrone.Core.Test.MediaFiles.AudioTagServiceFixture var file = GivenPopulatedTrackfile(0); - file.Path = copiedFile; + file.Path = _copiedFile; Subject.WriteTags(file, false, true); var fileInfo = _diskProvider.GetFileInfo(file.Path); diff --git a/src/NzbDrone.Core.Test/MediaFiles/DiskScanServiceTests/ScanFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/DiskScanServiceTests/ScanFixture.cs index 1ebba5da5..8ecf75845 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/DiskScanServiceTests/ScanFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/DiskScanServiceTests/ScanFixture.cs @@ -1,24 +1,24 @@ +using System; using System.Collections.Generic; using System.IO; using System.IO.Abstractions; +using System.IO.Abstractions.TestingHelpers; using System.Linq; using FizzWare.NBuilder; +using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Core.Configuration; +using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.TrackImport; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; -using NzbDrone.Core.RootFolders; -using NzbDrone.Test.Common; using NzbDrone.Core.Parser.Model; -using FluentAssertions; -using System.IO.Abstractions.TestingHelpers; -using NzbDrone.Core.DecisionEngine; -using System; using NzbDrone.Core.Qualities; +using NzbDrone.Core.RootFolders; +using NzbDrone.Core.Test.Framework; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles.DiskScanServiceTests { @@ -102,10 +102,11 @@ namespace NzbDrone.Core.Test.MediaFiles.DiskScanServiceTests Mocker.GetMock() .Setup(x => x.GetFilesWithBasePath(_artist.Path)) - .Returns(files.Select(x => new TrackFile { - Path = x, - Modified = lastWrite.Value.UtcDateTime - }).ToList()); + .Returns(files.Select(x => new TrackFile + { + Path = x, + Modified = lastWrite.Value.UtcDateTime + }).ToList()); } [Test] @@ -412,12 +413,13 @@ namespace NzbDrone.Core.Test.MediaFiles.DiskScanServiceTests Mocker.GetMock() .Setup(x => x.GetImportDecisions(It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns((List fileList, Artist artist, FilterFilesType filter, bool includeExisting) => - fileList.Select(x => new LocalTrack { - Artist = artist, - Path = x.FullName, - Modified = x.LastWriteTimeUtc, - FileTrackInfo = new ParsedTrackInfo() - }) + fileList.Select(x => new LocalTrack + { + Artist = artist, + Path = x.FullName, + Modified = x.LastWriteTimeUtc, + FileTrackInfo = new ParsedTrackInfo() + }) .Select(x => new ImportDecision(x, new Rejection("Reject"))) .ToList()); } @@ -425,7 +427,8 @@ namespace NzbDrone.Core.Test.MediaFiles.DiskScanServiceTests [Test] public void should_insert_new_unmatched_files_when_all_new() { - var files = new List { + var files = new List + { Path.Combine(_artist.Path, "Season 1", "file1.flac"), Path.Combine(_artist.Path, "Season 1", "s01e01.flac") }; @@ -444,7 +447,8 @@ namespace NzbDrone.Core.Test.MediaFiles.DiskScanServiceTests [Test] public void should_insert_new_unmatched_files_when_some_known() { - var files = new List { + var files = new List + { Path.Combine(_artist.Path, "Season 1", "file1.flac"), Path.Combine(_artist.Path, "Season 1", "s01e01.flac") }; @@ -463,7 +467,8 @@ namespace NzbDrone.Core.Test.MediaFiles.DiskScanServiceTests [Test] public void should_not_insert_files_when_all_known() { - var files = new List { + var files = new List + { Path.Combine(_artist.Path, "Season 1", "file1.flac"), Path.Combine(_artist.Path, "Season 1", "s01e01.flac") }; @@ -486,7 +491,8 @@ namespace NzbDrone.Core.Test.MediaFiles.DiskScanServiceTests [Test] public void should_not_update_info_for_unchanged_known_files() { - var files = new List { + var files = new List + { Path.Combine(_artist.Path, "Season 1", "file1.flac"), Path.Combine(_artist.Path, "Season 1", "s01e01.flac") }; @@ -504,13 +510,13 @@ namespace NzbDrone.Core.Test.MediaFiles.DiskScanServiceTests Mocker.GetMock() .Verify(x => x.Update(It.Is>(l => l.Count > 0)), Times.Never()); - } [Test] public void should_update_info_for_changed_known_files() { - var files = new List { + var files = new List + { Path.Combine(_artist.Path, "Season 1", "file1.flac"), Path.Combine(_artist.Path, "Season 1", "s01e01.flac") }; @@ -529,7 +535,8 @@ namespace NzbDrone.Core.Test.MediaFiles.DiskScanServiceTests [Test] public void should_update_fields_for_updated_files() { - var files = new List { + var files = new List + { Path.Combine(_artist.Path, "Season 1", "file1.flac"), }; @@ -542,9 +549,10 @@ namespace NzbDrone.Core.Test.MediaFiles.DiskScanServiceTests .With(x => x.Modified = new DateTime(2019, 2, 1)) .With(x => x.Size = 100) .With(x => x.Quality = new QualityModel(Quality.FLAC)) - .With(x => x.FileTrackInfo = new ParsedTrackInfo { - MediaInfo = Builder.CreateNew().Build() - }) + .With(x => x.FileTrackInfo = new ParsedTrackInfo + { + MediaInfo = Builder.CreateNew().Build() + }) .Build(); Mocker.GetMock() @@ -555,13 +563,12 @@ namespace NzbDrone.Core.Test.MediaFiles.DiskScanServiceTests Mocker.GetMock() .Verify(x => x.Update(It.Is>( - l => l.Count == 1 && + l => l.Count == 1 && l[0].Path == localTrack.Path && l[0].Modified == localTrack.Modified && l[0].Size == localTrack.Size && l[0].Quality.Equals(localTrack.Quality) && - l[0].MediaInfo.AudioFormat == localTrack.FileTrackInfo.MediaInfo.AudioFormat - )), + l[0].MediaInfo.AudioFormat == localTrack.FileTrackInfo.MediaInfo.AudioFormat)), Times.Once()); } } diff --git a/src/NzbDrone.Core.Test/MediaFiles/DownloadedAlbumsCommandServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/DownloadedAlbumsCommandServiceFixture.cs index dacf30aaf..e59c42f0d 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/DownloadedAlbumsCommandServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/DownloadedAlbumsCommandServiceFixture.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO.Abstractions; +using System.IO.Abstractions.TestingHelpers; using FizzWare.NBuilder; using Moq; using NUnit.Framework; @@ -9,11 +10,10 @@ using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Commands; using NzbDrone.Core.MediaFiles.TrackImport; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; using NzbDrone.Test.Common; -using System.IO.Abstractions.TestingHelpers; namespace NzbDrone.Core.Test.MediaFiles { @@ -28,7 +28,6 @@ namespace NzbDrone.Core.Test.MediaFiles [SetUp] public void Setup() { - Mocker.GetMock() .Setup(v => v.ProcessRootFolder(It.IsAny())) .Returns(new List()); @@ -47,11 +46,11 @@ namespace NzbDrone.Core.Test.MediaFiles .Build(); _trackedDownload = new TrackedDownload - { - DownloadItem = downloadItem, - RemoteAlbum = remoteAlbum, - State = TrackedDownloadStage.Downloading - }; + { + DownloadItem = downloadItem, + RemoteAlbum = remoteAlbum, + State = TrackedDownloadStage.Downloading + }; } private void GivenExistingFolder(string path) @@ -77,10 +76,8 @@ namespace NzbDrone.Core.Test.MediaFiles Assert.Throws(() => Subject.Execute(new DownloadedAlbumsScanCommand())); Mocker.GetMock().Verify(c => c.ProcessRootFolder(It.IsAny()), Times.Never()); - } - [Test] public void should_process_folder_if_downloadclientid_is_not_specified() { diff --git a/src/NzbDrone.Core.Test/MediaFiles/DownloadedTracksImportServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/DownloadedTracksImportServiceFixture.cs index 1aada9a68..3bc936e07 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/DownloadedTracksImportServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/DownloadedTracksImportServiceFixture.cs @@ -1,5 +1,7 @@ using System.Collections.Generic; +using System.IO; using System.IO.Abstractions; +using System.IO.Abstractions.TestingHelpers; using System.Linq; using FizzWare.NBuilder; using FluentAssertions; @@ -10,13 +12,11 @@ using NzbDrone.Core.Download; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.TrackImport; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; using NzbDrone.Test.Common; -using System.IO.Abstractions.TestingHelpers; -using System.IO; namespace NzbDrone.Core.Test.MediaFiles { @@ -33,7 +33,7 @@ namespace NzbDrone.Core.Test.MediaFiles public void Setup() { GivenAudioFiles(_audioFiles, 10); - + Mocker.GetMock().Setup(c => c.GetAudioFiles(It.IsAny(), It.IsAny())) .Returns(_audioFiles.Select(x => DiskProvider.GetFileInfo(x)).ToArray()); @@ -54,12 +54,11 @@ namespace NzbDrone.Core.Test.MediaFiles .Build(); _trackedDownload = new TrackedDownload - { DownloadItem = downloadItem, RemoteAlbum = remoteAlbum, State = TrackedDownloadStage.Downloading - }; + }; } private void GivenAudioFiles(string[] files, long filesize) @@ -246,7 +245,7 @@ namespace NzbDrone.Core.Test.MediaFiles .Setup(s => s.Import(It.IsAny>>(), true, null, ImportMode.Auto)) .Returns(imported.Select(i => new ImportResult(i)).ToList()); - GivenAudioFiles(new []{ _audioFiles.First().Replace(".ext", ".rar") }, 15.Megabytes()); + GivenAudioFiles(new[] { _audioFiles.First().Replace(".ext", ".rar") }, 15.Megabytes()); Subject.ProcessRootFolder(DiskProvider.GetDirectoryInfo(_droneFactory)); @@ -288,7 +287,7 @@ namespace NzbDrone.Core.Test.MediaFiles Subject.ProcessRootFolder(DiskProvider.GetDirectoryInfo(_droneFactory)); - DiskProvider.FolderExists(_subFolders[0]).Should().BeTrue(); + DiskProvider.FolderExists(_subFolders[0]).Should().BeTrue(); Mocker.GetMock() .Verify(v => v.DeleteFolder(It.IsAny(), true), Times.Never()); diff --git a/src/NzbDrone.Core.Test/MediaFiles/ImportApprovedTracksFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/ImportApprovedTracksFixture.cs index 425e0d803..2dc8eb36c 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/ImportApprovedTracksFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/ImportApprovedTracksFixture.cs @@ -8,14 +8,14 @@ using NUnit.Framework; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.MediaFiles.TrackImport; using NzbDrone.Core.MediaFiles.Events; +using NzbDrone.Core.MediaFiles.TrackImport; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles @@ -59,8 +59,7 @@ namespace NzbDrone.Core.Test.MediaFiles foreach (var track in tracks) { - _approvedDecisions.Add(new ImportDecision - ( + _approvedDecisions.Add(new ImportDecision( new LocalTrack { Artist = artist, @@ -85,7 +84,6 @@ namespace NzbDrone.Core.Test.MediaFiles Mocker.GetMock() .Setup(s => s.GetFilesByAlbum(It.IsAny())) .Returns(new List()); - } [Test] @@ -164,8 +162,8 @@ namespace NzbDrone.Core.Test.MediaFiles var fileDecision = _approvedDecisions.First(); fileDecision.Item.Size = 1.Gigabytes(); - var sampleDecision = new ImportDecision - (new LocalTrack + var sampleDecision = new ImportDecision( + new LocalTrack { Artist = fileDecision.Item.Artist, Album = fileDecision.Item.Album, @@ -175,7 +173,6 @@ namespace NzbDrone.Core.Test.MediaFiles Size = 80.Megabytes() }); - var all = new List>(); all.Add(fileDecision); all.Add(sampleDecision); @@ -219,6 +216,5 @@ namespace NzbDrone.Core.Test.MediaFiles Mocker.GetMock() .Verify(v => v.Delete(It.IsAny(), DeleteMediaFileReason.ManualOverride), Times.Once()); } - } } diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaFileDeletionService/DeleteTrackFileFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaFileDeletionService/DeleteTrackFileFixture.cs index edaf152ce..48d3006db 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaFileDeletionService/DeleteTrackFileFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaFileDeletionService/DeleteTrackFileFixture.cs @@ -5,8 +5,8 @@ using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Core.Exceptions; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles.MediaFileDeletionService diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaFileRepositoryFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaFileRepositoryFixture.cs index 67b4aba40..18a660a1d 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaFileRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaFileRepositoryFixture.cs @@ -1,12 +1,12 @@ +using System.Collections.Generic; +using System.Linq; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Music; +using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using System.Collections.Generic; -using System.Linq; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles @@ -14,10 +14,10 @@ namespace NzbDrone.Core.Test.MediaFiles [TestFixture] public class MediaFileRepositoryFixture : DbTest { - private Artist artist; - private Album album; - private List releases; - + private Artist _artist; + private Album _album; + private List _releases; + [SetUp] public void Setup() { @@ -25,48 +25,48 @@ namespace NzbDrone.Core.Test.MediaFiles .With(a => a.Id = 0) .Build(); Db.Insert(meta); - - artist = Builder.CreateNew() + + _artist = Builder.CreateNew() .With(a => a.ArtistMetadataId = meta.Id) .With(a => a.Id = 0) .Build(); - Db.Insert(artist); + Db.Insert(_artist); - album = Builder.CreateNew() + _album = Builder.CreateNew() .With(a => a.Id = 0) - .With(a => a.ArtistMetadataId = artist.ArtistMetadataId) + .With(a => a.ArtistMetadataId = _artist.ArtistMetadataId) .Build(); - Db.Insert(album); - - releases = Builder.CreateListOfSize(2) + Db.Insert(_album); + + _releases = Builder.CreateListOfSize(2) .All() .With(a => a.Id = 0) - .With(a => a.AlbumId = album.Id) + .With(a => a.AlbumId = _album.Id) .TheFirst(1) .With(a => a.Monitored = true) .TheNext(1) .With(a => a.Monitored = false) .Build().ToList(); - Db.InsertMany(releases); - + Db.InsertMany(_releases); + var files = Builder.CreateListOfSize(10) .All() .With(c => c.Id = 0) - .With(c => c.Quality =new QualityModel(Quality.MP3_192)) + .With(c => c.Quality = new QualityModel(Quality.MP3_192)) .TheFirst(5) - .With(c => c.AlbumId = album.Id) + .With(c => c.AlbumId = _album.Id) .TheFirst(1) .With(c => c.Path = @"C:\Test\Path\Artist\somefile1.flac".AsOsAgnostic()) .TheNext(1) .With(c => c.Path = @"C:\Test\Path\Artist\somefile2.flac".AsOsAgnostic()) .BuildListOfNew(); Db.InsertMany(files); - + var track = Builder.CreateListOfSize(10) .All() .With(a => a.Id = 0) .TheFirst(4) - .With(a => a.AlbumReleaseId = releases[0].Id) + .With(a => a.AlbumReleaseId = _releases[0].Id) .TheFirst(1) .With(a => a.TrackFileId = files[0].Id) .TheNext(1) @@ -77,21 +77,21 @@ namespace NzbDrone.Core.Test.MediaFiles .With(a => a.TrackFileId = files[3].Id) .TheNext(1) .With(a => a.TrackFileId = files[4].Id) - .With(a => a.AlbumReleaseId = releases[1].Id) + .With(a => a.AlbumReleaseId = _releases[1].Id) .TheNext(5) .With(a => a.TrackFileId = 0) .Build(); Db.InsertMany(track); } - + [Test] public void get_files_by_artist() { VerifyData(); - var artistFiles = Subject.GetFilesByArtist(artist.Id); + var artistFiles = Subject.GetFilesByArtist(_artist.Id); VerifyEagerLoaded(artistFiles); - artistFiles.Should().OnlyContain(c => c.Artist.Value.Id == artist.Id); + artistFiles.Should().OnlyContain(c => c.Artist.Value.Id == _artist.Id); } [Test] @@ -108,8 +108,8 @@ namespace NzbDrone.Core.Test.MediaFiles public void get_files_by_release() { VerifyData(); - var firstReleaseFiles = Subject.GetFilesByRelease(releases[0].Id); - var secondReleaseFiles = Subject.GetFilesByRelease(releases[1].Id); + var firstReleaseFiles = Subject.GetFilesByRelease(_releases[0].Id); + var secondReleaseFiles = Subject.GetFilesByRelease(_releases[1].Id); VerifyEagerLoaded(firstReleaseFiles); VerifyEagerLoaded(secondReleaseFiles); @@ -137,7 +137,7 @@ namespace NzbDrone.Core.Test.MediaFiles var files = Builder.CreateListOfSize(2) .All() .With(c => c.Id = 0) - .With(c => c.Quality =new QualityModel(Quality.MP3_192)) + .With(c => c.Quality = new QualityModel(Quality.MP3_192)) .TheFirst(1) .With(c => c.Path = @"C:\Test\Path2\Artist\somefile1.flac".AsOsAgnostic()) .TheNext(1) @@ -169,7 +169,7 @@ namespace NzbDrone.Core.Test.MediaFiles public void get_files_by_artist_should_only_return_tracks_for_monitored_releases() { VerifyData(); - var artistFiles = Subject.GetFilesByArtist(artist.Id); + var artistFiles = Subject.GetFilesByArtist(_artist.Id); VerifyEagerLoaded(artistFiles); artistFiles.Should().HaveCount(4); @@ -179,19 +179,19 @@ namespace NzbDrone.Core.Test.MediaFiles public void get_files_by_album() { VerifyData(); - var files = Subject.GetFilesByAlbum(album.Id); + var files = Subject.GetFilesByAlbum(_album.Id); VerifyEagerLoaded(files); - files.Should().OnlyContain(c => c.AlbumId == album.Id); + files.Should().OnlyContain(c => c.AlbumId == _album.Id); } [Test] public void get_files_by_album_should_only_return_tracks_for_monitored_releases() { VerifyData(); - var files = Subject.GetFilesByAlbum(album.Id); + var files = Subject.GetFilesByAlbum(_album.Id); VerifyEagerLoaded(files); - + files.Should().HaveCount(4); } @@ -236,10 +236,10 @@ namespace NzbDrone.Core.Test.MediaFiles [Test] public void delete_files_by_album_should_work_if_join_fails() { - Db.Delete(album); - Subject.DeleteFilesByAlbum(album.Id); - - Db.All().Where(x => x.AlbumId == album.Id).Should().HaveCount(0); + Db.Delete(_album); + Subject.DeleteFilesByAlbum(_album.Id); + + Db.All().Where(x => x.AlbumId == _album.Id).Should().HaveCount(0); } } } diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaFileServiceTests/FilterFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaFileServiceTests/FilterFixture.cs index 74f683506..f3443623f 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaFileServiceTests/FilterFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaFileServiceTests/FilterFixture.cs @@ -1,16 +1,16 @@ +using System; using System.Collections.Generic; +using System.IO.Abstractions; +using System.IO.Abstractions.TestingHelpers; using System.Linq; +using FizzWare.NBuilder; using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; -using System.IO.Abstractions.TestingHelpers; -using System.IO.Abstractions; -using System; -using FizzWare.NBuilder; namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests { @@ -24,10 +24,10 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests public void Setup() { _artist = new Artist - { - Id = 10, - Path = @"C:\".AsOsAgnostic() - }; + { + Id = 10, + Path = @"C:\".AsOsAgnostic() + }; } private List GivenFiles(string[] files) @@ -36,7 +36,7 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests { FileSystem.AddFile(file, new MockFileData(string.Empty) { LastWriteTime = _lastWrite }); } - + return files.Select(x => DiskProvider.GetFileInfo(x)).ToList(); } @@ -44,7 +44,7 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests [TestCase(FilterFilesType.Matched)] public void filter_should_return_all_files_if_no_existing_files(FilterFilesType filter) { - var files = GivenFiles(new [] + var files = GivenFiles(new[] { "C:\\file1.avi".AsOsAgnostic(), "C:\\file2.avi".AsOsAgnostic(), @@ -62,7 +62,7 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests [TestCase(FilterFilesType.Matched)] public void filter_should_return_nothing_if_all_files_exist(FilterFilesType filter) { - var files = GivenFiles(new [] + var files = GivenFiles(new[] { "C:\\file1.avi".AsOsAgnostic(), "C:\\file2.avi".AsOsAgnostic(), @@ -71,10 +71,11 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests Mocker.GetMock() .Setup(c => c.GetFilesWithBasePath(It.IsAny())) - .Returns(files.Select(f => new TrackFile { - Path = f.FullName, - Modified = _lastWrite - }).ToList()); + .Returns(files.Select(f => new TrackFile + { + Path = f.FullName, + Modified = _lastWrite + }).ToList()); Subject.FilterUnchangedFiles(files, _artist, filter).Should().BeEmpty(); } @@ -83,7 +84,7 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests [TestCase(FilterFilesType.Matched)] public void filter_should_not_return_existing_files(FilterFilesType filter) { - var files = GivenFiles(new [] + var files = GivenFiles(new[] { "C:\\file1.avi".AsOsAgnostic(), "C:\\file2.avi".AsOsAgnostic(), @@ -94,7 +95,8 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests .Setup(c => c.GetFilesWithBasePath(It.IsAny())) .Returns(new List { - new TrackFile{ + new TrackFile + { Path = "C:\\file2.avi".AsOsAgnostic(), Modified = _lastWrite } @@ -110,7 +112,7 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests { WindowsOnly(); - var files = GivenFiles(new [] + var files = GivenFiles(new[] { "C:\\file1.avi".AsOsAgnostic(), "C:\\FILE2.avi".AsOsAgnostic(), @@ -121,25 +123,24 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests .Setup(c => c.GetFilesWithBasePath(It.IsAny())) .Returns(new List { - new TrackFile{ + new TrackFile + { Path = "C:\\file2.avi".AsOsAgnostic(), Modified = _lastWrite } }); - Subject.FilterUnchangedFiles(files, _artist, filter).Should().HaveCount(2); Subject.FilterUnchangedFiles(files, _artist, filter).Select(x => x.FullName).Should().NotContain("C:\\file2.avi".AsOsAgnostic()); } - [TestCase(FilterFilesType.Known)] [TestCase(FilterFilesType.Matched)] public void filter_should_return_none_existing_files_not_ignoring_case(FilterFilesType filter) { PosixOnly(); - var files = GivenFiles(new [] + var files = GivenFiles(new[] { "C:\\file1.avi".AsOsAgnostic(), "C:\\FILE2.avi".AsOsAgnostic(), @@ -150,7 +151,8 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests .Setup(c => c.GetFilesWithBasePath(It.IsAny())) .Returns(new List { - new TrackFile{ + new TrackFile + { Path = "C:\\file2.avi".AsOsAgnostic(), Modified = _lastWrite } @@ -163,7 +165,7 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests [TestCase(FilterFilesType.Matched)] public void filter_should_not_change_casing(FilterFilesType filter) { - var files = GivenFiles(new [] + var files = GivenFiles(new[] { "C:\\FILE1.avi".AsOsAgnostic() }); @@ -177,7 +179,6 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests Subject.FilterUnchangedFiles(files, _artist, filter).Should().Contain(files.First()); } - [TestCase(FilterFilesType.Known)] [TestCase(FilterFilesType.Matched)] public void filter_should_not_return_existing_file_if_size_unchanged(FilterFilesType filter) @@ -192,7 +193,8 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests .Setup(c => c.GetFilesWithBasePath(It.IsAny())) .Returns(new List { - new TrackFile{ + new TrackFile + { Path = "C:\\file2.avi".AsOsAgnostic(), Size = 10, Modified = _lastWrite @@ -216,7 +218,8 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests .Setup(c => c.GetFilesWithBasePath(It.IsAny())) .Returns(new List { - new TrackFile{ + new TrackFile + { Path = "C:\\file2.avi".AsOsAgnostic(), Size = 10, Modified = _lastWrite, @@ -227,7 +230,7 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests Subject.FilterUnchangedFiles(files, _artist, filter).Should().HaveCount(3); Subject.FilterUnchangedFiles(files, _artist, filter).Select(x => x.FullName).Should().Contain("C:\\file2.avi".AsOsAgnostic()); } - + [TestCase(FilterFilesType.Matched)] public void filter_unmatched_should_not_return_existing_file_if_matched(FilterFilesType filter) { @@ -241,7 +244,8 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests .Setup(c => c.GetFilesWithBasePath(It.IsAny())) .Returns(new List { - new TrackFile{ + new TrackFile + { Path = "C:\\file2.avi".AsOsAgnostic(), Size = 10, Modified = _lastWrite, @@ -267,7 +271,8 @@ namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests .Setup(c => c.GetFilesWithBasePath(It.IsAny())) .Returns(new List { - new TrackFile{ + new TrackFile + { Path = "C:\\file2.avi".AsOsAgnostic(), Size = 10, Modified = _lastWrite diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaFileServiceTests/MediaFileServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaFileServiceTests/MediaFileServiceFixture.cs index 9a9dfc9b6..fc6f7a5c3 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaFileServiceTests/MediaFileServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaFileServiceTests/MediaFileServiceFixture.cs @@ -5,8 +5,8 @@ using Moq; using NUnit.Framework; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.MediaFiles.TrackFileMovingServiceTests { @@ -61,6 +61,5 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackFileMovingServiceTests VerifyEventPublished(Times.Once()); } - } } diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaFileTableCleanupServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaFileTableCleanupServiceFixture.cs index 4ac1c3ad8..f1c8ba681 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaFileTableCleanupServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaFileTableCleanupServiceFixture.cs @@ -1,20 +1,19 @@ 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.Music; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles { public class MediaFileTableCleanupServiceFixture : CoreTest { - private readonly string DELETED_PATH = @"c:\ANY FILE STARTING WITH THIS PATH IS CONSIDERED DELETED!".AsOsAgnostic(); + private readonly string _deletedPath = @"c:\ANY FILE STARTING WITH THIS PATH IS CONSIDERED DELETED!".AsOsAgnostic(); private List _tracks; private Artist _artist; @@ -76,15 +75,15 @@ namespace NzbDrone.Core.Test.MediaFiles .All() .With(x => x.Path = Path.Combine(@"c:\test".AsOsAgnostic(), Path.GetRandomFileName())) .Random(2) - .With(c => c.Path = Path.Combine(DELETED_PATH, Path.GetRandomFileName())) + .With(c => c.Path = Path.Combine(_deletedPath, Path.GetRandomFileName())) .Build(); GivenTrackFiles(trackFiles); - Subject.Clean(_artist, FilesOnDisk(trackFiles.Where(e => !e.Path.StartsWith(DELETED_PATH)))); + Subject.Clean(_artist, FilesOnDisk(trackFiles.Where(e => !e.Path.StartsWith(_deletedPath)))); Mocker.GetMock() - .Verify(c => c.DeleteMany(It.Is>(e => e.Count == 2 && e.All(y => y.Path.StartsWith(DELETED_PATH))), DeleteMediaFileReason.MissingFromDisk), Times.Once()); + .Verify(c => c.DeleteMany(It.Is>(e => e.Count == 2 && e.All(y => y.Path.StartsWith(_deletedPath))), DeleteMediaFileReason.MissingFromDisk), Times.Once()); } [Test] diff --git a/src/NzbDrone.Core.Test/MediaFiles/RenameTrackFileServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/RenameTrackFileServiceFixture.cs index 2e1f60544..79d79d376 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/RenameTrackFileServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/RenameTrackFileServiceFixture.cs @@ -7,8 +7,8 @@ using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Commands; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.MediaFiles { @@ -16,7 +16,7 @@ namespace NzbDrone.Core.Test.MediaFiles { private Artist _artist; private List _trackFiles; - + [SetUp] public void Setup() { @@ -59,7 +59,7 @@ namespace NzbDrone.Core.Test.MediaFiles { GivenNoTrackFiles(); - Subject.Execute(new RenameFilesCommand(_artist.Id, new List{1})); + Subject.Execute(new RenameFilesCommand(_artist.Id, new List { 1 })); Mocker.GetMock() .Verify(v => v.PublishEvent(It.IsAny()), Times.Never()); diff --git a/src/NzbDrone.Core.Test/MediaFiles/TrackFileMovingServiceTests/MoveTrackFileFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/TrackFileMovingServiceTests/MoveTrackFileFixture.cs index c5c0fa630..4136c498f 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/TrackFileMovingServiceTests/MoveTrackFileFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/TrackFileMovingServiceTests/MoveTrackFileFixture.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using FizzWare.NBuilder; using Moq; @@ -9,12 +10,11 @@ using NzbDrone.Common.Extensions; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Music; using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; using NzbDrone.Test.Common; -using System.IO; namespace NzbDrone.Core.Test.MediaFiles.TrackFileMovingServiceTests { diff --git a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Aggregation/AggregateFilenameInfoFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Aggregation/AggregateFilenameInfoFixture.cs index 4819ba958..1160b474f 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Aggregation/AggregateFilenameInfoFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Aggregation/AggregateFilenameInfoFixture.cs @@ -1,30 +1,30 @@ -using NUnit.Framework; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Parser.Model; -using System.Collections.Generic; -using System.Linq; -using System.IO; -using NzbDrone.Test.Common; -using NzbDrone.Core.MediaFiles.TrackImport.Aggregation.Aggregators; -using FluentAssertions; -using System.Text; using System; using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using FluentAssertions; +using NUnit.Framework; +using NzbDrone.Core.MediaFiles.TrackImport.Aggregation.Aggregators; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Test.Framework; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Aggregation.Aggregators { [TestFixture] public class AggregateFilenameInfoFixture : CoreTest { - private LocalAlbumRelease GivenTracks(List files, string root) { - var tracks = files.Select(x => new LocalTrack { - Path = Path.Combine(root, x), - FileTrackInfo = new ParsedTrackInfo { - TrackNumbers = new [] { 0 }, - } - }).ToList(); + var tracks = files.Select(x => new LocalTrack + { + Path = Path.Combine(root, x), + FileTrackInfo = new ParsedTrackInfo + { + TrackNumbers = new[] { 0 }, + } + }).ToList(); return new LocalAlbumRelease(tracks); } @@ -39,12 +39,13 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Aggregation.Aggregators [Test] public void should_aggregate_filenames_example() { - var release = GivenTracks(new List { + var release = GivenTracks(new List + { "Adele - 19 - 101 - Daydreamer.mp3", "Adele - 19 - 102 - Best for Last.mp3", "Adele - 19 - 103 - Chasing Pavements.mp3", "Adele - 19 - 203 - That's It, I Quit, I'm Moving On.mp3" - }, @"C:\incoming".AsOsAgnostic()); + }, @"C:\incoming".AsOsAgnostic()); Subject.Aggregate(release, true); @@ -56,49 +57,51 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Aggregation.Aggregators public static class TestCaseFactory { - private static List tokenList = new List { + private static List tokenList = new List + { + new[] { "trackNum2", "artist", "title", "tag" }, + new[] { "trackNum3", "artist", "title", "tag" }, + new[] { "trackNum2", "artist", "tag", "title" }, + new[] { "trackNum3", "artist", "tag", "title" }, + new[] { "trackNum2", "artist", "title" }, + new[] { "trackNum3", "artist", "title" }, - new [] {"trackNum2", "artist", "title", "tag"}, - new [] {"trackNum3", "artist", "title", "tag"}, - new [] {"trackNum2", "artist", "tag", "title"}, - new [] {"trackNum3", "artist", "tag", "title"}, - new [] {"trackNum2", "artist", "title"}, - new [] {"trackNum3", "artist", "title"}, + new[] { "artist", "tag", "trackNum2", "title" }, + new[] { "artist", "tag", "trackNum3", "title" }, + new[] { "artist", "trackNum2", "title", "tag" }, + new[] { "artist", "trackNum3", "title", "tag" }, + new[] { "artist", "trackNum2", "title" }, + new[] { "artist", "trackNum3", "title" }, - new [] {"artist", "tag", "trackNum2", "title"}, - new [] {"artist", "tag", "trackNum3", "title"}, - new [] {"artist", "trackNum2", "title", "tag"}, - new [] {"artist", "trackNum3", "title", "tag"}, - new [] {"artist", "trackNum2", "title"}, - new [] {"artist", "trackNum3", "title"}, + new[] { "artist", "title", "tag" }, + new[] { "artist", "tag", "title" }, + new[] { "artist", "title" }, - new [] {"artist", "title", "tag"}, - new [] {"artist", "tag", "title"}, - new [] {"artist", "title"}, + new[] { "trackNum2", "title" }, + new[] { "trackNum3", "title" }, - new [] {"trackNum2", "title"}, - new [] {"trackNum3", "title"}, - - new [] {"title"}, + new[] { "title" }, }; - private static List> separators = new List> { + private static List> separators = new List> + { Tuple.Create(" - ", " "), Tuple.Create("_", " "), Tuple.Create("-", "_") }; - private static List> otherCases = new List> { - Tuple.Create(new [] {"track2", "title"}, " ", " "), - Tuple.Create(new [] {"track3", "title"}, " ", " ") + private static List> otherCases = new List> + { + Tuple.Create(new[] { "track2", "title" }, " ", " "), + Tuple.Create(new[] { "track3", "title" }, " ", " ") }; - + public static IEnumerable TestCases { get { int i = 0; - + foreach (var tokens in tokenList) { foreach (var separator in separators) @@ -130,7 +133,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Aggregation.Aggregators var components = new List(); foreach (var field in fields) { - switch(field) + switch (field) { case "artist": components.Add("artist name".Replace(" ", whitespace)); @@ -139,7 +142,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Aggregation.Aggregators components.Add("tag string ignore".Replace(" ", whitespace)); break; case "title": - components.Add($"{(char)(96+i)} track title {i}".Replace(" ", whitespace)); + components.Add($"{(char)(96 + i)} track title {i}".Replace(" ", whitespace)); break; case "trackNum2": components.Add(i.ToString("00")); @@ -149,6 +152,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Aggregation.Aggregators break; } } + outp.Add(string.Join(fieldSeparator, components) + ".mp3"); } @@ -159,7 +163,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Aggregation.Aggregators { for (int i = 1; i <= tracks.Count; i++) { - var info = tracks[i-1].FileTrackInfo; + var info = tracks[i - 1].FileTrackInfo; if (tokens.Contains("artist")) { @@ -168,7 +172,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Aggregation.Aggregators if (tokens.Contains("title")) { - info.Title.Should().Be($"{(char)(96+i)} track title {i}".Replace(" ", whitespace)); + info.Title.Should().Be($"{(char)(96 + i)} track title {i}".Replace(" ", whitespace)); } if (tokens.Contains("trackNum2") || tokens.Contains("trackNum3")) @@ -186,8 +190,9 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Aggregation.Aggregators } } } - - [Test, TestCaseSource(typeof(TestCaseFactory), "TestCases")] + + [Test] + [TestCaseSource(typeof(TestCaseFactory), "TestCases")] public void should_aggregate_filenames_auto(Tuple testcase) { var files = GivenFilenames(testcase.Item1, testcase.Item2, testcase.Item3); @@ -197,6 +202,5 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Aggregation.Aggregators VerifyDataAuto(release.LocalTracks, testcase.Item1, testcase.Item3); } - } } diff --git a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/AlbumDistanceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/AlbumDistanceFixture.cs index d311b450c..a6fd25472 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/AlbumDistanceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/AlbumDistanceFixture.cs @@ -1,41 +1,40 @@ -using NUnit.Framework; -using NzbDrone.Core.MediaFiles.TrackImport.Identification; -using FluentAssertions; -using NzbDrone.Core.Test.Framework; -using FizzWare.NBuilder; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Music; +using System; using System.Collections.Generic; using System.Linq; -using System; +using FizzWare.NBuilder; +using FluentAssertions; +using NUnit.Framework; +using NzbDrone.Core.MediaFiles.TrackImport.Identification; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification { [TestFixture] public class AlbumDistanceFixture : CoreTest { - - private ArtistMetadata artist; + private ArtistMetadata _artist; [SetUp] public void Setup() { - artist = Builder + _artist = Builder .CreateNew() .With(x => x.Name = "artist") .Build(); } - + private List GivenTracks(int count) { - return Builder - .CreateListOfSize(count) - .All() - .With(x => x.ArtistMetadata = artist) - .With(x => x.MediumNumber = 1) - .Build() - .ToList(); + return Builder + .CreateListOfSize(count) + .All() + .With(x => x.ArtistMetadata = _artist) + .With(x => x.MediumNumber = 1) + .Build() + .ToList(); } private LocalTrack GivenLocalTrack(Track track, AlbumRelease release) @@ -56,7 +55,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification .With(x => x.Label = release.Label.First()) .With(x => x.Year = (uint)(release.Album.Value.ReleaseDate?.Year ?? 0)) .Build(); - + var localTrack = Builder .CreateNew() .With(x => x.FileTrackInfo = fileInfo) @@ -72,6 +71,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification { output.Add(GivenLocalTrack(track, release)); } + return output; } @@ -80,7 +80,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification var album = Builder .CreateNew() .With(x => x.Title = title) - .With(x => x.ArtistMetadata = artist) + .With(x => x.ArtistMetadata = _artist) .Build(); var media = Builder @@ -109,7 +109,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification return mapping; } - + [Test] public void test_identical_albums() { @@ -142,7 +142,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification var release = GivenAlbumRelease("album", tracks); var localTracks = GivenLocalTracks(tracks, release); var mapping = GivenMapping(localTracks, tracks); - + release.Album.Value.ArtistMetadata = Builder .CreateNew() .With(x => x.Name = "different artist") @@ -164,19 +164,18 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification .With(x => x.Name = "Various Artists") .With(x => x.ForeignArtistId = "89ad4ac3-39f7-470e-963a-56509c546377") .Build(); - + Subject.AlbumReleaseDistance(localTracks, release, mapping).NormalizedDistance().Should().Be(0.0); } // TODO: there are a couple more VA tests in beets but we don't support VA yet anyway - [Test] public void test_tracks_out_of_order() { var tracks = GivenTracks(3); var release = GivenAlbumRelease("album", tracks); var localTracks = GivenLocalTracks(tracks, release); - localTracks = new [] {1, 3, 2}.Select(x => localTracks[x-1]).ToList(); + localTracks = new[] { 1, 3, 2 }.Select(x => localTracks[x - 1]).ToList(); var mapping = GivenMapping(localTracks, tracks); var dist = Subject.AlbumReleaseDistance(localTracks, release, mapping); diff --git a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/DistanceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/DistanceFixture.cs index 4b1040083..8c0851f6d 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/DistanceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/DistanceFixture.cs @@ -1,8 +1,8 @@ +using System.Collections.Generic; +using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.MediaFiles.TrackImport.Identification; using NzbDrone.Test.Common; -using FluentAssertions; -using System.Collections.Generic; namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification { @@ -14,7 +14,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification { var dist = new Distance(); dist.Add("add", 1.0); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"add", new List { 1.0 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "add", new List { 1.0 } } }); } [Test] @@ -22,13 +22,13 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification { var dist = new Distance(); dist.AddEquality("equality", "ghi", new List { "abc", "def", "ghi" }); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"equality", new List { 0.0 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "equality", new List { 0.0 } } }); dist.AddEquality("equality", "xyz", new List { "abc", "def", "ghi" }); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"equality", new List { 0.0, 1.0 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "equality", new List { 0.0, 1.0 } } }); dist.AddEquality("equality", "abc", new List { "abc", "def", "ghi" }); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"equality", new List { 0.0, 1.0, 0.0 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "equality", new List { 0.0, 1.0, 0.0 } } }); } [Test] @@ -36,10 +36,10 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification { var dist = new Distance(); dist.AddBool("expr", true); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"expr", new List { 1.0 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "expr", new List { 1.0 } } }); dist.AddBool("expr", false); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"expr", new List { 1.0, 0.0 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "expr", new List { 1.0, 0.0 } } }); } [Test] @@ -47,16 +47,16 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification { var dist = new Distance(); dist.AddNumber("number", 1, 1); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"number", new List { 0.0 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "number", new List { 0.0 } } }); dist.AddNumber("number", 1, 2); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"number", new List { 0.0, 1.0 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "number", new List { 0.0, 1.0 } } }); dist.AddNumber("number", 2, 1); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"number", new List { 0.0, 1.0, 1.0 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "number", new List { 0.0, 1.0, 1.0 } } }); dist.AddNumber("number", -1, 2); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"number", new List { 0.0, 1.0, 1.0, 1.0, 1.0, 1.0 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "number", new List { 0.0, 1.0, 1.0, 1.0, 1.0, 1.0 } } }); } [Test] @@ -64,13 +64,13 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification { var dist = new Distance(); dist.AddPriority("priority", "abc", new List { "abc" }); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"priority", new List { 0.0 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "priority", new List { 0.0 } } }); dist.AddPriority("priority", "def", new List { "abc", "def" }); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"priority", new List { 0.0, 0.5 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "priority", new List { 0.0, 0.5 } } }); dist.AddPriority("priority", "xyz", new List { "abc", "def" }); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"priority", new List { 0.0, 0.5, 1.0 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "priority", new List { 0.0, 0.5, 1.0 } } }); } [Test] @@ -78,16 +78,16 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification { var dist = new Distance(); dist.AddPriority("priority", new List { "abc" }, new List { "abc" }); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"priority", new List { 0.0 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "priority", new List { 0.0 } } }); dist.AddPriority("priority", new List { "def" }, new List { "abc" }); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"priority", new List { 0.0, 1.0 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "priority", new List { 0.0, 1.0 } } }); dist.AddPriority("priority", new List { "abc", "xyz" }, new List { "abc" }); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"priority", new List { 0.0, 1.0, 0.0 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "priority", new List { 0.0, 1.0, 0.0 } } }); dist.AddPriority("priority", new List { "def", "xyz" }, new List { "abc", "def" }); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"priority", new List { 0.0, 1.0, 0.0, 0.5 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "priority", new List { 0.0, 1.0, 0.0, 0.5 } } }); } [Test] @@ -95,16 +95,16 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification { var dist = new Distance(); dist.AddRatio("ratio", 25, 100); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"ratio", new List { 0.25 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "ratio", new List { 0.25 } } }); dist.AddRatio("ratio", 10, 5); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"ratio", new List { 0.25, 1.0 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "ratio", new List { 0.25, 1.0 } } }); dist.AddRatio("ratio", -5, 5); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"ratio", new List { 0.25, 1.0, 0.0 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "ratio", new List { 0.25, 1.0, 0.0 } } }); dist.AddRatio("ratio", 5, 0); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"ratio", new List { 0.25, 1.0, 0.0, 0.0 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "ratio", new List { 0.25, 1.0, 0.0, 0.0 } } }); } [Test] @@ -112,7 +112,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification { var dist = new Distance(); dist.AddString("string", "abcd", "bcde"); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"string", new List { 0.5 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "string", new List { 0.5 } } }); } [Test] @@ -120,15 +120,15 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification { var dist = new Distance(); dist.AddString("string", string.Empty, "bcd"); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"string", new List { 1.0 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "string", new List { 1.0 } } }); } - + [Test] public void test_add_string_both_none() { var dist = new Distance(); dist.AddString("string", string.Empty, string.Empty); - dist.Penalties.Should().BeEquivalentTo(new Dictionary> { {"string", new List { 0.0 }}} ); + dist.Penalties.Should().BeEquivalentTo(new Dictionary> { { "string", new List { 0.0 } } }); } [Test] diff --git a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/GetCandidatesFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/GetCandidatesFixture.cs index b4c769152..bc9f73cb9 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/GetCandidatesFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/GetCandidatesFixture.cs @@ -1,42 +1,39 @@ -using NUnit.Framework; -using NzbDrone.Core.MediaFiles.TrackImport.Identification; -using FluentAssertions; -using NzbDrone.Core.Test.Framework; -using FizzWare.NBuilder; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Music; using System.Collections.Generic; using System.Linq; -using System; -using NzbDrone.Core.Parser; -using NzbDrone.Common.Serializer; +using FizzWare.NBuilder; +using FluentAssertions; using Moq; +using NUnit.Framework; +using NzbDrone.Core.MediaFiles.TrackImport.Identification; +using NzbDrone.Core.Music; +using NzbDrone.Core.Parser; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification { [TestFixture] public class GetCandidatesFixture : CoreTest { - - private ArtistMetadata artist; + private ArtistMetadata _artist; [SetUp] public void Setup() { - artist = Builder + _artist = Builder .CreateNew() .With(x => x.Name = "artist") .Build(); } - + private List GivenTracks(int count) { - return Builder - .CreateListOfSize(count) - .All() - .With(x => x.ArtistMetadata = artist) - .Build() - .ToList(); + return Builder + .CreateListOfSize(count) + .All() + .With(x => x.ArtistMetadata = _artist) + .Build() + .ToList(); } private ParsedTrackInfo GivenParsedTrackInfo(Track track, AlbumRelease release) @@ -76,7 +73,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification var album = Builder .CreateNew() .With(x => x.Title = title) - .With(x => x.ArtistMetadata = artist) + .With(x => x.ArtistMetadata = _artist) .Build(); var media = Builder @@ -110,11 +107,13 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification { Mocker.GetMock() .Setup(x => x.Lookup(It.IsAny>(), It.IsAny())) - .Callback((List x, double thres) => { - foreach(var track in x) { - track.AcoustIdResults = null; - } - }); + .Callback((List x, double thres) => + { + foreach (var track in x) + { + track.AcoustIdResults = null; + } + }); Mocker.GetMock() .Setup(x => x.GetReleasesByRecordingIds(It.IsAny>())) @@ -134,8 +133,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification var localAlbumRelease = new LocalAlbumRelease(localTracks); Subject.GetCandidatesFromTags(localAlbumRelease, null, null, release, false).Should().BeEquivalentTo( - new List { new CandidateAlbumRelease(release) } - ); + new List { new CandidateAlbumRelease(release) }); } [Test] @@ -152,8 +150,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification .Returns(release); Subject.GetCandidatesFromTags(localAlbumRelease, null, null, null, false).Should().BeEquivalentTo( - new List { new CandidateAlbumRelease(release) } - ); + new List { new CandidateAlbumRelease(release) }); } } } diff --git a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/IdentificationServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/IdentificationServiceFixture.cs index 1057ff9e5..d2d6bc181 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/IdentificationServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/IdentificationServiceFixture.cs @@ -1,27 +1,27 @@ +using System.Collections; +using System.Collections.Generic; using System.IO; using System.Linq; -using System.Collections; using FluentAssertions; using FluentValidation.Results; using Moq; using Newtonsoft.Json; using NUnit.Framework; +using NzbDrone.Common.Serializer; using NzbDrone.Core.Configuration; +using NzbDrone.Core.MediaFiles.TrackImport.Aggregation; +using NzbDrone.Core.MediaFiles.TrackImport.Aggregation.Aggregators; using NzbDrone.Core.MediaFiles.TrackImport.Identification; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.MetadataSource; using NzbDrone.Core.MetadataSource.SkyHook; using NzbDrone.Core.Music; using NzbDrone.Core.Music.Commands; +using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Metadata; using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; -using System.Collections.Generic; -using NzbDrone.Common.Serializer; -using NzbDrone.Core.Parser; -using NzbDrone.Core.MediaFiles.TrackImport.Aggregation.Aggregators; -using NzbDrone.Core.MediaFiles.TrackImport.Aggregation; namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification { @@ -32,13 +32,13 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification private AddArtistService _addArtistService; private RefreshArtistService _refreshArtistService; - private IdentificationService Subject; - + private IdentificationService _subject; + [SetUp] public void SetUp() { UseRealHttp(); - + // Resolve all the parts we need Mocker.SetConstant(Mocker.Resolve()); Mocker.SetConstant(Mocker.Resolve()); @@ -58,7 +58,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification Mocker.SetConstant(Mocker.Resolve()); Mocker.SetConstant(Mocker.Resolve()); Mocker.SetConstant(Mocker.Resolve()); - + _addArtistService = Mocker.Resolve(); Mocker.SetConstant(Mocker.Resolve()); @@ -71,14 +71,14 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification Mocker.SetConstant(Mocker.Resolve()); // set up the augmenters - List> aggregators = new List> { + List> aggregators = new List> + { Mocker.Resolve() }; Mocker.SetConstant>>(aggregators); Mocker.SetConstant(Mocker.Resolve()); - - Subject = Mocker.Resolve(); + _subject = Mocker.Resolve(); } private void GivenMetadataProfile(MetadataProfile profile) @@ -102,15 +102,18 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification private Artist GivenArtist(string foreignArtistId, int metadataProfileId) { - var artist = _addArtistService.AddArtist(new Artist { - Metadata = new ArtistMetadata { - ForeignArtistId = foreignArtistId - }, - Path = @"c:\test".AsOsAgnostic(), - MetadataProfileId = metadataProfileId - }); + var artist = _addArtistService.AddArtist(new Artist + { + Metadata = new ArtistMetadata + { + ForeignArtistId = foreignArtistId + }, + Path = @"c:\test".AsOsAgnostic(), + MetadataProfileId = metadataProfileId + }); - var command = new RefreshArtistCommand{ + var command = new RefreshArtistCommand + { ArtistId = artist.Id, Trigger = CommandTrigger.Unspecified }; @@ -127,15 +130,17 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification Mocker.GetMock() .Setup(x => x.Lookup(It.IsAny>(), It.IsAny())) - .Callback((List track, double thres) => { - track.ForEach(x => x.AcoustIdResults = fingerprints.SingleOrDefault(f => f.Path == x.Path).AcoustIdResults); - }); + .Callback((List track, double thres) => + { + track.ForEach(x => x.AcoustIdResults = fingerprints.SingleOrDefault(f => f.Path == x.Path).AcoustIdResults); + }); } public static class IdTestCaseFactory { // for some reason using Directory.GetFiles causes nUnit to error - private static string[] files = { + private static string[] files = + { "FilesWithMBIds.json", "PreferMissingToBadMatch.json", "InconsistentTyposInAlbum.json", @@ -159,7 +164,8 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification // these are slow to run so only do so manually [Explicit] - [Test, TestCaseSource(typeof(IdTestCaseFactory), "TestCases")] + [Test] + [TestCaseSource(typeof(IdTestCaseFactory), "TestCases")] public void should_match_tracks(string file) { var path = Path.Combine(TestContext.CurrentContext.TestDirectory, "Files", "Identification", file); @@ -168,17 +174,18 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification var artists = GivenArtists(testcase.LibraryArtists); var specifiedArtist = artists.SingleOrDefault(x => x.Metadata.Value.ForeignArtistId == testcase.Artist); - var tracks = testcase.Tracks.Select(x => new LocalTrack { - Path = x.Path.AsOsAgnostic(), - FileTrackInfo = x.FileTrackInfo - }).ToList(); + var tracks = testcase.Tracks.Select(x => new LocalTrack + { + Path = x.Path.AsOsAgnostic(), + FileTrackInfo = x.FileTrackInfo + }).ToList(); if (testcase.Fingerprints != null) { GivenFingerprints(testcase.Fingerprints); } - var result = Subject.Identify(tracks, specifiedArtist, null, null, testcase.NewDownload, testcase.SingleRelease, false); + var result = _subject.Identify(tracks, specifiedArtist, null, null, testcase.NewDownload, testcase.SingleRelease, false); TestLogger.Debug($"Found releases:\n{result.Where(x => x.AlbumRelease != null).Select(x => x.AlbumRelease?.ForeignReleaseId).ToJson()}"); diff --git a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/MunkresFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/MunkresFixture.cs index b9e7ab06c..2229a05f2 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/MunkresFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/MunkresFixture.cs @@ -1,7 +1,7 @@ +using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.MediaFiles.TrackImport.Identification; using NzbDrone.Test.Common; -using FluentAssertions; namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification { @@ -15,170 +15,178 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification m.Run(); m.Cost.Should().Be(expectedCost); } - + [Test] public void MunkresSquareTest1() { - var C = new double[,] { + var c = new double[,] + { { 1, 2, 3 }, { 2, 4, 6 }, { 3, 6, 9 } }; - RunTest(C, 10); - + RunTest(c, 10); } [Test] public void MunkresSquareTest2() { - var C = new double[,] { + var c = new double[,] + { { 400, 150, 400 }, { 400, 450, 600 }, { 300, 225, 300 } }; - RunTest(C, 850); + RunTest(c, 850); } [Test] public void MunkresSquareTest3() { - var C = new double[,] { + var c = new double[,] + { { 10, 10, 8 }, { 9, 8, 1 }, { 9, 7, 4 } }; - RunTest(C, 18); + RunTest(c, 18); } [Test] public void MunkresSquareTest4() { - var C = new double[,] { + var c = new double[,] + { { 5, 9, 1 }, { 10, 3, 2 }, { 8, 7, 4 } }; - RunTest(C, 12); + RunTest(c, 12); } [Test] public void MunkresSquareTest5() { - var C = new double[,] { - {12, 26, 17, 0, 0}, - {49, 43, 36, 10, 5}, - {97, 9, 66, 34, 0}, - {52, 42, 19, 36, 0}, - {15, 93, 55, 80, 0} + var c = new double[,] + { + { 12, 26, 17, 0, 0 }, + { 49, 43, 36, 10, 5 }, + { 97, 9, 66, 34, 0 }, + { 52, 42, 19, 36, 0 }, + { 15, 93, 55, 80, 0 } }; - RunTest(C, 48); + RunTest(c, 48); } [Test] public void Munkres5x5Test() { - var C = new double[,] { - {12, 9, 27, 10, 23}, - {7, 13, 13, 30, 19}, - {25, 18, 26, 11, 26}, - {9, 28, 26, 23, 13}, - {16, 16, 24, 6, 9} + var c = new double[,] + { + { 12, 9, 27, 10, 23 }, + { 7, 13, 13, 30, 19 }, + { 25, 18, 26, 11, 26 }, + { 9, 28, 26, 23, 13 }, + { 16, 16, 24, 6, 9 } }; - RunTest(C, 51); + RunTest(c, 51); } [Test] public void Munkres10x10Test() { - var C = new double[,] { - {37, 34, 29, 26, 19, 8, 9, 23, 19, 29}, - {9, 28, 20, 8, 18, 20, 14, 33, 23, 14}, - {15, 26, 12, 28, 6, 17, 9, 13, 21, 7}, - {2, 8, 38, 36, 39, 5, 36, 2, 38, 27}, - {30, 3, 33, 16, 21, 39, 7, 23, 28, 36}, - {7, 5, 19, 22, 36, 36, 24, 19, 30, 2}, - {34, 20, 13, 36, 12, 33, 9, 10, 23, 5}, - {7, 37, 22, 39, 33, 39, 10, 3, 13, 26}, - {21, 25, 23, 39, 31, 37, 32, 33, 38, 1}, - {17, 34, 40, 10, 29, 37, 40, 3, 25, 3} + var c = new double[,] + { + { 37, 34, 29, 26, 19, 8, 9, 23, 19, 29 }, + { 9, 28, 20, 8, 18, 20, 14, 33, 23, 14 }, + { 15, 26, 12, 28, 6, 17, 9, 13, 21, 7 }, + { 2, 8, 38, 36, 39, 5, 36, 2, 38, 27 }, + { 30, 3, 33, 16, 21, 39, 7, 23, 28, 36 }, + { 7, 5, 19, 22, 36, 36, 24, 19, 30, 2 }, + { 34, 20, 13, 36, 12, 33, 9, 10, 23, 5 }, + { 7, 37, 22, 39, 33, 39, 10, 3, 13, 26 }, + { 21, 25, 23, 39, 31, 37, 32, 33, 38, 1 }, + { 17, 34, 40, 10, 29, 37, 40, 3, 25, 3 } }; - RunTest(C, 66); + RunTest(c, 66); } [Test] public void Munkres20x20Test() { - var C = new double[,] { - {5, 4, 3, 9, 8, 9, 3, 5, 6, 9, 4, 10, 3, 5, 6, 6, 1, 8, 10, 2}, - {10, 9, 9, 2, 8, 3, 9, 9, 10, 1, 7, 10, 8, 4, 2, 1, 4, 8, 4, 8}, - {10, 4, 4, 3, 1, 3, 5, 10, 6, 8, 6, 8, 4, 10, 7, 2, 4, 5, 1, 8}, - {2, 1, 4, 2, 3, 9, 3, 4, 7, 3, 4, 1, 3, 2, 9, 8, 6, 5, 7, 8}, - {3, 4, 4, 1, 4, 10, 1, 2, 6, 4, 5, 10, 2, 2, 3, 9, 10, 9, 9, 10}, - {1, 10, 1, 8, 1, 3, 1, 7, 1, 1, 2, 1, 2, 6, 3, 3, 4, 4, 8, 6}, - {1, 8, 7, 10, 10, 3, 4, 6, 1, 6, 6, 4, 9, 6, 9, 6, 4, 5, 4, 7}, - {8, 10, 3, 9, 4, 9, 3, 3, 4, 6, 4, 2, 6, 7, 7, 4, 4, 3, 4, 7}, - {1, 3, 8, 2, 6, 9, 2, 7, 4, 8, 10, 8, 10, 5, 1, 3, 10, 10, 2, 9}, - {2, 4, 1, 9, 2, 9, 7, 8, 2, 1, 4, 10, 5, 2, 7, 6, 5, 7, 2, 6}, - {4, 5, 1, 4, 2, 3, 3, 4, 1, 8, 8, 2, 6, 9, 5, 9, 6, 3, 9, 3}, - {3, 1, 1, 8, 6, 8, 8, 7, 9, 3, 2, 1, 8, 2, 4, 7, 3, 1, 2, 4}, - {5, 9, 8, 6, 10, 4, 10, 3, 4, 10, 10, 10, 1, 7, 8, 8, 7, 7, 8, 8}, - {1, 4, 6, 1, 6, 1, 2, 10, 5, 10, 2, 6, 2, 4, 5, 5, 3, 5, 1, 5}, - {5, 6, 9, 10, 6, 6, 10, 6, 4, 1, 5, 3, 9, 5, 2, 10, 9, 9, 5, 1}, - {10, 9, 4, 6, 9, 5, 3, 7, 10, 1, 6, 8, 1, 1, 10, 9, 5, 7, 7, 5}, - {2, 6, 6, 6, 6, 2, 9, 4, 7, 5, 3, 2, 10, 3, 4, 5, 10, 9, 1, 7}, - {5, 2, 4, 9, 8, 4, 8, 2, 4, 1, 3, 7, 6, 8, 1, 6, 8, 8, 10, 10}, - {9, 6, 3, 1, 8, 5, 7, 8, 7, 2, 1, 8, 2, 8, 3, 7, 4, 8, 7, 7}, - {8, 4, 4, 9, 7, 10, 6, 2, 1, 5, 8, 5, 1, 1, 1, 9, 1, 3, 5, 3} + var c = new double[,] + { + { 5, 4, 3, 9, 8, 9, 3, 5, 6, 9, 4, 10, 3, 5, 6, 6, 1, 8, 10, 2 }, + { 10, 9, 9, 2, 8, 3, 9, 9, 10, 1, 7, 10, 8, 4, 2, 1, 4, 8, 4, 8 }, + { 10, 4, 4, 3, 1, 3, 5, 10, 6, 8, 6, 8, 4, 10, 7, 2, 4, 5, 1, 8 }, + { 2, 1, 4, 2, 3, 9, 3, 4, 7, 3, 4, 1, 3, 2, 9, 8, 6, 5, 7, 8 }, + { 3, 4, 4, 1, 4, 10, 1, 2, 6, 4, 5, 10, 2, 2, 3, 9, 10, 9, 9, 10 }, + { 1, 10, 1, 8, 1, 3, 1, 7, 1, 1, 2, 1, 2, 6, 3, 3, 4, 4, 8, 6 }, + { 1, 8, 7, 10, 10, 3, 4, 6, 1, 6, 6, 4, 9, 6, 9, 6, 4, 5, 4, 7 }, + { 8, 10, 3, 9, 4, 9, 3, 3, 4, 6, 4, 2, 6, 7, 7, 4, 4, 3, 4, 7 }, + { 1, 3, 8, 2, 6, 9, 2, 7, 4, 8, 10, 8, 10, 5, 1, 3, 10, 10, 2, 9 }, + { 2, 4, 1, 9, 2, 9, 7, 8, 2, 1, 4, 10, 5, 2, 7, 6, 5, 7, 2, 6 }, + { 4, 5, 1, 4, 2, 3, 3, 4, 1, 8, 8, 2, 6, 9, 5, 9, 6, 3, 9, 3 }, + { 3, 1, 1, 8, 6, 8, 8, 7, 9, 3, 2, 1, 8, 2, 4, 7, 3, 1, 2, 4 }, + { 5, 9, 8, 6, 10, 4, 10, 3, 4, 10, 10, 10, 1, 7, 8, 8, 7, 7, 8, 8 }, + { 1, 4, 6, 1, 6, 1, 2, 10, 5, 10, 2, 6, 2, 4, 5, 5, 3, 5, 1, 5 }, + { 5, 6, 9, 10, 6, 6, 10, 6, 4, 1, 5, 3, 9, 5, 2, 10, 9, 9, 5, 1 }, + { 10, 9, 4, 6, 9, 5, 3, 7, 10, 1, 6, 8, 1, 1, 10, 9, 5, 7, 7, 5 }, + { 2, 6, 6, 6, 6, 2, 9, 4, 7, 5, 3, 2, 10, 3, 4, 5, 10, 9, 1, 7 }, + { 5, 2, 4, 9, 8, 4, 8, 2, 4, 1, 3, 7, 6, 8, 1, 6, 8, 8, 10, 10 }, + { 9, 6, 3, 1, 8, 5, 7, 8, 7, 2, 1, 8, 2, 8, 3, 7, 4, 8, 7, 7 }, + { 8, 4, 4, 9, 7, 10, 6, 2, 1, 5, 8, 5, 1, 1, 1, 9, 1, 3, 5, 3 } }; - RunTest(C, 22); + RunTest(c, 22); } [Test] public void MunkresRectangularTest1() { - var C = new double[,] { + var c = new double[,] + { { 400, 150, 400, 1 }, { 400, 450, 600, 2 }, { 300, 225, 300, 3 } }; - RunTest(C, 452); + RunTest(c, 452); } [Test] public void MunkresRectangularTest2() { - var C = new double[,] { + var c = new double[,] + { { 10, 10, 8, 11 }, { 9, 8, 1, 1 }, { 9, 7, 4, 10 } }; - RunTest(C, 15); + RunTest(c, 15); } [Test] public void MunkresRectangularTest3() { - var C = new double[,] { - {34, 26, 17, 12}, - {43, 43, 36, 10}, - {97, 47, 66, 34}, - {52, 42, 19, 36}, - {15, 93, 55, 80} + var c = new double[,] + { + { 34, 26, 17, 12 }, + { 43, 43, 36, 10 }, + { 97, 47, 66, 34 }, + { 52, 42, 19, 36 }, + { 15, 93, 55, 80 } }; - RunTest(C, 70); + RunTest(c, 70); } - } } - diff --git a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/TrackDistanceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/TrackDistanceFixture.cs index cda57ecaa..961845f95 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/TrackDistanceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/TrackDistanceFixture.cs @@ -1,11 +1,11 @@ +using FizzWare.NBuilder; +using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.MediaFiles.TrackImport.Identification; -using FluentAssertions; -using NzbDrone.Core.Test.Framework; -using FizzWare.NBuilder; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Music; using NzbDrone.Core.Parser; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification { @@ -18,7 +18,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification .CreateNew() .With(x => x.Name = "artist") .Build(); - + var mbTrack = Builder .CreateNew() .With(x => x.Title = title) @@ -38,7 +38,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification .With(x => x.TrackNumbers = new[] { 1 }) .With(x => x.RecordingMBId = track.ForeignRecordingId) .Build(); - + var localTrack = Builder .CreateNew() .With(x => x.FileTrackInfo = fileInfo) @@ -46,7 +46,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification return localTrack; } - + [Test] public void test_identical_tracks() { @@ -55,7 +55,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification Subject.TrackDistance(localTrack, track, 1, true).NormalizedDistance().Should().Be(0.0); } - + [Test] public void test_feat_removed_from_localtrack() { diff --git a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/TrackGroupingServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/TrackGroupingServiceFixture.cs index 094e5989a..a83c935e0 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/TrackGroupingServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/TrackGroupingServiceFixture.cs @@ -1,16 +1,16 @@ -using NUnit.Framework; -using NzbDrone.Core.MediaFiles.TrackImport.Identification; -using NzbDrone.Test.Common; -using FluentAssertions; -using NzbDrone.Core.Test.Framework; -using FizzWare.NBuilder; -using NzbDrone.Core.Parser.Model; using System.Collections.Generic; -using System.Linq; using System.IO; -using FizzWare.NBuilder.PropertyNaming; +using System.Linq; using System.Reflection; using System.Text; +using FizzWare.NBuilder; +using FizzWare.NBuilder.PropertyNaming; +using FluentAssertions; +using NUnit.Framework; +using NzbDrone.Core.MediaFiles.TrackImport.Identification; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Test.Framework; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification { @@ -18,50 +18,51 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification // but the standard random value namer would give paths that are too long on windows public class RandomValueNamerShortStrings : RandomValuePropertyNamer { - private readonly IRandomGenerator generator; - private static readonly List allowedChars; - - public RandomValueNamerShortStrings(BuilderSettings settings) : base(settings) + private static readonly List AllowedChars; + private readonly IRandomGenerator _generator; + + public RandomValueNamerShortStrings(BuilderSettings settings) + : base(settings) { - generator = new RandomGenerator(); + _generator = new RandomGenerator(); } static RandomValueNamerShortStrings() { - allowedChars = new List(); + AllowedChars = new List(); for (char c = 'a'; c < 'z'; c++) { - allowedChars.Add(c); + AllowedChars.Add(c); } for (char c = 'A'; c < 'Z'; c++) { - allowedChars.Add(c); + AllowedChars.Add(c); } for (char c = '0'; c < '9'; c++) { - allowedChars.Add(c); + AllowedChars.Add(c); } } protected override string GetString(MemberInfo memberInfo) { - int length = generator.Next(1, 100); + int length = _generator.Next(1, 100); char[] chars = new char[length]; for (int i = 0; i < length; i++) { - int index = generator.Next(0, allowedChars.Count - 1); - chars[i] = allowedChars[index]; + int index = _generator.Next(0, AllowedChars.Count - 1); + chars[i] = AllowedChars[index]; } byte[] bytes = Encoding.UTF8.GetBytes(chars); return Encoding.UTF8.GetString(bytes, 0, bytes.Length); } } - + [TestFixture] public class TrackGroupingServiceFixture : CoreTest { @@ -117,7 +118,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification .With(f => f.AlbumMBId = null) .With(f => f.ReleaseMBId = null) .Build(); - + var tracks = fileInfos.Select(x => Builder .CreateNew() .With(y => y.FileTrackInfo = x) @@ -196,7 +197,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification TrackGroupingService.IsVariousArtists(tracks).Should().Be(false); TrackGroupingService.LooksLikeSingleRelease(tracks).Should().Be(true); - + output.Count.Should().Be(1); output[0].LocalTracks.Count.Should().Be(count); } @@ -206,10 +207,8 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification [TestCase("disk")] public void should_group_multi_disc_release(string mediaName) { - var tracks = GivenTracks($"C:\\music\\incoming\\artist - album\\{mediaName} 1".AsOsAgnostic(), - "artist", "album", 10); - tracks.AddRange(GivenTracks($"C:\\music\\incoming\\artist - album\\{mediaName} 2".AsOsAgnostic(), - "artist", "album", 5)); + var tracks = GivenTracks($"C:\\music\\incoming\\artist - album\\{mediaName} 1".AsOsAgnostic(), "artist", "album", 10); + tracks.AddRange(GivenTracks($"C:\\music\\incoming\\artist - album\\{mediaName} 2".AsOsAgnostic(), "artist", "album", 5)); TrackGroupingService.IsVariousArtists(tracks).Should().Be(false); TrackGroupingService.LooksLikeSingleRelease(tracks).Should().Be(true); @@ -222,14 +221,12 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification [Test] public void should_not_group_two_different_albums_by_same_artist() { - var tracks = GivenTracks($"C:\\music\\incoming\\artist - album1".AsOsAgnostic(), - "artist", "album1", 10); - tracks.AddRange(GivenTracks($"C:\\music\\incoming\\artist - album2".AsOsAgnostic(), - "artist", "album2", 5)); + var tracks = GivenTracks($"C:\\music\\incoming\\artist - album1".AsOsAgnostic(), "artist", "album1", 10); + tracks.AddRange(GivenTracks($"C:\\music\\incoming\\artist - album2".AsOsAgnostic(), "artist", "album2", 5)); TrackGroupingService.IsVariousArtists(tracks).Should().Be(false); TrackGroupingService.LooksLikeSingleRelease(tracks).Should().Be(false); - + var output = Subject.GroupTracks(tracks); output.Count.Should().Be(2); output[0].LocalTracks.Count.Should().Be(10); @@ -239,14 +236,12 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification [Test] public void should_group_albums_with_typos() { - var tracks = GivenTracks($"C:\\music\\incoming\\artist - album".AsOsAgnostic(), - "artist", "Rastaman Vibration (Remastered)", 10); - tracks.AddRange(GivenTracks($"C:\\music\\incoming\\artist - album".AsOsAgnostic(), - "artist", "Rastaman Vibration (Remastered", 5)); + var tracks = GivenTracks($"C:\\music\\incoming\\artist - album".AsOsAgnostic(), "artist", "Rastaman Vibration (Remastered)", 10); + tracks.AddRange(GivenTracks($"C:\\music\\incoming\\artist - album".AsOsAgnostic(), "artist", "Rastaman Vibration (Remastered", 5)); TrackGroupingService.IsVariousArtists(tracks).Should().Be(false); TrackGroupingService.LooksLikeSingleRelease(tracks).Should().Be(true); - + var output = Subject.GroupTracks(tracks); output.Count.Should().Be(1); output[0].LocalTracks.Count.Should().Be(15); @@ -255,14 +250,12 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification [Test] public void should_not_group_two_different_tracks_in_same_directory() { - var tracks = GivenTracks($"C:\\music\\incoming".AsOsAgnostic(), - "artist", "album1", 1); - tracks.AddRange(GivenTracks($"C:\\music\\incoming".AsOsAgnostic(), - "artist", "album2", 1)); + var tracks = GivenTracks($"C:\\music\\incoming".AsOsAgnostic(), "artist", "album1", 1); + tracks.AddRange(GivenTracks($"C:\\music\\incoming".AsOsAgnostic(), "artist", "album2", 1)); TrackGroupingService.IsVariousArtists(tracks).Should().Be(false); TrackGroupingService.LooksLikeSingleRelease(tracks).Should().Be(false); - + var output = Subject.GroupTracks(tracks); output.Count.Should().Be(2); output[0].LocalTracks.Count.Should().Be(1); @@ -272,14 +265,12 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification [Test] public void should_separate_two_albums_in_same_directory() { - var tracks = GivenTracks($"C:\\music\\incoming\\artist discog".AsOsAgnostic(), - "artist", "album1", 10); - tracks.AddRange(GivenTracks($"C:\\music\\incoming\\artist disog".AsOsAgnostic(), - "artist", "album2", 5)); + var tracks = GivenTracks($"C:\\music\\incoming\\artist discog".AsOsAgnostic(), "artist", "album1", 10); + tracks.AddRange(GivenTracks($"C:\\music\\incoming\\artist disog".AsOsAgnostic(), "artist", "album2", 5)); TrackGroupingService.IsVariousArtists(tracks).Should().Be(false); TrackGroupingService.LooksLikeSingleRelease(tracks).Should().Be(false); - + var output = Subject.GroupTracks(tracks); output.Count.Should().Be(2); output[0].LocalTracks.Count.Should().Be(10); @@ -292,13 +283,12 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification var tracks = new List(); for (int i = 0; i < 100; i++) { - tracks.AddRange(GivenTracks($"C:\\music".AsOsAgnostic(), - "artist" + i, "album" + i, 10)); + tracks.AddRange(GivenTracks($"C:\\music".AsOsAgnostic(), "artist" + i, "album" + i, 10)); } // don't test various artists here because it's designed to only work if there's a common album TrackGroupingService.LooksLikeSingleRelease(tracks).Should().Be(false); - + var output = Subject.GroupTracks(tracks); output.Count.Should().Be(100); output.Select(x => x.LocalTracks.Count).Distinct().Should().BeEquivalentTo(new List { 10 }); @@ -307,14 +297,12 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification [Test] public void should_separate_two_albums_by_different_artists_in_same_directory() { - var tracks = GivenTracks($"C:\\music\\incoming".AsOsAgnostic(), - "artist1", "album1", 10); - tracks.AddRange(GivenTracks($"C:\\music\\incoming".AsOsAgnostic(), - "artist2", "album2", 5)); + var tracks = GivenTracks($"C:\\music\\incoming".AsOsAgnostic(), "artist1", "album1", 10); + tracks.AddRange(GivenTracks($"C:\\music\\incoming".AsOsAgnostic(), "artist2", "album2", 5)); TrackGroupingService.IsVariousArtists(tracks).Should().Be(false); TrackGroupingService.LooksLikeSingleRelease(tracks).Should().Be(false); - + var output = Subject.GroupTracks(tracks); output.Count.Should().Be(2); output[0].LocalTracks.Count.Should().Be(10); @@ -329,7 +317,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification TrackGroupingService.IsVariousArtists(tracks).Should().Be(true); TrackGroupingService.LooksLikeSingleRelease(tracks).Should().Be(true); - + var output = Subject.GroupTracks(tracks); output.Count.Should().Be(1); output[0].LocalTracks.Count.Should().Be(10); @@ -338,14 +326,12 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification [Test] public void should_not_group_two_albums_by_different_artists_with_same_title() { - var tracks = GivenTracks($"C:\\music\\incoming\\album".AsOsAgnostic(), - "artist1", "album", 10); - tracks.AddRange(GivenTracks($"C:\\music\\incoming\\album".AsOsAgnostic(), - "artist2", "album", 5)); + var tracks = GivenTracks($"C:\\music\\incoming\\album".AsOsAgnostic(), "artist1", "album", 10); + tracks.AddRange(GivenTracks($"C:\\music\\incoming\\album".AsOsAgnostic(), "artist2", "album", 5)); TrackGroupingService.IsVariousArtists(tracks).Should().Be(false); TrackGroupingService.LooksLikeSingleRelease(tracks).Should().Be(false); - + var output = Subject.GroupTracks(tracks); output.Count.Should().Be(2); @@ -369,8 +355,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification [Test] public void should_not_fail_if_some_tags_null() { - var tracks = GivenTracks($"C:\\music\\incoming\\album".AsOsAgnostic(), - "artist1", "album", 10); + var tracks = GivenTracks($"C:\\music\\incoming\\album".AsOsAgnostic(), "artist1", "album", 10); tracks.AddRange(GivenTracksWithNoTags($"C:\\music\\incoming\\album".AsOsAgnostic(), 2)); TrackGroupingService.IsVariousArtists(tracks).Should().Be(false); @@ -384,17 +369,15 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification [Test] public void should_cope_with_one_album_in_subfolder_of_another() { - var tracks = GivenTracks($"C:\\music\\incoming\\album".AsOsAgnostic(), - "artist1", "album", 10); - tracks.AddRange(GivenTracks($"C:\\music\\incoming\\album\\anotheralbum".AsOsAgnostic(), - "artist2", "album2", 10)); + var tracks = GivenTracks($"C:\\music\\incoming\\album".AsOsAgnostic(), "artist1", "album", 10); + tracks.AddRange(GivenTracks($"C:\\music\\incoming\\album\\anotheralbum".AsOsAgnostic(), "artist2", "album2", 10)); TrackGroupingService.IsVariousArtists(tracks).Should().Be(false); TrackGroupingService.LooksLikeSingleRelease(tracks).Should().Be(false); var output = Subject.GroupTracks(tracks); - foreach(var group in output) + foreach (var group in output) { TestLogger.Debug($"*** group {group} ***"); TestLogger.Debug(string.Join("\n", group.LocalTracks.Select(x => x.Path))); diff --git a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/TrackMappingFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/TrackMappingFixture.cs index ce84b1436..c1445bdb9 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/TrackMappingFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Identification/TrackMappingFixture.cs @@ -1,41 +1,38 @@ -using NUnit.Framework; -using NzbDrone.Core.MediaFiles.TrackImport.Identification; -using FluentAssertions; -using NzbDrone.Core.Test.Framework; -using FizzWare.NBuilder; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Music; using System.Collections.Generic; using System.Linq; -using System; +using FizzWare.NBuilder; +using FluentAssertions; +using NUnit.Framework; +using NzbDrone.Core.MediaFiles.TrackImport.Identification; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser; -using NzbDrone.Common.Serializer; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification { [TestFixture] public class TrackMappingFixture : CoreTest { - - private ArtistMetadata artist; + private ArtistMetadata _artist; [SetUp] public void Setup() { - artist = Builder + _artist = Builder .CreateNew() .With(x => x.Name = "artist") .Build(); } - + private List GivenTracks(int count) { - return Builder - .CreateListOfSize(count) - .All() - .With(x => x.ArtistMetadata = artist) - .Build() - .ToList(); + return Builder + .CreateListOfSize(count) + .All() + .With(x => x.ArtistMetadata = _artist) + .Build() + .ToList(); } private ParsedTrackInfo GivenParsedTrackInfo(Track track, AlbumRelease release) @@ -76,7 +73,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification var album = Builder .CreateNew() .With(x => x.Title = title) - .With(x => x.ArtistMetadata = artist) + .With(x => x.ArtistMetadata = _artist) .Build(); var media = Builder @@ -102,19 +99,20 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification var release = GivenAlbumRelease("album", tracks); var localTracks = GivenLocalTracks(tracks, release); - localTracks[2].FileTrackInfo.TrackNumbers = new [] { 2 }; - localTracks[1].FileTrackInfo.TrackNumbers = new [] { 3 }; - localTracks = new [] {0, 2, 1}.Select(x => localTracks[x]).ToList(); + localTracks[2].FileTrackInfo.TrackNumbers = new[] { 2 }; + localTracks[1].FileTrackInfo.TrackNumbers = new[] { 3 }; + localTracks = new[] { 0, 2, 1 }.Select(x => localTracks[x]).ToList(); var result = Subject.MapReleaseTracks(localTracks, tracks); - + result.Mapping .ToDictionary(x => x.Key, y => y.Value.Item1) - .Should().BeEquivalentTo(new Dictionary { - {localTracks[0], tracks[0]}, - {localTracks[1], tracks[2]}, - {localTracks[2], tracks[1]}, - }); + .Should().BeEquivalentTo(new Dictionary + { + { localTracks[0], tracks[0] }, + { localTracks[1], tracks[2] }, + { localTracks[2], tracks[1] }, + }); result.LocalExtra.Should().BeEmpty(); result.MBExtra.Should().BeEmpty(); } @@ -135,11 +133,12 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification result.Mapping .ToDictionary(x => x.Key, y => y.Value.Item1) - .Should().BeEquivalentTo(new Dictionary { - {localTracks[0], tracks[0]}, - {localTracks[1], tracks[1]}, - {localTracks[2], tracks[2]}, - }); + .Should().BeEquivalentTo(new Dictionary + { + { localTracks[0], tracks[0] }, + { localTracks[1], tracks[1] }, + { localTracks[2], tracks[2] }, + }); result.LocalExtra.Should().BeEmpty(); result.MBExtra.Should().BeEmpty(); } @@ -153,13 +152,14 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification localTracks.RemoveAt(1); var result = Subject.MapReleaseTracks(localTracks, tracks); - + result.Mapping .ToDictionary(x => x.Key, y => y.Value.Item1) - .Should().BeEquivalentTo(new Dictionary { - {localTracks[0], tracks[0]}, - {localTracks[1], tracks[2]} - }); + .Should().BeEquivalentTo(new Dictionary + { + { localTracks[0], tracks[0] }, + { localTracks[1], tracks[2] } + }); result.LocalExtra.Should().BeEmpty(); result.MBExtra.Should().BeEquivalentTo(new List { tracks[1] }); } @@ -173,13 +173,14 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Identification tracks.RemoveAt(1); var result = Subject.MapReleaseTracks(localTracks, tracks); - + result.Mapping .ToDictionary(x => x.Key, y => y.Value.Item1) - .Should().BeEquivalentTo(new Dictionary { - {localTracks[0], tracks[0]}, - {localTracks[2], tracks[1]} - }); + .Should().BeEquivalentTo(new Dictionary + { + { localTracks[0], tracks[0] }, + { localTracks[2], tracks[1] } + }); result.LocalExtra.Should().BeEquivalentTo(new List { localTracks[1] }); result.MBExtra.Should().BeEmpty(); } diff --git a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/ImportDecisionMakerFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/ImportDecisionMakerFixture.cs index 90a5a45fd..08c8b957a 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/ImportDecisionMakerFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/ImportDecisionMakerFixture.cs @@ -1,23 +1,23 @@ using System.Collections.Generic; +using System.IO.Abstractions; +using System.IO.Abstractions.TestingHelpers; using System.Linq; +using FizzWare.NBuilder; using FluentAssertions; using Moq; using NUnit.Framework; -using System.IO.Abstractions; using NzbDrone.Core.DecisionEngine; +using NzbDrone.Core.Download; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.TrackImport; +using NzbDrone.Core.MediaFiles.TrackImport.Aggregation; +using NzbDrone.Core.MediaFiles.TrackImport.Identification; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; using NzbDrone.Test.Common; -using FizzWare.NBuilder; -using NzbDrone.Core.Download; -using NzbDrone.Core.MediaFiles.TrackImport.Aggregation; -using NzbDrone.Core.Profiles.Qualities; -using NzbDrone.Core.MediaFiles.TrackImport.Identification; -using System.IO.Abstractions.TestingHelpers; namespace NzbDrone.Core.Test.MediaFiles.TrackImport { @@ -38,7 +38,6 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport private Mock> _albumfail2; private Mock> _albumfail3; - private Mock> _pass1; private Mock> _pass2; private Mock> _pass3; @@ -58,7 +57,6 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport _albumfail2 = new Mock>(); _albumfail3 = new Mock>(); - _pass1 = new Mock>(); _pass2 = new Mock>(); _pass3 = new Mock>(); @@ -74,7 +72,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport _albumfail1.Setup(c => c.IsSatisfiedBy(It.IsAny())).Returns(Decision.Reject("_albumfail1")); _albumfail2.Setup(c => c.IsSatisfiedBy(It.IsAny())).Returns(Decision.Reject("_albumfail2")); _albumfail3.Setup(c => c.IsSatisfiedBy(It.IsAny())).Returns(Decision.Reject("_albumfail3")); - + _pass1.Setup(c => c.IsSatisfiedBy(It.IsAny())).Returns(Decision.Accept()); _pass2.Setup(c => c.IsSatisfiedBy(It.IsAny())).Returns(Decision.Accept()); _pass3.Setup(c => c.IsSatisfiedBy(It.IsAny())).Returns(Decision.Accept()); @@ -104,11 +102,12 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport Mocker.GetMock() .Setup(s => s.Identify(It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) - .Returns((List tracks, Artist artist, Album album, AlbumRelease release, bool newDownload, bool singleRelease, bool includeExisting) => { - var ret = new LocalAlbumRelease(tracks); - ret.AlbumRelease = _albumRelease; - return new List { ret }; - }); + .Returns((List tracks, Artist artist, Album album, AlbumRelease release, bool newDownload, bool singleRelease, bool includeExisting) => + { + var ret = new LocalAlbumRelease(tracks); + ret.AlbumRelease = _albumRelease; + return new List { ret }; + }); Mocker.GetMock() .Setup(c => c.FilterUnchangedFiles(It.IsAny>(), It.IsAny(), It.IsAny())) @@ -269,7 +268,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport .Setup(c => c.Augment(It.IsAny(), It.IsAny())) .Throws(); - GivenAudioFiles(new [] + GivenAudioFiles(new[] { @"C:\Test\Unsorted\The.Office.S03E115.DVDRip.XviD-OSiTV".AsOsAgnostic(), @"C:\Test\Unsorted\The.Office.S03E115.DVDRip.XviD-OSiTV".AsOsAgnostic(), @@ -289,7 +288,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport { GivenSpecifications(_pass1); - GivenAudioFiles(new [] + GivenAudioFiles(new[] { @"C:\Test\Unsorted\The.Office.S03E115.DVDRip.XviD-OSiTV".AsOsAgnostic(), @"C:\Test\Unsorted\The.Office.S03E115.DVDRip.XviD-OSiTV".AsOsAgnostic(), @@ -298,9 +297,10 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport Mocker.GetMock() .Setup(s => s.Identify(It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) - .Returns((List tracks, Artist artist, Album album, AlbumRelease release, bool newDownload, bool singleRelease, bool includeExisting) => { - return new List { new LocalAlbumRelease(tracks) }; - }); + .Returns((List tracks, Artist artist, Album album, AlbumRelease release, bool newDownload, bool singleRelease, bool includeExisting) => + { + return new List { new LocalAlbumRelease(tracks) }; + }); var decisions = Subject.GetImportDecisions(_fileInfos, _artist, FilterFilesType.None, false); @@ -316,7 +316,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport { GivenSpecifications(_pass1); - GivenAudioFiles(new [] + GivenAudioFiles(new[] { @"C:\Test\Unsorted\The.Office.S03E115.DVDRip.XviD-OSiTV".AsOsAgnostic(), @"C:\Test\Unsorted\The.Office.S03E115.DVDRip.XviD-OSiTV".AsOsAgnostic(), @@ -339,7 +339,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport .Setup(c => c.Augment(It.IsAny(), It.IsAny())) .Throws(); - GivenAudioFiles(new [] + GivenAudioFiles(new[] { @"C:\Test\Unsorted\The.Office.S03E115.DVDRip.XviD-OSiTV".AsOsAgnostic() }); diff --git a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Specifications/FreeSpaceSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Specifications/FreeSpaceSpecificationFixture.cs index e7e997378..a470c786d 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Specifications/FreeSpaceSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Specifications/FreeSpaceSpecificationFixture.cs @@ -7,9 +7,9 @@ using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.TrackImport.Specifications; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Specifications @@ -24,7 +24,7 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Specifications [SetUp] public void Setup() { - _rootFolder = @"C:\Test\Music".AsOsAgnostic(); + _rootFolder = @"C:\Test\Music".AsOsAgnostic(); _artist = Builder.CreateNew() .With(s => s.Path = Path.Combine(_rootFolder, "Alice in Chains")) @@ -36,11 +36,11 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Specifications .ToList(); _localTrack = new LocalTrack - { - Path = @"C:\Test\Unsorted\Alice in Chains\Alice in Chains - track1.mp3".AsOsAgnostic(), - Tracks = tracks, - Artist = _artist - }; + { + Path = @"C:\Test\Unsorted\Alice in Chains\Alice in Chains - track1.mp3".AsOsAgnostic(), + Tracks = tracks, + Artist = _artist + }; } private void GivenFileSize(long size) diff --git a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Specifications/NotUnpackingSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Specifications/NotUnpackingSpecificationFixture.cs index fe2de539e..f12a5f967 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Specifications/NotUnpackingSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Specifications/NotUnpackingSpecificationFixture.cs @@ -6,9 +6,9 @@ using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.TrackImport.Specifications; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Specifications diff --git a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Specifications/SameFileSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Specifications/SameFileSpecificationFixture.cs index 073ce9cd5..4fb6d1302 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Specifications/SameFileSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Specifications/SameFileSpecificationFixture.cs @@ -5,9 +5,9 @@ using Marr.Data; using NUnit.Framework; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.TrackImport.Specifications; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Specifications { diff --git a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Specifications/UpgradeSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Specifications/UpgradeSpecificationFixture.cs index b648af0da..55ca5fe33 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Specifications/UpgradeSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/TrackImport/Specifications/UpgradeSpecificationFixture.cs @@ -3,14 +3,14 @@ using FizzWare.NBuilder; using FluentAssertions; using Marr.Data; using NUnit.Framework; +using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.TrackImport.Specifications; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; -using NzbDrone.Core.Configuration; namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Specifications { @@ -159,7 +159,6 @@ namespace NzbDrone.Core.Test.MediaFiles.TrackImport.Specifications Subject.IsSatisfiedBy(_localTrack).Accepted.Should().BeFalse(); } - [Test] public void should_return_false_if_not_a_revision_upgrade_and_prefers_propers() { diff --git a/src/NzbDrone.Core.Test/MediaFiles/UpgradeMediaFileServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/UpgradeMediaFileServiceFixture.cs index 39ab2d558..de69f06de 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/UpgradeMediaFileServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/UpgradeMediaFileServiceFixture.cs @@ -7,9 +7,9 @@ using Moq; using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles @@ -18,22 +18,21 @@ namespace NzbDrone.Core.Test.MediaFiles { private TrackFile _trackFile; private LocalTrack _localTrack; - private string rootPath = @"C:\Test\Music\Artist".AsOsAgnostic(); + private string _rootPath = @"C:\Test\Music\Artist".AsOsAgnostic(); [SetUp] public void Setup() { _localTrack = new LocalTrack(); _localTrack.Artist = new Artist - { - Path = rootPath - }; + { + Path = _rootPath + }; _trackFile = Builder .CreateNew() .Build(); - Mocker.GetMock() .Setup(c => c.FileExists(It.IsAny())) .Returns(true); @@ -56,7 +55,7 @@ namespace NzbDrone.Core.Test.MediaFiles new TrackFile { Id = 1, - Path = Path.Combine(rootPath, @"Season 01\30.rock.s01e01.avi"), + Path = Path.Combine(_rootPath, @"Season 01\30.rock.s01e01.avi"), })) .Build() .ToList(); @@ -71,7 +70,7 @@ namespace NzbDrone.Core.Test.MediaFiles new TrackFile { Id = 1, - Path = Path.Combine(rootPath, @"Season 01\30.rock.s01e01.avi"), + Path = Path.Combine(_rootPath, @"Season 01\30.rock.s01e01.avi"), })) .Build() .ToList(); @@ -85,14 +84,14 @@ namespace NzbDrone.Core.Test.MediaFiles new TrackFile { Id = 1, - Path = Path.Combine(rootPath, @"Season 01\30.rock.s01e01.avi"), + Path = Path.Combine(_rootPath, @"Season 01\30.rock.s01e01.avi"), })) .TheNext(1) .With(e => e.TrackFile = new LazyLoaded( new TrackFile { Id = 2, - Path = Path.Combine(rootPath, @"Season 01\30.rock.s01e02.avi"), + Path = Path.Combine(_rootPath, @"Season 01\30.rock.s01e02.avi"), })) .Build() .ToList(); diff --git a/src/NzbDrone.Core.Test/Messaging/Commands/CommandEqualityComparerFixture.cs b/src/NzbDrone.Core.Test/Messaging/Commands/CommandEqualityComparerFixture.cs index 63a2fd581..5982015a9 100644 --- a/src/NzbDrone.Core.Test/Messaging/Commands/CommandEqualityComparerFixture.cs +++ b/src/NzbDrone.Core.Test/Messaging/Commands/CommandEqualityComparerFixture.cs @@ -36,7 +36,7 @@ namespace NzbDrone.Core.Test.Messaging.Commands [Test] public void should_return_true_when_single_property_matches() { - var command1 = new AlbumSearchCommand { AlbumIds = new List{ 1 } }; + var command1 = new AlbumSearchCommand { AlbumIds = new List { 1 } }; var command2 = new AlbumSearchCommand { AlbumIds = new List { 1 } }; CommandEqualityComparer.Instance.Equals(command1, command2).Should().BeTrue(); @@ -51,12 +51,11 @@ namespace NzbDrone.Core.Test.Messaging.Commands CommandEqualityComparer.Instance.Equals(command1, command2).Should().BeFalse(); } - [Test] public void should_return_false_when_only_one_has_properties() { var command1 = new ArtistSearchCommand(); - var command2 = new ArtistSearchCommand { ArtistId = 2}; + var command2 = new ArtistSearchCommand { ArtistId = 2 }; CommandEqualityComparer.Instance.Equals(command1, command2).Should().BeFalse(); } @@ -108,7 +107,6 @@ namespace NzbDrone.Core.Test.Messaging.Commands CommandEqualityComparer.Instance.Equals(command1, command2).Should().BeTrue(); } - [Test] public void should_return_false_when_commands_list_for_non_primitive_type_dont_match() { diff --git a/src/NzbDrone.Core.Test/Messaging/Commands/CommandExecutorFixture.cs b/src/NzbDrone.Core.Test/Messaging/Commands/CommandExecutorFixture.cs index bb1e6a733..e0f633266 100644 --- a/src/NzbDrone.Core.Test/Messaging/Commands/CommandExecutorFixture.cs +++ b/src/NzbDrone.Core.Test/Messaging/Commands/CommandExecutorFixture.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Concurrent; -using System.Collections.Generic; using System.Threading; using Moq; using NUnit.Framework; @@ -214,5 +212,4 @@ namespace NzbDrone.Core.Test.Messaging.Commands { public override string CompletionMessage => null; } - } diff --git a/src/NzbDrone.Core.Test/Messaging/Commands/CommandQueueFixture.cs b/src/NzbDrone.Core.Test/Messaging/Commands/CommandQueueFixture.cs index f27453095..bd37c938f 100644 --- a/src/NzbDrone.Core.Test/Messaging/Commands/CommandQueueFixture.cs +++ b/src/NzbDrone.Core.Test/Messaging/Commands/CommandQueueFixture.cs @@ -1,15 +1,12 @@ +using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Download; -using NzbDrone.Core.Messaging.Commands; -using NzbDrone.Core.Test.Framework; -using Moq; -using System.Collections.Generic; -using System.Linq; -using FizzWare.NBuilder; using NzbDrone.Core.ImportLists; -using NzbDrone.Core.Update.Commands; +using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Music.Commands; +using NzbDrone.Core.Test.Framework; +using NzbDrone.Core.Update.Commands; namespace NzbDrone.Core.Test.Messaging.Commands { diff --git a/src/NzbDrone.Core.Test/Messaging/Events/EventAggregatorFixture.cs b/src/NzbDrone.Core.Test/Messaging/Events/EventAggregatorFixture.cs index 2251915e8..be457b61f 100644 --- a/src/NzbDrone.Core.Test/Messaging/Events/EventAggregatorFixture.cs +++ b/src/NzbDrone.Core.Test/Messaging/Events/EventAggregatorFixture.cs @@ -12,33 +12,31 @@ namespace NzbDrone.Core.Test.Messaging.Events [TestFixture] public class EventAggregatorFixture : TestBase { - private Mock> HandlerA1; - private Mock> HandlerA2; + private Mock> _handlerA1; + private Mock> _handlerA2; - private Mock> HandlerB1; - private Mock> HandlerB2; - - private Mock> AsyncHandlerA1; + private Mock> _handlerB1; + private Mock> _handlerB2; + private Mock> _asyncHandlerA1; [SetUp] public void Setup() { - HandlerA1 = new Mock>(); - HandlerA2 = new Mock>(); - HandlerB1 = new Mock>(); - HandlerB2 = new Mock>(); + _handlerA1 = new Mock>(); + _handlerA2 = new Mock>(); + _handlerB1 = new Mock>(); + _handlerB2 = new Mock>(); - AsyncHandlerA1 = new Mock>(); + _asyncHandlerA1 = 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 +46,8 @@ namespace NzbDrone.Core.Test.Messaging.Events 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 +55,81 @@ namespace NzbDrone.Core.Test.Messaging.Events { 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(); + /* [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, - }; + 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(new List>()); - Mocker.GetMock() - .Setup(c => c.BuildAll>()) - .Returns(handlers); + Mocker.GetMock() + .Setup(c => c.BuildAll>()) + .Returns(handlers); - var counter = new ConcurrencyCounter(handlers.Count); + 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); - }); + AsyncHandlerA1.Setup(c => c.HandleAsync(It.IsAny())) + .Callback(c => + { + var id = counter.Start(); + Thread.Sleep(1000); + counter.Stop(id); + }); - Subject.PublishEvent(eventA); + Subject.PublishEvent(eventA); - counter.WaitForAllItems(); + counter.WaitForAllItems(); - counter.MaxThreads.Should().Be(3); - }*/ + counter.MaxThreads.Should().Be(3); + }*/ } - public class EventA : IEvent { - } public class EventB : IEvent { - } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/MetadataSource/MetadataRequestBuilderFixture.cs b/src/NzbDrone.Core.Test/MetadataSource/MetadataRequestBuilderFixture.cs index ea2cda29e..ba83ef66c 100644 --- a/src/NzbDrone.Core.Test/MetadataSource/MetadataRequestBuilderFixture.cs +++ b/src/NzbDrone.Core.Test/MetadataSource/MetadataRequestBuilderFixture.cs @@ -1,10 +1,10 @@ using FluentAssertions; using NUnit.Framework; -using NzbDrone.Core.MetadataSource; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Configuration; using NzbDrone.Common.Cloud; using NzbDrone.Common.Http; +using NzbDrone.Core.Configuration; +using NzbDrone.Core.MetadataSource; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.MetadataSource { diff --git a/src/NzbDrone.Core.Test/MetadataSource/SearchArtistComparerFixture.cs b/src/NzbDrone.Core.Test/MetadataSource/SearchArtistComparerFixture.cs index 9a70a3e38..ee432790e 100644 --- a/src/NzbDrone.Core.Test/MetadataSource/SearchArtistComparerFixture.cs +++ b/src/NzbDrone.Core.Test/MetadataSource/SearchArtistComparerFixture.cs @@ -3,8 +3,8 @@ using System.Linq; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.MetadataSource; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; +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 fe5ef827c..5b818ff2e 100644 --- a/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxyFixture.cs +++ b/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxyFixture.cs @@ -2,15 +2,14 @@ using System; using System.Collections.Generic; using System.Linq; using FluentAssertions; +using Moq; using NUnit.Framework; using NzbDrone.Core.Exceptions; using NzbDrone.Core.MetadataSource.SkyHook; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; -using NzbDrone.Test.Common.Categories; -using Moq; -using NzbDrone.Core.Profiles.Metadata; using NzbDrone.Core.MetadataSource.SkyHook.Resource; +using NzbDrone.Core.Music; +using NzbDrone.Core.Profiles.Metadata; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.MetadataSource.SkyHook { @@ -60,11 +59,11 @@ namespace NzbDrone.Core.Test.MetadataSource.SkyHook .Setup(s => s.Exists(It.IsAny())) .Returns(true); } - + public List GivenExampleAlbums() { var result = new List(); - + foreach (var primaryType in PrimaryAlbumType.All) { foreach (var secondaryType in SecondaryAlbumType.All) @@ -73,15 +72,16 @@ namespace NzbDrone.Core.Test.MetadataSource.SkyHook foreach (var releaseStatus in ReleaseStatus.All) { var releaseStatuses = new List { releaseStatus.Name }; - result.Add(new AlbumResource { - Type = primaryType.Name, - SecondaryTypes = secondaryTypes, - ReleaseStatuses = releaseStatuses - }); + result.Add(new AlbumResource + { + Type = primaryType.Name, + SecondaryTypes = secondaryTypes, + ReleaseStatuses = releaseStatuses + }); } } } - + return result; } @@ -100,7 +100,8 @@ namespace NzbDrone.Core.Test.MetadataSource.SkyHook [TestCaseSource(typeof(PrimaryAlbumType), "All")] public void should_filter_albums_by_primary_release_type(PrimaryAlbumType type) { - _metadataProfile.PrimaryAlbumTypes = new List { + _metadataProfile.PrimaryAlbumTypes = new List + { new ProfilePrimaryAlbumTypeItem { PrimaryAlbumType = type, @@ -108,16 +109,16 @@ namespace NzbDrone.Core.Test.MetadataSource.SkyHook } }; - var albums = GivenExampleAlbums(); Subject.FilterAlbums(albums, 1).Select(x => x.Type).Distinct() .Should().BeEquivalentTo(new List { type.Name }); } - + [TestCaseSource(typeof(SecondaryAlbumType), "All")] public void should_filter_albums_by_secondary_release_type(SecondaryAlbumType type) { - _metadataProfile.SecondaryAlbumTypes = new List { + _metadataProfile.SecondaryAlbumTypes = new List + { new ProfileSecondaryAlbumTypeItem { SecondaryAlbumType = type, @@ -128,7 +129,7 @@ namespace NzbDrone.Core.Test.MetadataSource.SkyHook var albums = GivenExampleAlbums(); var filtered = Subject.FilterAlbums(albums, 1); TestLogger.Debug(filtered.Count()); - + filtered.SelectMany(x => x.SecondaryTypes.Select(SkyHookProxy.MapSecondaryTypes)) .Select(x => x.Name) .Distinct() @@ -138,7 +139,8 @@ namespace NzbDrone.Core.Test.MetadataSource.SkyHook [TestCaseSource(typeof(ReleaseStatus), "All")] public void should_filter_albums_by_release_status(ReleaseStatus type) { - _metadataProfile.ReleaseStatuses = new List { + _metadataProfile.ReleaseStatuses = new List + { new ProfileReleaseStatusItem { ReleaseStatus = type, @@ -150,19 +152,19 @@ namespace NzbDrone.Core.Test.MetadataSource.SkyHook Subject.FilterAlbums(albums, 1).SelectMany(x => x.ReleaseStatuses).Distinct() .Should().BeEquivalentTo(new List { type.Name }); } - + [TestCase("12fa3845-7c62-36e5-a8da-8be137155a72", "Hysteria")] public void should_be_able_to_get_album_detail(string mbId, string name) { var details = Subject.GetAlbumInfo(mbId); - - ValidateAlbums(new List {details.Item2}); + + ValidateAlbums(new List { details.Item2 }); details.Item2.Title.Should().Be(name); } - [TestCase("12fa3845-7c62-36e5-a8da-8be137155a72", "3c186b52-ca73-46a3-a8e6-04559bfbb581",1, 13, "Hysteria")] - [TestCase("12fa3845-7c62-36e5-a8da-8be137155a72", "dee9ca6f-4f84-4359-82a9-b75a37ffc316",2, 27,"Hysteria")] + [TestCase("12fa3845-7c62-36e5-a8da-8be137155a72", "3c186b52-ca73-46a3-a8e6-04559bfbb581", 1, 13, "Hysteria")] + [TestCase("12fa3845-7c62-36e5-a8da-8be137155a72", "dee9ca6f-4f84-4359-82a9-b75a37ffc316", 2, 27, "Hysteria")] public void should_be_able_to_get_album_detail_with_release(string mbId, string release, int mediaCount, int trackCount, string name) { var details = Subject.GetAlbumInfo(mbId); @@ -220,20 +222,19 @@ namespace NzbDrone.Core.Test.MetadataSource.SkyHook { ValidateAlbum(album); } - } - + //if atleast one album has title it means parse it working. if (!idOnly) { - albums.Should().Contain(c => !string.IsNullOrWhiteSpace(c.Title)); + albums.Should().Contain(c => !string.IsNullOrWhiteSpace(c.Title)); } } private void ValidateAlbum(Album album) { album.Should().NotBeNull(); - + album.Title.Should().NotBeNullOrWhiteSpace(); album.AlbumType.Should().NotBeNullOrWhiteSpace(); diff --git a/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxySearchFixture.cs b/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxySearchFixture.cs index fede0a9b5..e7bef59a2 100644 --- a/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxySearchFixture.cs +++ b/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxySearchFixture.cs @@ -1,13 +1,13 @@ +using System; +using System.Collections.Generic; using FluentAssertions; +using Moq; using NUnit.Framework; using NzbDrone.Core.MetadataSource.SkyHook; +using NzbDrone.Core.Music; +using NzbDrone.Core.Profiles.Metadata; using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; -using Moq; -using NzbDrone.Core.Profiles.Metadata; -using NzbDrone.Core.Music; -using System.Collections.Generic; -using System; namespace NzbDrone.Core.Test.MetadataSource.SkyHook { @@ -19,7 +19,7 @@ namespace NzbDrone.Core.Test.MetadataSource.SkyHook { UseRealHttp(); - var _metadataProfile = new MetadataProfile + var metadataProfile = new MetadataProfile { Id = 1, PrimaryAlbumTypes = new List @@ -28,7 +28,6 @@ namespace NzbDrone.Core.Test.MetadataSource.SkyHook { PrimaryAlbumType = PrimaryAlbumType.Album, Allowed = true - } }, SecondaryAlbumTypes = new List @@ -51,11 +50,11 @@ namespace NzbDrone.Core.Test.MetadataSource.SkyHook Mocker.GetMock() .Setup(s => s.All()) - .Returns(new List{_metadataProfile}); + .Returns(new List { metadataProfile }); Mocker.GetMock() .Setup(s => s.Get(It.IsAny())) - .Returns(_metadataProfile); + .Returns(metadataProfile); } [TestCase("Coldplay", "Coldplay")] @@ -76,7 +75,6 @@ namespace NzbDrone.Core.Test.MetadataSource.SkyHook ExceptionVerification.IgnoreWarns(); } - [TestCase("Evolve", "Imagine Dragons", "Evolve")] [TestCase("Hysteria", null, "Hysteria")] [TestCase("lidarr:d77df681-b779-3d6d-b66a-3bfd15985e3e", null, "Pyromania")] @@ -103,7 +101,7 @@ namespace NzbDrone.Core.Test.MetadataSource.SkyHook { var result = Subject.SearchForNewArtist(term); result.Should().BeEmpty(); - + ExceptionVerification.IgnoreWarns(); } diff --git a/src/NzbDrone.Core.Test/MusicTests/AddAlbumFixture.cs b/src/NzbDrone.Core.Test/MusicTests/AddAlbumFixture.cs index 44e934e86..165e575ad 100644 --- a/src/NzbDrone.Core.Test/MusicTests/AddAlbumFixture.cs +++ b/src/NzbDrone.Core.Test/MusicTests/AddAlbumFixture.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using FizzWare.NBuilder; using FluentAssertions; @@ -6,11 +7,10 @@ using Moq; using NUnit.Framework; using NzbDrone.Core.Exceptions; using NzbDrone.Core.MetadataSource; -using NzbDrone.Core.Organizer; using NzbDrone.Core.Music; +using NzbDrone.Core.Organizer; using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; -using System; namespace NzbDrone.Core.Test.MusicTests { diff --git a/src/NzbDrone.Core.Test/MusicTests/AddArtistFixture.cs b/src/NzbDrone.Core.Test/MusicTests/AddArtistFixture.cs index 49f101465..fcb2cf28d 100644 --- a/src/NzbDrone.Core.Test/MusicTests/AddArtistFixture.cs +++ b/src/NzbDrone.Core.Test/MusicTests/AddArtistFixture.cs @@ -8,8 +8,8 @@ using Moq; using NUnit.Framework; using NzbDrone.Core.Exceptions; using NzbDrone.Core.MetadataSource; -using NzbDrone.Core.Organizer; using NzbDrone.Core.Music; +using NzbDrone.Core.Organizer; using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; @@ -69,10 +69,10 @@ namespace NzbDrone.Core.Test.MusicTests public void should_have_proper_path() { var newArtist = new Artist - { - ForeignArtistId = "ce09ea31-3d4a-4487-a797-e315175457a0", - RootFolderPath = @"C:\Test\Music" - }; + { + ForeignArtistId = "ce09ea31-3d4a-4487-a797-e315175457a0", + RootFolderPath = @"C:\Test\Music" + }; GivenValidArtist(newArtist.ForeignArtistId); GivenValidPath(); diff --git a/src/NzbDrone.Core.Test/MusicTests/AlbumMonitoredServiceTests/AlbumMonitoredServiceFixture.cs b/src/NzbDrone.Core.Test/MusicTests/AlbumMonitoredServiceTests/AlbumMonitoredServiceFixture.cs index 9d8fd0052..641b87f7b 100644 --- a/src/NzbDrone.Core.Test/MusicTests/AlbumMonitoredServiceTests/AlbumMonitoredServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MusicTests/AlbumMonitoredServiceTests/AlbumMonitoredServiceFixture.cs @@ -5,7 +5,6 @@ using FizzWare.NBuilder; using Moq; using NUnit.Framework; using NzbDrone.Common.Extensions; -using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Music; using NzbDrone.Core.Test.Framework; @@ -29,9 +28,11 @@ namespace NzbDrone.Core.Test.MusicTests.AlbumMonitoredServiceTests .All() .With(e => e.Monitored = true) .With(e => e.ReleaseDate = DateTime.UtcNow.AddDays(-7)) + //Future .TheFirst(1) .With(e => e.ReleaseDate = DateTime.UtcNow.AddDays(7)) + //Future/TBA .TheNext(1) .With(e => e.ReleaseDate = null) @@ -66,7 +67,7 @@ namespace NzbDrone.Core.Test.MusicTests.AlbumMonitoredServiceTests [Test] public void should_be_able_to_monitor_albums_when_passed_in_artist() { - var albumsToMonitor = new List{_albums.First().ForeignAlbumId}; + var albumsToMonitor = new List { _albums.First().ForeignAlbumId }; Subject.SetAlbumMonitoredStatus(_artist, new MonitoringOptions { Monitored = true, AlbumsToMonitor = albumsToMonitor }); @@ -80,7 +81,7 @@ namespace NzbDrone.Core.Test.MusicTests.AlbumMonitoredServiceTests [Test] public void should_be_able_to_monitor_all_albums() { - Subject.SetAlbumMonitoredStatus(_artist, new MonitoringOptions{Monitor = MonitorTypes.All}); + Subject.SetAlbumMonitoredStatus(_artist, new MonitoringOptions { Monitor = MonitorTypes.All }); Mocker.GetMock() .Verify(v => v.UpdateMany(It.Is>(l => l.All(e => e.Monitored)))); diff --git a/src/NzbDrone.Core.Test/MusicTests/AlbumRepositoryTests/AlbumRepositoryFixture.cs b/src/NzbDrone.Core.Test/MusicTests/AlbumRepositoryTests/AlbumRepositoryFixture.cs index 66e82f0bf..78878fc77 100644 --- a/src/NzbDrone.Core.Test/MusicTests/AlbumRepositoryTests/AlbumRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/MusicTests/AlbumRepositoryTests/AlbumRepositoryFixture.cs @@ -1,11 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Linq; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Music; using NzbDrone.Core.Test.Framework; -using System; -using System.Collections.Generic; -using System.Linq; namespace NzbDrone.Core.Test.MusicTests.AlbumRepositoryTests { @@ -29,7 +29,8 @@ namespace NzbDrone.Core.Test.MusicTests.AlbumRepositoryTests Monitored = true, ForeignArtistId = "this is a fake id", Id = 1, - Metadata = new ArtistMetadata { + Metadata = new ArtistMetadata + { Id = 1 } }; @@ -40,7 +41,7 @@ namespace NzbDrone.Core.Test.MusicTests.AlbumRepositoryTests _release = Builder .CreateNew() .With(e => e.Id = 0) - .With(e => e.ForeignReleaseId = "e00e40a3-5ed5-4ed3-9c22-0a8ff4119bdf" ) + .With(e => e.ForeignReleaseId = "e00e40a3-5ed5-4ed3-9c22-0a8ff4119bdf") .With(e => e.Monitored = true) .Build(); @@ -52,7 +53,7 @@ namespace NzbDrone.Core.Test.MusicTests.AlbumRepositoryTests Artist = _artist, ArtistMetadataId = _artist.ArtistMetadataId, AlbumType = "", - AlbumReleases = new List {_release }, + AlbumReleases = new List { _release }, }; _albumRepo.Insert(_album); @@ -75,11 +76,9 @@ namespace NzbDrone.Core.Test.MusicTests.AlbumRepositoryTests ForeignReleaseId = "fake id" } } - }; _albumRepo.Insert(_albumSpecial); - } [Test] @@ -135,15 +134,15 @@ namespace NzbDrone.Core.Test.MusicTests.AlbumRepositoryTests .With(x => x.Title = "Weezer") .With(x => x.CleanTitle = "weezer") .Build(); - + _albumRepo.InsertMany(albums); - + var album = _albumRepo.FindByTitle(_artist.ArtistMetadataId, "Weezer"); - + _albumRepo.All().Should().HaveCount(4); album.Should().BeNull(); } - + [Test] public void should_not_find_album_in_db_by_partial_releaseid() { @@ -162,15 +161,19 @@ namespace NzbDrone.Core.Test.MusicTests.AlbumRepositoryTests .With(x => x.Artist = _artist) .With(x => x.ArtistMetadataId = _artist.ArtistMetadataId) .TheFirst(1) + // next .With(x => x.ReleaseDate = DateTime.UtcNow.AddDays(1)) .TheNext(1) + // another future one .With(x => x.ReleaseDate = DateTime.UtcNow.AddDays(2)) .TheNext(1) + // most recent .With(x => x.ReleaseDate = DateTime.UtcNow.AddDays(-1)) .TheNext(1) + // an older one .With(x => x.ReleaseDate = DateTime.UtcNow.AddDays(-2)) .BuildList(); @@ -183,7 +186,7 @@ namespace NzbDrone.Core.Test.MusicTests.AlbumRepositoryTests { GivenMultipleAlbums(); - var result = _albumRepo.GetNextAlbums(new [] { _artist.ArtistMetadataId }); + var result = _albumRepo.GetNextAlbums(new[] { _artist.ArtistMetadataId }); result.Should().BeEquivalentTo(_albums.Take(1)); } @@ -192,7 +195,7 @@ namespace NzbDrone.Core.Test.MusicTests.AlbumRepositoryTests { GivenMultipleAlbums(); - var result = _albumRepo.GetLastAlbums(new [] { _artist.ArtistMetadataId }); + var result = _albumRepo.GetLastAlbums(new[] { _artist.ArtistMetadataId }); result.Should().BeEquivalentTo(_albums.Skip(2).Take(1)); } } diff --git a/src/NzbDrone.Core.Test/MusicTests/AlbumServiceFixture.cs b/src/NzbDrone.Core.Test/MusicTests/AlbumServiceFixture.cs index ec4641eb6..6faa5ebd1 100644 --- a/src/NzbDrone.Core.Test/MusicTests/AlbumServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MusicTests/AlbumServiceFixture.cs @@ -1,15 +1,9 @@ -using FizzWare.NBuilder; +using System.Collections.Generic; using FluentAssertions; +using Moq; using NUnit.Framework; using NzbDrone.Core.Music; using NzbDrone.Core.Test.Framework; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using NLog; -using Moq; namespace NzbDrone.Core.Test.MusicTests.AlbumRepositoryTests { @@ -23,16 +17,16 @@ namespace NzbDrone.Core.Test.MusicTests.AlbumRepositoryTests { _albums = new List(); _albums.Add(new Album - { - Title = "ANThology", - CleanTitle = "anthology", - }); + { + Title = "ANThology", + CleanTitle = "anthology", + }); _albums.Add(new Album - { - Title = "+", - CleanTitle = "", - }); + { + Title = "+", + CleanTitle = "", + }); Mocker.GetMock() .Setup(s => s.GetAlbumsByArtistMetadataId(It.IsAny())) @@ -42,10 +36,10 @@ namespace NzbDrone.Core.Test.MusicTests.AlbumRepositoryTests private void GivenSimilarAlbum() { _albums.Add(new Album - { - Title = "ANThology2", - CleanTitle = "anthology2", - }); + { + Title = "ANThology2", + CleanTitle = "anthology2", + }); } [TestCase("ANTholog", "ANThology")] diff --git a/src/NzbDrone.Core.Test/MusicTests/ArtistMetadataRepositoryTests/ArtistMetadataRepositoryFixture.cs b/src/NzbDrone.Core.Test/MusicTests/ArtistMetadataRepositoryTests/ArtistMetadataRepositoryFixture.cs index 111e456a6..d26fa1ca6 100644 --- a/src/NzbDrone.Core.Test/MusicTests/ArtistMetadataRepositoryTests/ArtistMetadataRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/MusicTests/ArtistMetadataRepositoryTests/ArtistMetadataRepositoryFixture.cs @@ -1,11 +1,11 @@ using System.Collections.Generic; +using System.Linq; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; using NzbDrone.Common.Extensions; -using System.Linq; +using NzbDrone.Core.Music; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.MusicTests.ArtistRepositoryTests { @@ -22,7 +22,7 @@ namespace NzbDrone.Core.Test.MusicTests.ArtistRepositoryTests _artistMetadataRepo = Mocker.Resolve(); _metadataList = Builder.CreateListOfSize(10).BuildList(); } - + [Test] public void upsert_many_should_insert_list_of_new() { @@ -30,12 +30,12 @@ namespace NzbDrone.Core.Test.MusicTests.ArtistRepositoryTests AllStoredModels.Should().HaveCount(_metadataList.Count); updated.Should().BeTrue(); } - + [Test] public void upsert_many_should_upsert_existing_with_id_0() { - var _clone = _metadataList.JsonClone(); - var updated = _artistMetadataRepo.UpsertMany(_clone); + var clone = _metadataList.JsonClone(); + var updated = _artistMetadataRepo.UpsertMany(clone); updated.Should().BeTrue(); AllStoredModels.Should().HaveCount(_metadataList.Count); @@ -48,11 +48,11 @@ namespace NzbDrone.Core.Test.MusicTests.ArtistRepositoryTests [Test] public void upsert_many_should_upsert_mixed_list_of_old_and_new() { - var _clone = _metadataList.Take(5).ToList().JsonClone(); - var updated = _artistMetadataRepo.UpsertMany(_clone); + var clone = _metadataList.Take(5).ToList().JsonClone(); + var updated = _artistMetadataRepo.UpsertMany(clone); updated.Should().BeTrue(); - AllStoredModels.Should().HaveCount(_clone.Count); + AllStoredModels.Should().HaveCount(clone.Count); updated = _artistMetadataRepo.UpsertMany(_metadataList); updated.Should().BeTrue(); diff --git a/src/NzbDrone.Core.Test/MusicTests/ArtistRepositoryTests/ArtistRepositoryFixture.cs b/src/NzbDrone.Core.Test/MusicTests/ArtistRepositoryTests/ArtistRepositoryFixture.cs index 2338c917a..48b5530cf 100644 --- a/src/NzbDrone.Core.Test/MusicTests/ArtistRepositoryTests/ArtistRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/MusicTests/ArtistRepositoryTests/ArtistRepositoryFixture.cs @@ -1,15 +1,15 @@ +using System; using System.Collections.Generic; +using System.Data.SQLite; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; +using NzbDrone.Common.Extensions; +using NzbDrone.Core.Music; +using NzbDrone.Core.Profiles.Metadata; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; -using NzbDrone.Core.Profiles.Metadata; -using NzbDrone.Common.Extensions; -using System; -using System.Data.SQLite; namespace NzbDrone.Core.Test.MusicTests.ArtistRepositoryTests { @@ -37,9 +37,9 @@ namespace NzbDrone.Core.Test.MusicTests.ArtistRepositoryTests var metadata = Builder.CreateNew() .With(a => a.Id = 0) .With(a => a.Name = name) - .With(a=> a.OldForeignArtistIds = oldIds) + .With(a => a.OldForeignArtistIds = oldIds) .BuildNew(); - + var artist = Builder.CreateNew() .With(a => a.Id = 0) .With(a => a.Metadata = metadata) @@ -77,7 +77,6 @@ namespace NzbDrone.Core.Test.MusicTests.ArtistRepositoryTests ReleaseStatuses = new List() }; - Mocker.Resolve().Insert(profile); Mocker.Resolve().Insert(metaProfile); @@ -87,10 +86,8 @@ namespace NzbDrone.Core.Test.MusicTests.ArtistRepositoryTests Subject.Insert(artist); - StoredModel.QualityProfile.Should().NotBeNull(); StoredModel.MetadataProfile.Should().NotBeNull(); - } [TestCase("The Black Eyed Peas")] @@ -135,11 +132,11 @@ namespace NzbDrone.Core.Test.MusicTests.ArtistRepositoryTests AddArtist(name, "4d7928cd-7ed2-4282-8c29-c0c9f966f1bd"); _artistRepo.All().Should().HaveCount(4); - + var artist = _artistRepo.FindByName(Parser.Parser.CleanArtistName(name)); artist.Should().BeNull(); } - + [Test] public void should_throw_sql_exception_adding_duplicate_artist() { @@ -148,7 +145,7 @@ namespace NzbDrone.Core.Test.MusicTests.ArtistRepositoryTests .With(a => a.Id = 0) .With(a => a.Name = name) .BuildNew(); - + var artist1 = Builder.CreateNew() .With(a => a.Id = 0) .With(a => a.Metadata = metadata) diff --git a/src/NzbDrone.Core.Test/MusicTests/ArtistServiceTests/FindByNameInexactFixture.cs b/src/NzbDrone.Core.Test/MusicTests/ArtistServiceTests/FindByNameInexactFixture.cs index 98409d8ab..8e5b3e4e9 100644 --- a/src/NzbDrone.Core.Test/MusicTests/ArtistServiceTests/FindByNameInexactFixture.cs +++ b/src/NzbDrone.Core.Test/MusicTests/ArtistServiceTests/FindByNameInexactFixture.cs @@ -2,8 +2,8 @@ using System.Collections.Generic; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.MusicTests.ArtistServiceTests { @@ -12,7 +12,7 @@ namespace NzbDrone.Core.Test.MusicTests.ArtistServiceTests public class FindByNameInexactFixture : CoreTest { private List _artists; - + private Artist CreateArtist(string name) { return Builder.CreateNew() @@ -63,11 +63,9 @@ namespace NzbDrone.Core.Test.MusicTests.ArtistServiceTests [TestCase("The Black Peas")] public void should_not_find_artist_in_db_by_ambiguous_name(string name) { - var artist = Subject.FindByNameInexact(name); artist.Should().BeNull(); } - } } diff --git a/src/NzbDrone.Core.Test/MusicTests/ArtistServiceTests/UpdateMultipleArtistFixture.cs b/src/NzbDrone.Core.Test/MusicTests/ArtistServiceTests/UpdateMultipleArtistFixture.cs index 5a8b92124..e9e77e2c2 100644 --- a/src/NzbDrone.Core.Test/MusicTests/ArtistServiceTests/UpdateMultipleArtistFixture.cs +++ b/src/NzbDrone.Core.Test/MusicTests/ArtistServiceTests/UpdateMultipleArtistFixture.cs @@ -5,7 +5,6 @@ using FizzWare.NBuilder; using FluentAssertions; using Moq; using NUnit.Framework; -using NzbDrone.Core.RootFolders; using NzbDrone.Core.Music; using NzbDrone.Core.Organizer; using NzbDrone.Core.Test.Framework; @@ -52,7 +51,6 @@ namespace NzbDrone.Core.Test.MusicTests.ArtistServiceTests .Setup(s => s.BuildPath(It.IsAny(), false)) .Returns((s, u) => Path.Combine(s.RootFolderPath, s.Name)); - Subject.UpdateArtists(_artists, false).ForEach(s => s.Path.Should().StartWith(newRoot)); } diff --git a/src/NzbDrone.Core.Test/MusicTests/EntityFixture.cs b/src/NzbDrone.Core.Test/MusicTests/EntityFixture.cs index ba5fb83b5..b0a7819b8 100644 --- a/src/NzbDrone.Core.Test/MusicTests/EntityFixture.cs +++ b/src/NzbDrone.Core.Test/MusicTests/EntityFixture.cs @@ -1,22 +1,21 @@ +using System.Collections; +using System.Linq; +using System.Reflection; +using AutoFixture; +using Equ; +using FluentAssertions; +using Marr.Data; using NUnit.Framework; using NzbDrone.Common.Extensions; using NzbDrone.Core.Music; using NzbDrone.Test.Common; -using FluentAssertions; -using System.Collections; -using System.Reflection; -using AutoFixture; -using System.Linq; -using Equ; -using Marr.Data; namespace NzbDrone.Core.Test.MusicTests { [TestFixture] public class EntityFixture : LoggingTest { - - Fixture fixture = new Fixture(); + private Fixture _fixture = new Fixture(); private static bool IsNotMarkedAsIgnore(PropertyInfo propertyInfo) { @@ -54,19 +53,20 @@ namespace NzbDrone.Core.Test.MusicTests [Test] public void two_equivalent_artist_metadata_should_be_equal() { - var item1 = fixture.Create(); + var item1 = _fixture.Create(); var item2 = item1.JsonClone(); item1.Should().NotBeSameAs(item2); item1.Should().Be(item2); } - [Test, TestCaseSource(typeof(EqualityPropertySource), "TestCases")] + [Test] + [TestCaseSource(typeof(EqualityPropertySource), "TestCases")] public void two_different_artist_metadata_should_not_be_equal(PropertyInfo prop) { - var item1 = fixture.Create(); + var item1 = _fixture.Create(); var item2 = item1.JsonClone(); - var different = fixture.Create(); + var different = _fixture.Create(); // make item2 different in the property under consideration var differentEntry = prop.GetValue(different); @@ -79,8 +79,8 @@ namespace NzbDrone.Core.Test.MusicTests [Test] public void metadata_and_db_fields_should_replicate_artist_metadata() { - var item1 = fixture.Create(); - var item2 = fixture.Create(); + var item1 = _fixture.Create(); + var item2 = _fixture.Create(); item1.Should().NotBe(item2); @@ -91,7 +91,7 @@ namespace NzbDrone.Core.Test.MusicTests private Track GivenTrack() { - return fixture.Build() + return _fixture.Build() .Without(x => x.AlbumRelease) .Without(x => x.ArtistMetadata) .Without(x => x.TrackFile) @@ -111,7 +111,8 @@ namespace NzbDrone.Core.Test.MusicTests item1.Should().Be(item2); } - [Test, TestCaseSource(typeof(EqualityPropertySource), "TestCases")] + [Test] + [TestCaseSource(typeof(EqualityPropertySource), "TestCases")] public void two_different_tracks_should_not_be_equal(PropertyInfo prop) { var item1 = GivenTrack(); @@ -141,7 +142,7 @@ namespace NzbDrone.Core.Test.MusicTests private AlbumRelease GivenAlbumRelease() { - return fixture.Build() + return _fixture.Build() .Without(x => x.Album) .Without(x => x.Tracks) .Create(); @@ -157,7 +158,8 @@ namespace NzbDrone.Core.Test.MusicTests item1.Should().Be(item2); } - [Test, TestCaseSource(typeof(EqualityPropertySource), "TestCases")] + [Test] + [TestCaseSource(typeof(EqualityPropertySource), "TestCases")] public void two_different_album_releases_should_not_be_equal(PropertyInfo prop) { var item1 = GivenAlbumRelease(); @@ -187,7 +189,7 @@ namespace NzbDrone.Core.Test.MusicTests private Album GivenAlbum() { - return fixture.Build() + return _fixture.Build() .Without(x => x.ArtistMetadata) .Without(x => x.AlbumReleases) .Without(x => x.Artist) @@ -205,7 +207,8 @@ namespace NzbDrone.Core.Test.MusicTests item1.Should().Be(item2); } - [Test, TestCaseSource(typeof(EqualityPropertySource), "TestCases")] + [Test] + [TestCaseSource(typeof(EqualityPropertySource), "TestCases")] public void two_different_albums_should_not_be_equal(PropertyInfo prop) { var item1 = GivenAlbum(); @@ -241,8 +244,8 @@ namespace NzbDrone.Core.Test.MusicTests private Artist GivenArtist() { - return fixture.Build() - .With(x => x.Metadata, new LazyLoaded(fixture.Create())) + return _fixture.Build() + .With(x => x.Metadata, new LazyLoaded(_fixture.Create())) .Without(x => x.QualityProfile) .Without(x => x.MetadataProfile) .Without(x => x.Albums) @@ -261,7 +264,8 @@ namespace NzbDrone.Core.Test.MusicTests item1.Should().Be(item2); } - [Test, TestCaseSource(typeof(EqualityPropertySource), "TestCases")] + [Test] + [TestCaseSource(typeof(EqualityPropertySource), "TestCases")] public void two_different_artists_should_not_be_equal(PropertyInfo prop) { var item1 = GivenArtist(); diff --git a/src/NzbDrone.Core.Test/MusicTests/MoveArtistServiceFixture.cs b/src/NzbDrone.Core.Test/MusicTests/MoveArtistServiceFixture.cs index e13b2f11b..bd448cc16 100644 --- a/src/NzbDrone.Core.Test/MusicTests/MoveArtistServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MusicTests/MoveArtistServiceFixture.cs @@ -5,10 +5,10 @@ using FizzWare.NBuilder; using Moq; using NUnit.Framework; using NzbDrone.Common.Disk; -using NzbDrone.Core.Organizer; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; using NzbDrone.Core.Music.Commands; +using NzbDrone.Core.Organizer; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MusicTests @@ -89,13 +89,15 @@ namespace NzbDrone.Core.Test.MusicTests [Test] public void should_use_destination_path() { - Subject.Execute(_command); Mocker.GetMock() .Verify( - v => v.TransferFolder(_command.SourcePath, _command.DestinationPath, TransferMode.Move, - It.IsAny()), Times.Once()); + v => v.TransferFolder(_command.SourcePath, + _command.DestinationPath, + TransferMode.Move, + It.IsAny()), + Times.Once()); Mocker.GetMock() .Verify(v => v.GetArtistFolder(It.IsAny(), null), Times.Never()); @@ -107,7 +109,6 @@ namespace NzbDrone.Core.Test.MusicTests var artistFolder = "Artist"; var expectedPath = Path.Combine(_bulkCommand.DestinationRootFolder, artistFolder); - Mocker.GetMock() .Setup(s => s.GetArtistFolder(It.IsAny(), null)) .Returns(artistFolder); @@ -116,8 +117,11 @@ namespace NzbDrone.Core.Test.MusicTests Mocker.GetMock() .Verify( - v => v.TransferFolder(_bulkCommand.Artist.First().SourcePath, expectedPath, TransferMode.Move, - It.IsAny()), Times.Once()); + v => v.TransferFolder(_bulkCommand.Artist.First().SourcePath, + expectedPath, + TransferMode.Move, + It.IsAny()), + Times.Once()); } [Test] @@ -127,17 +131,17 @@ namespace NzbDrone.Core.Test.MusicTests .Setup(s => s.FolderExists(It.IsAny())) .Returns(false); - Subject.Execute(_command); Mocker.GetMock() .Verify( - v => v.TransferFolder(_command.SourcePath, _command.DestinationPath, TransferMode.Move, + v => v.TransferFolder(_command.SourcePath, + _command.DestinationPath, + TransferMode.Move, It.IsAny()), Times.Never()); Mocker.GetMock() .Verify(v => v.GetArtistFolder(It.IsAny(), null), Times.Never()); - } } } diff --git a/src/NzbDrone.Core.Test/MusicTests/RefreshAlbumReleaseServiceFixture.cs b/src/NzbDrone.Core.Test/MusicTests/RefreshAlbumReleaseServiceFixture.cs index 9dfaa7af0..b51940d93 100644 --- a/src/NzbDrone.Core.Test/MusicTests/RefreshAlbumReleaseServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MusicTests/RefreshAlbumReleaseServiceFixture.cs @@ -5,13 +5,8 @@ using FizzWare.NBuilder; using Moq; using NUnit.Framework; using NzbDrone.Common.Extensions; -using NzbDrone.Core.Exceptions; -using NzbDrone.Core.MetadataSource; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; -using NzbDrone.Test.Common; -using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.History; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.MusicTests { @@ -25,7 +20,6 @@ namespace NzbDrone.Core.Test.MusicTests [SetUp] public void Setup() { - _release = Builder .CreateNew() .With(s => s.Media = new List { new Medium { Number = 1 } }) @@ -47,7 +41,6 @@ namespace NzbDrone.Core.Test.MusicTests Mocker.GetMock() .Setup(s => s.GetTracksForRefresh(_release.Id, It.IsAny>())) .Returns(_tracks); - } [Test] @@ -72,18 +65,18 @@ namespace NzbDrone.Core.Test.MusicTests var clash = existing.JsonClone(); clash.Id = 100; clash.ForeignReleaseId = clash.ForeignReleaseId + 1; - + clash.Tracks = Builder.CreateListOfSize(10) .All() .With(x => x.AlbumReleaseId = clash.Id) .With(x => x.ArtistMetadata = _metadata) .With(x => x.ArtistMetadataId = _metadata.Id) .BuildList(); - + Mocker.GetMock() .Setup(x => x.GetReleaseByForeignReleaseId(clash.ForeignReleaseId, false)) .Returns(clash); - + Mocker.GetMock() .Setup(x => x.GetTracksForRefresh(It.IsAny(), It.IsAny>())) .Returns(_tracks); @@ -102,7 +95,6 @@ namespace NzbDrone.Core.Test.MusicTests // check that clash gets updated Mocker.GetMock() .Verify(v => v.UpdateMany(It.Is>(s => s.First().ForeignReleaseId == newInfo.ForeignReleaseId))); - } [Test] @@ -141,7 +133,6 @@ namespace NzbDrone.Core.Test.MusicTests Mocker.GetMock() .Verify(v => v.UpdateMany(It.Is>(s => s.First().ForeignReleaseId == newInfo.ForeignReleaseId))); - } } } diff --git a/src/NzbDrone.Core.Test/MusicTests/RefreshAlbumServiceFixture.cs b/src/NzbDrone.Core.Test/MusicTests/RefreshAlbumServiceFixture.cs index fdd4ac8c2..19f6faadb 100644 --- a/src/NzbDrone.Core.Test/MusicTests/RefreshAlbumServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MusicTests/RefreshAlbumServiceFixture.cs @@ -6,28 +6,27 @@ using Moq; using NUnit.Framework; using NzbDrone.Common.Extensions; using NzbDrone.Core.Exceptions; -using NzbDrone.Core.MetadataSource; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; -using NzbDrone.Test.Common; -using NzbDrone.Core.MediaFiles; using NzbDrone.Core.History; +using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.MetadataSource; +using NzbDrone.Core.Music; +using NzbDrone.Core.Test.Framework; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MusicTests { [TestFixture] public class RefreshAlbumServiceFixture : CoreTest { + private readonly List _fakeArtists = new List { new ArtistMetadata() }; + private readonly string _fakeArtistForeignId = "xxx-xxx-xxx"; private Artist _artist; private List _albums; private List _releases; - private readonly string _fakeArtistForeignId = "xxx-xxx-xxx"; - private readonly List _fakeArtists = new List { new ArtistMetadata() }; [SetUp] public void Setup() { - var release = Builder .CreateNew() .With(s => s.Media = new List { new Medium { Number = 1 } }) @@ -37,7 +36,7 @@ namespace NzbDrone.Core.Test.MusicTests .Build(); _releases = new List { release }; - + var album1 = Builder.CreateNew() .With(x => x.ArtistMetadata = Builder.CreateNew().Build()) .With(s => s.Id = 1234) @@ -45,7 +44,7 @@ namespace NzbDrone.Core.Test.MusicTests .With(s => s.AlbumReleases = _releases) .Build(); - _albums = new List{ album1 }; + _albums = new List { album1 }; _artist = Builder.CreateNew() .With(s => s.Albums = _albums) @@ -60,7 +59,7 @@ namespace NzbDrone.Core.Test.MusicTests .Returns(new List { release }); Mocker.GetMock() - .Setup(s => s.UpsertMany(It.IsAny >())) + .Setup(s => s.UpsertMany(It.IsAny>())) .Returns(true); Mocker.GetMock() @@ -116,15 +115,15 @@ namespace NzbDrone.Core.Test.MusicTests clash.Id = 100; clash.ArtistMetadata = existing.ArtistMetadata.Value.JsonClone(); clash.ForeignAlbumId = clash.ForeignAlbumId + 1; - + clash.AlbumReleases = Builder.CreateListOfSize(10) .All().With(x => x.AlbumId = clash.Id) .BuildList(); - + Mocker.GetMock() .Setup(x => x.FindById(clash.ForeignAlbumId)) .Returns(clash); - + Mocker.GetMock() .Setup(x => x.GetReleasesByAlbum(_albums.First().Id)) .Returns(_releases); @@ -145,11 +144,11 @@ namespace NzbDrone.Core.Test.MusicTests GivenNewAlbumInfo(newAlbumInfo); Subject.RefreshAlbumInfo(_albums, null, false, false); - + // check releases moved to clashing album Mocker.GetMock() .Verify(v => v.UpdateMany(It.Is>(x => x.All(y => y.AlbumId == clash.Id) && x.Count == _releases.Count))); - + // check old album is deleted Mocker.GetMock() .Verify(v => v.DeleteMany(It.Is>(x => x.First().ForeignAlbumId == existing.ForeignAlbumId))); @@ -170,11 +169,11 @@ namespace NzbDrone.Core.Test.MusicTests GivenNewAlbumInfo(album); Subject.RefreshAlbumInfo(album, null, false); - + Mocker.GetMock() .Verify(x => x.DeleteAlbum(album.Id, true, false), Times.Once()); - + ExceptionVerification.ExpectedWarns(1); } @@ -184,6 +183,7 @@ namespace NzbDrone.Core.Test.MusicTests var newAlbum = Builder.CreateNew() .With(x => x.ArtistMetadata = Builder.CreateNew().Build()) .Build(); + // this is required because RefreshAlbumInfo will edit the album passed in var albumCopy = Builder.CreateNew() .With(x => x.ArtistMetadata = Builder.CreateNew().Build()) @@ -217,14 +217,14 @@ namespace NzbDrone.Core.Test.MusicTests .Returns(Tuple.Create("dummy string", albumCopy, new List())); Subject.RefreshAlbumInfo(newAlbum, null, false); - + Mocker.GetMock() .Verify(x => x.RefreshEntityInfo(It.Is>(l => l.Count == 7 && l.Count(y => y.Monitored) == 1), It.IsAny>(), It.IsAny(), It.IsAny())); } - + [TestCase(true, true, 1)] [TestCase(true, false, 0)] [TestCase(false, true, 1)] @@ -234,6 +234,7 @@ namespace NzbDrone.Core.Test.MusicTests var newAlbum = Builder.CreateNew() .With(x => x.ArtistMetadata = Builder.CreateNew().Build()) .Build(); + // this is required because RefreshAlbumInfo will edit the album passed in var albumCopy = Builder.CreateNew() .With(x => x.ArtistMetadata = Builder.CreateNew().Build()) @@ -270,13 +271,12 @@ namespace NzbDrone.Core.Test.MusicTests .Returns(Tuple.Create("dummy string", albumCopy, new List())); Subject.RefreshAlbumInfo(newAlbum, null, false); - + Mocker.GetMock() .Verify(x => x.RefreshEntityInfo(It.Is>(l => l.Count == 10 && l.Count(y => y.Monitored) == 1), It.IsAny>(), It.IsAny(), It.IsAny())); - } [Test] @@ -285,6 +285,7 @@ namespace NzbDrone.Core.Test.MusicTests var newAlbum = Builder.CreateNew() .With(x => x.ArtistMetadata = Builder.CreateNew().Build()) .Build(); + // this is required because RefreshAlbumInfo will edit the album passed in var albumCopy = Builder.CreateNew() .With(x => x.ArtistMetadata = Builder.CreateNew().Build()) @@ -325,28 +326,29 @@ namespace NzbDrone.Core.Test.MusicTests .Returns(Tuple.Create("dummy string", albumCopy, new List())); Subject.RefreshAlbumInfo(newAlbum, null, false); - + Mocker.GetMock() .Verify(x => x.RefreshEntityInfo(It.Is>( - l => l.Count == 10 && + l => l.Count == 10 && l.Count(y => y.Monitored) == 1 && l.Single(y => y.Monitored).ForeignReleaseId == "ExistingId2"), It.IsAny>(), It.IsAny(), It.IsAny())); } - + [Test] public void refreshing_album_should_change_monitored_release_if_monitored_release_deleted() { var newAlbum = Builder.CreateNew() .With(x => x.ArtistMetadata = Builder.CreateNew().Build()) .Build(); + // this is required because RefreshAlbumInfo will edit the album passed in var albumCopy = Builder.CreateNew() .With(x => x.ArtistMetadata = Builder.CreateNew().Build()) .Build(); - + // Only existingId1 monitored in skyhook. ExistingId2 is missing var releases = Builder.CreateListOfSize(10) .All() @@ -382,10 +384,10 @@ namespace NzbDrone.Core.Test.MusicTests .Returns(Tuple.Create("dummy string", albumCopy, new List())); Subject.RefreshAlbumInfo(newAlbum, null, false); - + Mocker.GetMock() .Verify(x => x.RefreshEntityInfo(It.Is>( - l => l.Count == 11 && + l => l.Count == 11 && l.Count(y => y.Monitored) == 1 && l.Single(y => y.Monitored).ForeignReleaseId != "ExistingId2"), It.IsAny>(), diff --git a/src/NzbDrone.Core.Test/MusicTests/RefreshArtistServiceFixture.cs b/src/NzbDrone.Core.Test/MusicTests/RefreshArtistServiceFixture.cs index 2f7c1631e..3f1f093e3 100644 --- a/src/NzbDrone.Core.Test/MusicTests/RefreshArtistServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MusicTests/RefreshArtistServiceFixture.cs @@ -4,15 +4,15 @@ using Moq; using NUnit.Framework; using NzbDrone.Common.Extensions; using NzbDrone.Core.Exceptions; +using NzbDrone.Core.History; +using NzbDrone.Core.ImportLists.Exclusions; +using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MetadataSource; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; using NzbDrone.Core.Music.Commands; -using NzbDrone.Test.Common; -using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.History; using NzbDrone.Core.Music.Events; -using NzbDrone.Core.ImportLists.Exclusions; +using NzbDrone.Core.Test.Framework; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MusicTests { @@ -36,7 +36,7 @@ namespace NzbDrone.Core.Test.MusicTests .With(s => s.ForeignAlbumId = "2") .Build(); - _albums = new List {_album1, _album2}; + _albums = new List { _album1, _album2 }; _remoteAlbums = _albums.JsonClone(); _remoteAlbums.ForEach(x => x.Id = 0); @@ -77,7 +77,7 @@ namespace NzbDrone.Core.Test.MusicTests .Setup(s => s.GetArtistInfo(_artist.ForeignArtistId, _artist.MetadataProfileId)) .Returns(artist); } - + private void GivenArtistFiles() { Mocker.GetMock() @@ -121,7 +121,8 @@ namespace NzbDrone.Core.Test.MusicTests { var newArtistInfo = _artist.JsonClone(); newArtistInfo.Metadata = _artist.Metadata.Value.JsonClone(); - newArtistInfo.Metadata.Value.Images = new List { + newArtistInfo.Metadata.Value.Images = new List + { new MediaCover.MediaCover(MediaCover.MediaCoverTypes.Logo, "dummy") }; newArtistInfo.Albums = _remoteAlbums; @@ -146,25 +147,25 @@ namespace NzbDrone.Core.Test.MusicTests Mocker.GetMock() .Verify(v => v.UpdateArtist(It.IsAny()), Times.Never()); - + Mocker.GetMock() .Verify(v => v.DeleteArtist(It.IsAny(), It.IsAny(), It.IsAny()), Times.Once()); ExceptionVerification.ExpectedErrors(1); ExceptionVerification.ExpectedWarns(1); } - + [Test] public void should_log_error_but_not_delete_if_musicbrainz_id_not_found_and_artist_has_files() { GivenArtistFiles(); GivenAlbumsForRefresh(new List()); - + Subject.Execute(new RefreshArtistCommand(_artist.Id)); Mocker.GetMock() .Verify(v => v.UpdateArtist(It.IsAny()), Times.Never()); - + Mocker.GetMock() .Verify(v => v.DeleteArtist(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); @@ -248,7 +249,7 @@ namespace NzbDrone.Core.Test.MusicTests Mocker.GetMock(MockBehavior.Strict) .InSequence(seq) .Setup(x => x.DeleteArtist(existing.Id, It.IsAny(), false)); - + Mocker.GetMock(MockBehavior.Strict) .InSequence(seq) .Setup(x => x.UpdateArtist(It.Is(a => a.Id == clash.Id))) diff --git a/src/NzbDrone.Core.Test/MusicTests/RefreshTrackServiceFixture.cs b/src/NzbDrone.Core.Test/MusicTests/RefreshTrackServiceFixture.cs index 7ff5a21f0..ceb928a35 100644 --- a/src/NzbDrone.Core.Test/MusicTests/RefreshTrackServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MusicTests/RefreshTrackServiceFixture.cs @@ -5,9 +5,9 @@ using FizzWare.NBuilder; using Moq; using NUnit.Framework; using NzbDrone.Common.Extensions; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Music; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.MusicTests { @@ -49,7 +49,6 @@ namespace NzbDrone.Core.Test.MusicTests .Verify(v => v.SyncTags(It.Is>(x => x.Count == 1 && x[0].AlbumRelease != null && x[0].AlbumRelease.IsLoaded == true))); - } } } diff --git a/src/NzbDrone.Core.Test/MusicTests/ShouldRefreshAlbumFixture.cs b/src/NzbDrone.Core.Test/MusicTests/ShouldRefreshAlbumFixture.cs index 8299f0539..99361dde8 100644 --- a/src/NzbDrone.Core.Test/MusicTests/ShouldRefreshAlbumFixture.cs +++ b/src/NzbDrone.Core.Test/MusicTests/ShouldRefreshAlbumFixture.cs @@ -1,5 +1,4 @@ using System; -using System.Linq; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; @@ -12,12 +11,12 @@ namespace NzbDrone.Core.Test.MusicTests public class ShouldRefreshAlbumFixture : TestBase { private Album _album; - + [SetUp] public void Setup() { _album = Builder.CreateNew() - .With(e=>e.ReleaseDate = DateTime.Today.AddDays(-100)) + .With(e => e.ReleaseDate = DateTime.Today.AddDays(-100)) .Build(); } diff --git a/src/NzbDrone.Core.Test/MusicTests/ShouldRefreshArtistFixture.cs b/src/NzbDrone.Core.Test/MusicTests/ShouldRefreshArtistFixture.cs index fee0024f6..33ca92cc7 100644 --- a/src/NzbDrone.Core.Test/MusicTests/ShouldRefreshArtistFixture.cs +++ b/src/NzbDrone.Core.Test/MusicTests/ShouldRefreshArtistFixture.cs @@ -12,7 +12,7 @@ namespace NzbDrone.Core.Test.MusicTests public class ShouldRefreshArtistFixture : TestBase { private Artist _artist; - + [SetUp] public void Setup() { diff --git a/src/NzbDrone.Core.Test/NotificationTests/NotificationBaseFixture.cs b/src/NzbDrone.Core.Test/NotificationTests/NotificationBaseFixture.cs index a7898e103..0dadac30f 100644 --- a/src/NzbDrone.Core.Test/NotificationTests/NotificationBaseFixture.cs +++ b/src/NzbDrone.Core.Test/NotificationTests/NotificationBaseFixture.cs @@ -2,9 +2,9 @@ using System; using FluentAssertions; using FluentValidation.Results; using NUnit.Framework; +using NzbDrone.Core.Music; using NzbDrone.Core.Notifications; using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Music; 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 @@ namespace NzbDrone.Core.Test.NotificationTests } } - class TestNotificationWithOnReleaseImport : NotificationBase + private class TestNotificationWithOnReleaseImport : NotificationBase { public override string Name => "TestNotification"; public override string Link => ""; - public override ValidationResult Test() { throw new NotImplementedException(); @@ -36,15 +35,13 @@ namespace NzbDrone.Core.Test.NotificationTests { 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(); @@ -86,18 +83,15 @@ namespace NzbDrone.Core.Test.NotificationTests } } - class TestNotificationWithNoEvents : NotificationBase + private class TestNotificationWithNoEvents : NotificationBase { public override string Name => "TestNotification"; public override string Link => ""; - public override ValidationResult Test() { throw new NotImplementedException(); } - - } [Test] @@ -127,7 +121,6 @@ namespace NzbDrone.Core.Test.NotificationTests notification.SupportsOnTrackRetag.Should().BeTrue(); } - [Test] public void should_support_none_if_none_are_implemented() { @@ -143,5 +136,4 @@ namespace NzbDrone.Core.Test.NotificationTests notification.SupportsOnTrackRetag.Should().BeFalse(); } } - } diff --git a/src/NzbDrone.Core.Test/NotificationTests/SynologyIndexerFixture.cs b/src/NzbDrone.Core.Test/NotificationTests/SynologyIndexerFixture.cs index 08df42c62..a241199e1 100644 --- a/src/NzbDrone.Core.Test/NotificationTests/SynologyIndexerFixture.cs +++ b/src/NzbDrone.Core.Test/NotificationTests/SynologyIndexerFixture.cs @@ -1,13 +1,13 @@ using System.Collections.Generic; +using System.IO; using Moq; using NUnit.Framework; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Music; using NzbDrone.Core.Notifications; using NzbDrone.Core.Notifications.Synology; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; using NzbDrone.Test.Common; -using System.IO; namespace NzbDrone.Core.Test.NotificationTests { @@ -16,14 +16,14 @@ namespace NzbDrone.Core.Test.NotificationTests { private Artist _artist; private AlbumDownloadMessage _upgrade; - private string rootPath = @"C:\Test\".AsOsAgnostic(); + private string _rootPath = @"C:\Test\".AsOsAgnostic(); [SetUp] public void SetUp() { _artist = new Artist() { - Path = rootPath, + Path = _rootPath, }; _upgrade = new AlbumDownloadMessage() @@ -34,20 +34,19 @@ namespace NzbDrone.Core.Test.NotificationTests { new TrackFile { - Path = Path.Combine(rootPath, "file1.S01E01E02.mkv") + Path = Path.Combine(_rootPath, "file1.S01E01E02.mkv") } - }, OldFiles = new List { new TrackFile { - Path = Path.Combine(rootPath, "file1.S01E01.mkv") + Path = Path.Combine(_rootPath, "file1.S01E01.mkv") }, new TrackFile { - Path = Path.Combine(rootPath, "file1.S01E02.mkv") + Path = Path.Combine(_rootPath, "file1.S01E02.mkv") } } }; @@ -56,7 +55,7 @@ namespace NzbDrone.Core.Test.NotificationTests { Settings = new SynologyIndexerSettings { - UpdateLibrary = true + UpdateLibrary = true } }; } diff --git a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/GetArtistPathFixture.cs b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/GetArtistPathFixture.cs index 95d47c801..4340555e5 100644 --- a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/GetArtistPathFixture.cs +++ b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/GetArtistPathFixture.cs @@ -3,10 +3,10 @@ using System.Linq; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; +using NzbDrone.Core.Music; using NzbDrone.Core.Notifications.Xbmc; using NzbDrone.Core.Notifications.Xbmc.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.NotificationTests.Xbmc { @@ -26,9 +26,9 @@ namespace NzbDrone.Core.Test.NotificationTests.Xbmc _xbmcArtist = Builder.CreateListOfSize(3) .All() - .With(s => s.MusicbrainzArtistId = new List{"0"}) + .With(s => s.MusicbrainzArtistId = new List { "0" }) .TheFirst(1) - .With(s => s.MusicbrainzArtistId = new List {MB_ID.ToString()}) + .With(s => s.MusicbrainzArtistId = new List { MB_ID.ToString() }) .Build() .ToList(); @@ -41,9 +41,9 @@ namespace NzbDrone.Core.Test.NotificationTests.Xbmc { _artist = new Artist { - ForeignArtistId = MB_ID, - Name = "Artist" - }; + ForeignArtistId = MB_ID, + Name = "Artist" + }; } private void GivenMatchingTitle() @@ -61,7 +61,7 @@ namespace NzbDrone.Core.Test.NotificationTests.Xbmc { ForeignArtistId = "1000", Name = "Does not exist" - }; + }; } [Test] diff --git a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/OnReleaseImportFixture.cs b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/OnReleaseImportFixture.cs index 56b80b878..6fed550f5 100644 --- a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/OnReleaseImportFixture.cs +++ b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/OnReleaseImportFixture.cs @@ -4,10 +4,10 @@ using FizzWare.NBuilder; using Moq; using NUnit.Framework; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Music; using NzbDrone.Core.Notifications; using NzbDrone.Core.Notifications.Xbmc; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.NotificationTests.Xbmc { @@ -15,7 +15,7 @@ namespace NzbDrone.Core.Test.NotificationTests.Xbmc public class OnReleaseImportFixture : CoreTest { private AlbumDownloadMessage _albumDownloadMessage; - + [SetUp] public void Setup() { @@ -33,9 +33,9 @@ namespace NzbDrone.Core.Test.NotificationTests.Xbmc Subject.Definition = new NotificationDefinition(); Subject.Definition.Settings = new XbmcSettings - { - UpdateLibrary = true - }; + { + UpdateLibrary = true + }; } private void GivenOldFiles() @@ -45,10 +45,10 @@ namespace NzbDrone.Core.Test.NotificationTests.Xbmc .ToList(); Subject.Definition.Settings = new XbmcSettings - { - UpdateLibrary = true, - CleanLibrary = true - }; + { + UpdateLibrary = true, + CleanLibrary = true + }; } [Test] diff --git a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/UpdateFixture.cs b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/UpdateFixture.cs index 5a8333f1c..852a7173a 100644 --- a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/UpdateFixture.cs +++ b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/UpdateFixture.cs @@ -3,10 +3,10 @@ using System.Linq; using FizzWare.NBuilder; using Moq; using NUnit.Framework; +using NzbDrone.Core.Music; using NzbDrone.Core.Notifications.Xbmc; using NzbDrone.Core.Notifications.Xbmc.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.NotificationTests.Xbmc { @@ -25,7 +25,7 @@ namespace NzbDrone.Core.Test.NotificationTests.Xbmc _xbmcArtist = Builder.CreateListOfSize(3) .TheFirst(1) - .With(s => s.MusicbrainzArtistId = new List { MB_ID.ToString()}) + .With(s => s.MusicbrainzArtistId = new List { MB_ID.ToString() }) .TheNext(2) .With(s => s.MusicbrainzArtistId = new List()) .Build() @@ -61,10 +61,10 @@ namespace NzbDrone.Core.Test.NotificationTests.Xbmc .With(s => s.Name = "Not Shawn Desman") .Build(); - Subject.Update(_settings, fakeArtist); + Subject.Update(_settings, fakeArtist); - 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/BuildFilePathFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/BuildFilePathFixture.cs index 0af5aad66..f76c1c262 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/BuildFilePathFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/BuildFilePathFixture.cs @@ -1,8 +1,8 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; -using NzbDrone.Core.Organizer; using NzbDrone.Core.Music; +using NzbDrone.Core.Organizer; using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; @@ -12,15 +12,15 @@ namespace NzbDrone.Core.Test.OrganizerTests public class BuildFilePathFixture : 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); } [Test] @@ -39,7 +39,7 @@ namespace NzbDrone.Core.Test.OrganizerTests .With(s => s.Title = "Fake: Album") .Build(); - namingConfig.AlbumFolderFormat = "{Artist Name} {Album Title}"; + _namingConfig.AlbumFolderFormat = "{Artist Name} {Album Title}"; Subject.BuildTrackFilePath(fakeArtist, fakeAlbum, filename, ".flac").Should().Be(expectedPath.AsOsAgnostic()); } diff --git a/src/NzbDrone.Core.Test/OrganizerTests/CleanFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/CleanFixture.cs index 9e8600104..084123c52 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/CleanFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/CleanFixture.cs @@ -14,6 +14,5 @@ namespace NzbDrone.Core.Test.OrganizerTests { FileNameBuilder.CleanFileName(name).Should().Be(expectedName); } - } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/CleanTitleFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/CleanTitleFixture.cs index 8d1389c18..f6a5fd350 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/CleanTitleFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/CleanTitleFixture.cs @@ -4,10 +4,10 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Music; using NzbDrone.Core.Organizer; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { diff --git a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/FileNameBuilderFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/FileNameBuilderFixture.cs index f08dec808..a8ee23d2c 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/FileNameBuilderFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/FileNameBuilderFixture.cs @@ -5,10 +5,10 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Music; using NzbDrone.Core.Organizer; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { @@ -30,7 +30,8 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests _artist = Builder .CreateNew() .With(s => s.Name = "Linkin Park") - .With(s => s.Metadata = new ArtistMetadata { + .With(s => s.Metadata = new ArtistMetadata + { Disambiguation = "US Rock Band", Name = "Linkin Park" }) @@ -54,11 +55,9 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests .With(s => s.Disambiguation = "The Best Album") .Build(); - _namingConfig = NamingConfig.Default; _namingConfig.RenameTracks = true; - Mocker.GetMock() .Setup(c => c.GetConfig()).Returns(_namingConfig); @@ -72,14 +71,15 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests _trackFile = Builder.CreateNew() .With(e => e.Quality = new QualityModel(Quality.MP3_256)) .With(e => e.ReleaseGroup = "LidarrTest") - .With(e => e.MediaInfo = new Parser.Model.MediaInfoModel { + .With(e => e.MediaInfo = new Parser.Model.MediaInfoModel + { AudioBitrate = 320, AudioBits = 16, AudioChannels = 2, AudioFormat = "Flac Audio", AudioSampleRate = 44100 }).Build(); - + Mocker.GetMock() .Setup(v => v.Get(Moq.It.IsAny())) .Returns(v => Quality.DefaultQualityDefinitions.First(c => c.Quality == v)); @@ -100,7 +100,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { _namingConfig.StandardTrackFormat = "{Artist Name}"; - Subject.BuildTrackFileName(new List {_track1}, _artist, _album, _trackFile) + Subject.BuildTrackFileName(new List { _track1 }, _artist, _album, _trackFile) .Should().Be("Linkin Park"); } @@ -109,7 +109,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { _namingConfig.StandardTrackFormat = "{Artist_Name}"; - Subject.BuildTrackFileName(new List {_track1}, _artist, _album, _trackFile) + Subject.BuildTrackFileName(new List { _track1 }, _artist, _album, _trackFile) .Should().Be("Linkin_Park"); } @@ -118,7 +118,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { _namingConfig.StandardTrackFormat = "{Artist.Name}"; - Subject.BuildTrackFileName(new List {_track1}, _artist, _album, _trackFile) + Subject.BuildTrackFileName(new List { _track1 }, _artist, _album, _trackFile) .Should().Be("Linkin.Park"); } @@ -127,7 +127,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { _namingConfig.StandardTrackFormat = "{Artist-Name}"; - Subject.BuildTrackFileName(new List {_track1}, _artist, _album, _trackFile) + Subject.BuildTrackFileName(new List { _track1 }, _artist, _album, _trackFile) .Should().Be("Linkin-Park"); } @@ -136,7 +136,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { _namingConfig.StandardTrackFormat = "{ARTIST NAME}"; - Subject.BuildTrackFileName(new List {_track1}, _artist, _album, _trackFile) + Subject.BuildTrackFileName(new List { _track1 }, _artist, _album, _trackFile) .Should().Be("LINKIN PARK"); } @@ -154,7 +154,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { _namingConfig.StandardTrackFormat = "{artist name}"; - Subject.BuildTrackFileName(new List {_track1}, _artist, _album, _trackFile) + Subject.BuildTrackFileName(new List { _track1 }, _artist, _album, _trackFile) .Should().Be("linkin park"); } @@ -273,7 +273,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { _namingConfig.StandardTrackFormat = "{Track Title}"; - Subject.BuildTrackFileName(new List {_track1}, _artist, _album, _trackFile) + Subject.BuildTrackFileName(new List { _track1 }, _artist, _album, _trackFile) .Should().Be("City Sushi"); } @@ -383,7 +383,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { _namingConfig.StandardTrackFormat = "{Artist Name} - {Album Title} - {track:00} - {Track Title} [{Quality Title}]"; - Subject.BuildTrackFileName(new List {_track1}, _artist, _album, _trackFile) + Subject.BuildTrackFileName(new List { _track1 }, _artist, _album, _trackFile) .Should().Be("Linkin Park - Hybrid Theory - 06 - City Sushi [MP3-256]"); } @@ -396,7 +396,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests Subject.BuildTrackFileName(new List { _track1 }, _artist, _album, _trackFile) .Should().Be(Path.GetFileNameWithoutExtension(_trackFile.Path)); } - + [Test] public void use_file_name_when_sceneName_is_not_null() { @@ -486,7 +486,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests public void should_include_affixes_if_value_not_empty() { _namingConfig.StandardTrackFormat = "{Artist.Name}.{track:00}{_Track.Title_}{Quality.Title}"; - + Subject.BuildTrackFileName(new List { _track1 }, _artist, _album, _trackFile) .Should().Be("Linkin.Park.06_City.Sushi_MP3-256"); } @@ -589,8 +589,6 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests .Should().Be(string.Format("MP3-256{0}City{0}Sushi", separator)); } - - [Test] public void should_be_able_to_use_original_filename() { diff --git a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/TitleTheFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/TitleTheFixture.cs index 8b54bd11a..acc7440e6 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/TitleTheFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/TitleTheFixture.cs @@ -4,10 +4,10 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Music; using NzbDrone.Core.Organizer; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { @@ -33,7 +33,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests .CreateNew() .With(s => s.Title = "Anthology") .Build(); - + _release = Builder .CreateNew() .With(s => s.Media = new List { new Medium { Number = 1 } }) @@ -68,6 +68,7 @@ namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests [TestCase("The Amazing Race (Latin America)", "Amazing Race, The (Latin America)")] [TestCase("The Rat Pack (A&E)", "Rat Pack, The (A&E)")] [TestCase("The Climax: I (Almost) Got Away With It (2016)", "Climax- I (Almost) Got Away With It, The (2016)")] + //[TestCase("", "")] public void should_get_expected_title_back(string name, string expected) { diff --git a/src/NzbDrone.Core.Test/OrganizerTests/GetAlbumFolderFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/GetAlbumFolderFixture.cs index dec3d8318..359b016b5 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/GetAlbumFolderFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/GetAlbumFolderFixture.cs @@ -1,35 +1,35 @@ using FluentAssertions; using NUnit.Framework; +using NzbDrone.Core.Music; using NzbDrone.Core.Organizer; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.OrganizerTests { [TestFixture] public class GetAlbumFolderFixture : 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("Venture Bros.", "Today", "{Artist.Name}.{Album.Title}", "Venture.Bros.Today")] [TestCase("Venture Bros.", "Today", "{Artist Name} {Album Title}", "Venture Bros. Today")] public void should_use_albumFolderFormat_to_build_folder_name(string artistName, string albumTitle, string format, string expected) { - namingConfig.AlbumFolderFormat = format; + _namingConfig.AlbumFolderFormat = format; var artist = new Artist { Name = artistName }; var album = new Album { Title = albumTitle }; - Subject.GetAlbumFolder(artist, album, namingConfig).Should().Be(expected); + Subject.GetAlbumFolder(artist, album, _namingConfig).Should().Be(expected); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/OrganizerTests/GetArtistFolderFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/GetArtistFolderFixture.cs index 1a9a2b400..0c84ddd7a 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/GetArtistFolderFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/GetArtistFolderFixture.cs @@ -1,8 +1,8 @@ using FluentAssertions; using NUnit.Framework; +using NzbDrone.Core.Music; using NzbDrone.Core.Organizer; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.OrganizerTests { @@ -10,15 +10,15 @@ namespace NzbDrone.Core.Test.OrganizerTests public class GetArtistFolderFixture : 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("Avenged Sevenfold", "{Artist Name}", "Avenged Sevenfold")] @@ -29,11 +29,11 @@ namespace NzbDrone.Core.Test.OrganizerTests [TestCase("Avenged Sevenfold", ".{Artist.Name}.", "Avenged.Sevenfold")] public void should_use_artistFolderFormat_to_build_folder_name(string artistName, string format, string expected) { - namingConfig.ArtistFolderFormat = format; + _namingConfig.ArtistFolderFormat = format; var artist = new Artist { Name = artistName }; Subject.GetArtistFolder(artist).Should().Be(expected); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/ParserTests/ArtistTitleInfoFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ArtistTitleInfoFixture.cs index 1fab6f605..54623599c 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ArtistTitleInfoFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ArtistTitleInfoFixture.cs @@ -7,8 +7,7 @@ namespace NzbDrone.Core.Test.ParserTests [TestFixture] public class ArtistTitleInfoFixture : CoreTest { - - // TODO: Redo this test and parsed info for Albums which do have a year association + // TODO: Redo this test and parsed info for Albums which do have a year association [Test] [Ignore("Artist Don't have year association thus we dont use this currently")] public void should_have_year_zero_when_title_doesnt_have_a_year() diff --git a/src/NzbDrone.Core.Test/ParserTests/CrapParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/CrapParserFixture.cs index 1a0493273..e5674bcdb 100644 --- a/src/NzbDrone.Core.Test/ParserTests/CrapParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/CrapParserFixture.cs @@ -1,13 +1,12 @@ using System; +using System.Text; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; -using System.Text; namespace NzbDrone.Core.Test.ParserTests { - [TestFixture] public class CrapParserFixture : CoreTest { @@ -53,7 +52,9 @@ namespace NzbDrone.Core.Test.ParserTests hash = BitConverter.ToString(hashData).Replace("-", ""); if (Parser.Parser.ParseAlbumTitle(hash) == null) + { success++; + } } success.Should().Be(repetitions); @@ -79,7 +80,9 @@ namespace NzbDrone.Core.Test.ParserTests } if (Parser.Parser.ParseAlbumTitle(hash.ToString()) == null) + { success++; + } } success.Should().Be(repetitions); diff --git a/src/NzbDrone.Core.Test/ParserTests/FingerprintingServiceFixture.cs b/src/NzbDrone.Core.Test/ParserTests/FingerprintingServiceFixture.cs index 6f6508f4f..eafe6837b 100644 --- a/src/NzbDrone.Core.Test/ParserTests/FingerprintingServiceFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/FingerprintingServiceFixture.cs @@ -43,8 +43,7 @@ namespace NzbDrone.Core.Test.ParserTests v.Url.Equals(new HttpUri("https://api.acoustid.org/v2/lookup")) && v.Headers.Contains(new KeyValuePair("Content-Encoding", "gzip")) && v.Headers.ContentType == "application/x-www-form-urlencoded" && - Encoding.UTF8.GetString(v.ContentData.Decompress()) == response.Request - ))) + Encoding.UTF8.GetString(v.ContentData.Decompress()) == response.Request))) .Returns(r => new HttpResponse(new HttpResponse(r, new HttpHeader(), response.Response))); } } @@ -85,13 +84,13 @@ FINGERPRINT=AQAHJlMURlEURcgP6cwRD43Y4Ptw9FowncWPWkf6GB9-JYdP9OgJHw8u4Apw4SsOHMdx result.Duration.Should().Be(229.29); result.Fingerprint.Should().Be("AQAHJlMURlEURcgP6cwRD43Y4Ptw9FowncWPWkf6GB9-JYdP9OgJHw8u4Apw4SsOHMdxHAfwHIfYET_0HiZ55MfxNCm8Hj-mRM8KLlXwIzqS-Que_Cg7NEseE_2j4DUjJBOvI08UNNUufEd5NM-OHzmSUZsO58er7nhUeN6EK3HYwhe0H-fxXEFzlOSHJwpj3MevID7kHyqVqBH6zEI6GzmSs4HTDz4j9DjxKHDvpLiOH7l4iFUWRXiiqtCJmMqNPmiAZEyY5AgTLclxmSWuwJ-O33jz4KdwHt-PsDHRjBNyCQ_-KcGPhoePsJNyiJOiI-5VPKMj_McvfNQRUkyiImEzAv2Ckxb-RUJ-CVpGhMYnB5em4scvHFeuoU7DwHugT8fRecPVpMF5_Cb8jNvw4n_wJ6iV4xcSHuFxKcfTBhVF5uiPA6OSoWQP5x_6BX-5YDoaJT_OLA3e0Ifr4D2SH2EYB-WShLiE6plg5U2G6jlOSgy-G8-Rk0XD7yiP4DyPfcejiQ2aH9WVHKeOJ5eQP9CeKEfD44zw45kj_NAQJmIWfMTPCJF048IPPTtcB_GP_2ieFydyxYXGvUgffIO1D96SHW10vEeYI9mNR-qLhnpwfYHz49KR8ijnol58pDGLKWuF4wvKTUGjrE-Q79COdFyI8Aze4C70LMP24-YKJLtSeCHqajJ6e2g0qsdzBd94RNdxHY80oomYocdB5hNiUrGIVtrhJ0f4CY-Y48yOF5rFI93sgNF2hNRhTSk65odGaUhJClc5ArOGdi8-oz_SzaqQ3MKV63DkGX8NT07wVcdf5MmO5Av8C9dOONGIS_mRS7gO8fjhLNMFbQqq4zF0jRPir2j2Y9_xH5Z-_EFiHWE-oaePh8JN3CsaiYgkGvrR_OgVaI2iHv_gTLsQaTeuZ8K5HUdMCWUlHpLIIFyO8TiNO2nQOHzwLkfYQg2RHxXlUfDxHX-MO9Pxwc8J90JSEzmDJk-Ji0cpZanw44mOWpKEkkHDsUFkZsfNaJCOqDvK_fg-9NHx5UHtFGEOPUeu47hw4dzwH22Nc9pgK8dZhJ-h8wipwyS8Dw8cZ0evC8kZJcgrHT22jsfhH_QCv4jMHNp25NLx6Hh4tEtaePzgcNHxDOkYQ3tCxBsvPFKOfyzCB-L5IHyCpzhFHo9zvMeP5vrQbdzwK8N_hFG6F0mdo2GOJ4yxM0bJRFaGH3WyHUdzHWWe4uoH8hWS8EGOGuUSBZ-E6w7sZsKpIId-IzyDptLxhD76GpfxNDHSkdCTS0JMFS-8Rh6e48c6Hv2O8CG05MinRcUX9A0cKoSv4Ts8KbSQbCXyDDeDZ_mKUrwHP8tRi8d94UcX3ImMLzq8o3-DnFXwHG2UJ_Au6FlwNLgOXU_xakKv4zp8VMeN_vBz9OCbQzsFP7h8PB96Df8llNJSWI8KfVkqZMcPaw5ePEgf6HKQjj2YTRmOxslyTJ-K_kj3Qj9M6TjCM33QixGcX8PzHNfxDOfhMx2SHflz_Dr-K6hSKVLQ7MSjII-UQ9fQ53Bi6ahMoz5jNA304xDz7RjTI08eXKeChzmeDeUJfw7OEPVGnB_yoz_M6sZj8MOfHE5wXKLhT0V-MMhjlDv0C-mP_jgt4cxRMgoLSz5GkUZ-3MFTPHCpB-W2EheX43iWeUgfDhdJPAsR_oKWmDGeJRMRoyea3fhyVA6RjsuCCxdDiD-2fsizC5eSp_CPh4UnP5gU6sOpL7g3ocyCSDn0I7-L4znKBg3uKDmeW8Nzsriqg5eMHk33Cn9Q_0hPQtMX4oqOfMedHI-IehuDm92Q9xDzISyH67jOoc_R_OijI61TJLuObzn-zWi6S2gVT3jUIkhOw2pMgU13XPuGM4c7_B_yHCcPPYpD4Tp6DW6To89xIS-qH31w6vjBLksu4mFEDcndIByvI9SPS4PODM2PdumCfOKDXJByhPGKy8FFZcP3olGs4z5T1MrC4yHiK8e_QdSD-KBz9M3RjNIRPfFQQxxH_PBxKYeoSKRw6YGl8Zh4H09i4rogLg_IsDsuHz_6y2imQ2ZThGcO50KaNj2uoZtk6MJjhIm-DeHj4UMzC9V43Hky9Dj0pwv06Dn05MGPR4OnQ3s8_MFDqI8EnYdG6RRSH9eHmgryH192ZCKPPyp-52jqHWXHBT-O5D2Rw85F3JtAX7jeqLCYLMfF4seN_MeUC9pzXCKuR0K7o_mC_1DNDPl21NoLSzuO_sSVBEefZ0hrC8mHU0GVtviDH7XzoM7w9CgfTInCDc8DPhPyH0nkw9vgbEfJRJvwC08I98gj6ESu4ylx3FGJfvIKM7ZRsluER8eVIll6hL-EUsoOcz_K4250WM4Rq7qQXFKO9-iNMzSeYxuLL3vB8CnyBsmxX3iOJ9uHUqLgJ0f148ZxD8ka9QjlfHieF3cUCeEPLXWMnHiCMih5_HAbfA5-NKP0I5m2ncijw2mGq0mxLzvOS6idB2dQS0KPJsoNMsyOP5MQHclyXGgmTbiSKPjhD0fsI7lk9ELzD5eUEH0mvGONatyFZ9GK5D8iHs3hvEEXzcSn6egdCc1HIU-gD3mGU71QvsN5nDk-KYXH0EW40kiuLDH-eDgjPDt6NHF4PHjw_Si3w3fhHz9hnhTRJzuuI3wk-At4NLhw6Sgn_KtwccB_iD9gWxUOP8bhHb8HT0evRcJ_ouuC5oM0t0K_I_7gTUpwXI6RZ4fIE-kkynhzvMwFnzmI1MXeQ1xW9MqDHqkj3Fl0fDyeHa2iB9-CF2EuaD9yBWdi4cHjKEoCZzGPfOGhK8tx4kyHSh3SROODkIpRW4eW54J-NEckOZJGPH8S_MXX5HgiHj18MUMWj8UJ_SL-HL0HOxF0_MZ3xDDzoL_QKzr8gOGH8IH-Ii9-eE8s1Bc-7cS1EY3KHPON2D3axMa344eWx4JmH1dKnDxRUtvQ3DJO4spyaH8ORx9yLVlRNcbRH-4T3NERTXrwD4pJKoGvDlt9IeQS9Drcx7jEdHCqHdO2436Ea0cZIlkmBrmOx8WHK0eZC36Kylks47mNI8zEndAcFzleM2hWxkR_PMH14UOYH4V6ovvh4j7eGflx68H24P_gUsHx7fCNx7g2IX5QLpwW5FqWGDyH_vAVrCXgZ0F-iIqOSswe_ESPZqxRH9su6ISvoz2OR0Xt4Olx96CO43gl-CHqB7rxpzjR7EPlctDNQl6SoxJpIT3-wD_q4cmRB1qOPkbeKI3wa9ijBU9E-HSRL9uh4_7wKA1RK1GI5tFxGe0PMQmNf0iPPyIeHf_xJg9O5IeYv3geFuHJID96SRs-HGePG47xRsTFBfpxScthJ1Eq1D9Cwj-eLcZVH-5wwfvRN0b8BzvCPAE5HemWLOgqGfehHc2XNMj7oOxxpOijBDrBMES6ZclxesQzvBX8oD9e9IJ_tJOMagpzNNfBC4-OqTua96i3w6_RK-HR8DmSWULcxMOV43fwP2iuTMi14UwERUrI6MgX5J-S4BbmQ-yPPDn85DhxamIC_7hSPMf9IJmSuAhzYg9OUkrw6UHzoCdyfUjAHf05NGoWB2-InCeS2XFwH4we5ThODp2i7-Dn4BaHMJKSC7qObPKD5ktm1BS-oEyuBc1xXoiThTmSJ5Qx5VGHXmFwcnjjCJ6SIHmi3Mgf4EqHR7uC7xFOZQiZdUOy7MaNn8eHv4EZ6cFH4T_uI_mHvA9OxUEj1phEDTlzHP-D_UmIo3FIhCxRPeiX4wmuJEeeT2hCCslOPNjvBI80EqwUFE3xI9bICXpUBM0zfej0tPglnDeYXIuRH2KP_Ivw5LiUB1nictCdEvfRTTma73hyfNEjrEw-iLMS4-GFPWlCZPmOZuyPOcR_9JUGuyb64_iFL_hkxH6g7YiXF009PLlw7DkO_kHPFE2VrcSToVeQPkR16M3x-DjCE8ePH_mFhD8eocdxXiu6w2nC6ehxIkHe4cwMVlqOvfBTnJi6LNPR7B_4HOm-QE-OPW4i5DiPXM6E39AEH6Vz9MeRb8ePA7kh3ugRUnoERxH6CrVjfHvgx7BPo1aON8UlPEiupIgfBeuNShmoTTz-FCGpHMnNDp9wncF1XDqSPUeYxMf4ZMecHKd-8DrEHz--m3h6_Cr6ozluyRISh9ERH4d7nMcXBhPJB83xDZP-obGET1oRH8nzB2dYNCeO6Ua-7NDx7InwRyuaH6F148qSJ_jT4SyJ8BLRjBnk5EmG3KLQHdtJosyiJsFvoheyZKeQPMqOL0yk4jz847mEX3g61NfxBrXwWChPNGd0fAuq7ALV9EJ6aDx-hPlRH9eO0PrRHNehJzmKXxkhH-oKHz_S47iEzyJyHDr8RyjxFtV4iCoz4kj_glbh4xPyBR8P_UGYUcfDo9_hLwdv-Ee0EZdwCbqOnHjg_IeT4_ng4zDJD8ls5Ds-JniEx1sC58jxaNAp9LqhH2r8oIKe6LiOntByCbEjVnguR9gvXAmPc0HZo7k5_A7yGr9GaNnR49GFZwo0xDkcHj2uHL3RHEfeQbuI-3CP-yGq6cZPdB6xxT3-Ii-OK4Mr1I6D58MnPGJihDyaP9AV4kXIT2i4ZCeeHtWPX3jm4jh7pNJ6_PgiiM-DXMnxwEctxkap7YeDjsmJij6uBOYiJPuR48aPhyeOKb9RUQyeF8n7IecPJsyI8iVQ80RzjshTaHmD8J3w6EDVCk9zXOlxHM1lBX-RI_nRLwf_DP7hB5WOPwgbEeJb4algxgcvvIE14zhO4j0cKYRmLS_6HfxxHf0nzCz0H82DWsiDLxEndO3hP-jxo9-FMId-5A8-EndUBVX06Wj64yqOvN3wFb9DqNKGPjouAulROccfaUPEP8KTQ9cWPD_CHPXmDG9wXUb4Q8uFXA6eG4zawzochcd__INP9C2yHOIR_sLR5wqavHjU8Dji74Tma0jJ4MdF8B2-GH5mGXvhG-GhqPzQjDpygrFz2GGDn4iT69izEY7Q_7ieLZAVEU1Elsi_HB4DL8dk9fiWoelQnkF-KErErMSTNHikqCq0PrgmBeEp-HRU9CHCjIfmIdJTNFUmTQF7VE2EJqm0Is9SFeVyatj4IyQZXDl6NFWWDpeI3DtOY_SLJ8sM9k2QZ2huVMcTA4cAAYgB4YwSDACBiFBMPPGctY6a6pAAxighhEjKAAaBNsgIIAAQRgFFHCBGIACQIBJAoAAADCKiCDLSCCABQYQQwIwEigkArKGII0OUQEwAogBRoCCHCCKQAEcEkQYQYoQSigDjCBMCIUCJIUQJQQRRiDAAHSEKEOCCEAAgDRQBxDEgkBEGEAQQFkIIIAQhAgnBAFTAQIEAQYgxYwBClAkEACMEAEAAMQgISAxCgiiCACESIWQAUWYQBoBDBhBGgBBAMSMkYogAIwjwBCMkACLCCASEIMARg4QCBCAijCYAKweEAkAJYRgSAkDjjBCMQgioMIYBQIgDQhkBGiKEQAeBFAQAZoACBgFKFAEAOQMAEIQYgICShChGCCDKESSYoEIQAIRiFkAAgQJMCWMYRUAIgAQAigFEgFDEEAEwEAYQaQw0BgEHADDWGSCAWEgIBQQxBghmjBQCCEqMA0YpQIwAwgDjHFBECiWUEQYxohABRAhAjAUCESUARgRQYgAARggKMAVOAEIEc4gyJ4ABABCCjGMIKAIAEQIAIAwChAEgAGEAGAeIUMZY4QghSBhADSCCGiKNlAQoogAChjCDEAEEWEIRA0QohoQAQCkECEGQEQIEMUwYgIgBABgECECCKEQAAkIgYZARSABkmFECASIARQAAIBggQBDggASECKMVIgJIwwQQUAKChDAQAQMJEcwRIAQQAAlCBGEOCEEMA0A5IARBSAgCiUMCMQEEcdYoYQUglgpgCDDCAMoJIAIIxBRyEggCFAIECGEYQYQp4oBgCCAICSAKEUUMIgwIRAxQwDEEDCCOCsAEYIQBIpBUhhoFlGQcAUYgBAQAJIAhgAglFFEYGAGkEswIAAxSlEBAhABAGKWQktApAQRQBABigBIBAAMyNAQqpYACBgACBAHEOAMIEtIoAAgThBkCCCHIChMYAQYBYAUAgCAmTEgEEAEEUUIhNRAABgChCACCKAAEAAAQYwghCAAAAEJgMMEYCEhAAiADCAAFRAACOUKII4gBowwwECABgAJAIKgMoogJAwABQiFBODLECMSQAQYoYCRAAABgjBBGEUiAYQAR6ghiAhBKCFMGEeAFEIIAYBBDABEhFDKKIgOYoAQo4QgToElEAPIMIIAQtVZQgxQoBJIKAENGESSIFAQwgBAgADAAAMBEOGKIQMpJAAgQRCljKCGICKQAIQAYYwQXQCCgDBJECWIIGAgwxgRQRAnDhMMOGICMEAgYIYEiAhADCBGEMiMIAsQQoBAiBAgPiHBEGiMMIIoSoJAABCFJDAFEaKAIAIYyQJQBgigCBAMAgGIAQQYRIZBASAhDABEIIgLEEQA4JgCBSgAAnAEKIIYJoIAYAjAkQCAiCAEMIACYAYAIFDxxSgElGGAcEaGMkIQBBDlSEDFBFRKLAOEEJMIQBYgQgEAGAGEEEKIIcYAZIRChSDOLiAXMMGohUk4IYJFQCAkECCGWGCCIMMwAABATlCgghCjMGWCSEMIAAAigwjhjCAMICQCIEAIZA4gwTgACkGKMMEIVUEwABBzAmBnBlBKCSGIMAcAqpagFBUWCgBRIGCuYUYQhwAggggEIjjKKAyAAMwoE5owIziIiBCSGCAIMAEAoggxFCCAmmFTEWMKUYQgNQBhBgCAEjFNIKeOMQ4AwRYBBwAjGgDDAMQSMUUwAIqAR1jpIEEEEKGMEAkYIhBADQgBEqUFAFEqQIYI4JhSwwihRjUCAGAeQAYgAYrRhgBGkjEBACCEBAEYopIAwQCCGBDAAGUAAoooJJKByRkBDiJDCMa2UAQMYYRgQAGBFADBIGKEAYg4AgAgQSgAoHCFMCgCUAEY5BQBCxjMIEBBEEgAA"); } - + [TestCase("nin.mp3")] [TestCase("nin.flac")] public void should_fingerprint_file(string file) { var path = Path.Combine(TestContext.CurrentContext.TestDirectory, "Files", "Media", file); - + var fingerprint = Subject.GetFingerprint(path); fingerprint.Should().NotBeNull(); fingerprint.Fingerprint.Should().Be("AQACmomSJEySRNISHCa6zDh6OO_hoUfr48cvHD83-JApYL6F8oCMHvlg46qOHYf740L6ascN_fj0wh90aD2OC41FC-Exf0IvPBKyH6qNOGLEgrBxXC3w4MiFB2J--Cce4cYXpLwGXER64RHxQxT142eJFMeL40g_HSbUh7h6xONhuDZ-5NpxFrpwfCrSo4pj_EJYHoehvzjeHcbnDGoOH30WPEYeEz3xI72P0sLRNRHx49IB_IXx4_iH5yF-HOdx2FoE8R5-HM2hJmOF6hFSXziPHdtxmLmQ5sKYHzouFjlMokfOBncsaE91mPoQ_MctTCqRX9CEnziO_zhcCPk_POmOoz8u1KOQ6-ihazgaHw9OaPlxAvmKfDhUpcWH_MNbBr-Do0eYH7p-5PqFPUbD5TK2o6p0_MeP8IcOw0c-H8eRZxCjRniE8HgPhlKKxqmk4jnai8JZBO9SPMauFEeOHxeOFj_-NsgFdaHxIzx8PMzQRsQfRL4GHvoiNLnwXD6uA-Jx_DiM4-Wh5nBUIXx8vEMtBt60wWwQ3mh7ovE1PCmaHMdx9AiOM8SFXMfVC_oToDl64sqSsfiNB-Wh5_iT4xf-D8dh6PjxAP6CP8fjQf9ghM069IYfwxf8C5cQdwcXC5-CPNiP48WBKh_i49DN4Dz6C82Rx8mQH7-wgzls5VDznPhz4PBx_AAr-PjxVBHUB-aHQld2oWfQODnOoKcLX7iW4fHBFcfxHPOgH_Mt_HjEJDoq9cKH44nyQyfCjBeeVBP4VEUfvIvwIIueUYWTJviFH_lx_EeOQ7wG1sibwNGL7oh_6GzQTGKIkFm64CE-1TiYH_6OWHXw_Dh-2Dp0_TgR43mOXjOOkOGhZdKHPHiIvgy2H_0xJlsQX9Cu48gN__iR5_jBHj7U6wiVtyj9oemOz8LR_Ba-IM8VXDPCJ1PBRdMRyhe8aYZ-HP3R48fBvdCeHM9R7Qve48htuMoS0eiR-_jxoDkYLjoeJ9DUU_iA4zr44zec4_EOPcdTeAib4URPPLCPnseniUL0D6HSHf9xoz3wByF73Ic-VA_-fYh_ePwQ_cGlQD-ap-jDHOEpXENWwrEyPMe1I8ePHz_yQz-8D_-NrIbzo7uF-IcuohkZXBpyH89jnAJFHSH5DP9R5fh0FDrB42mGazj-bbhz6DwahGSKq_jxGwx3-EIsbnh-wdYO4YSPHz8OQszxPMSPhsf3HDl6zTCRhwr6g1fxPAej44txfLhw6JiPisfb4LhzlDy0ZDhj5NqIo3-w_UA6Cn2GKk6hHtcAH7-JH4cDNSkeHS9yH9_x4cyQ6yIemM5xBefx9HCqGT-OHzxOaDwefLfwpBfyC-EP_9CZo88snEPOHl-EHn4QMSd-XAN2PAe8HdBlH9SLrzm6HH-hK0d5mCrOoj9-MMe3hrhycPERjw9-YciJHx-EP8cTsRvOw5OOHjpjY14yEj0ycbBxZUXEVHB25BrM4McOhCwwCCDgjAQAFIOoAIICIQSAQiBDFELAEaYUMMtAKgUSACBnRJEQEGCAeAoRRIQQliFAsVYGGOKIcEYAAIVRgjgAJDNGKYCUBgIIKLwxCBHjCVDGECYuAsJBDhUSBhGhCACGKKOEEUUI4AAxHAkFHQEAQWeQJAYIYGQUAgBBgNGAMAEQMABRJwQSD2gCGAIMAOUIYhQBKwBjBCKmlCIBAACUYmYJZA0gRDgBCDDwWQcRAAAARJxACoFuBABOAACIwlY5Q4BwQAEAJDDYKZGQwogIyQwSABFmFDHDCAKAUMwooYAQABEgACPEAEORcQQ4aAAgHBRBpFFMECUoUJQZs4ARSBEFgUHKOUGAAYQ5QxAQyAFADDlAKgKMUAIQBxpQjBDLIBNCAGKsIBQRRQSSwjkFkCPDEOEQIUwKJJiywADhtHGAEaKAUBASxRRBxBgCDFBAKYWAAkIAYQQQBAkLBFEAKEIexEYxQYhFBghiAEDECCABMQAACh1QiBAgCDBUIEUZQAAAwpxYADFzAIAEIQEwkAQIAJhwylElhINSOMEEAwwggJVSAjHjgBQIEcMQcUARBJRT8AKBgAMAGKMIABIxQYVwhACAFbKAAUEAccAR4wmRlAjCiEEGMGIcEAQYZCSCTCInBQ"); @@ -112,7 +111,8 @@ FINGERPRINT=AQAHJlMURlEURcgP6cwRD43Y4Ptw9FowncWPWkf6GB9-JYdP9OgJHw8u4Apw4SsOHMdx [Test] public void should_lookup_list() { - var files = new [] { + var files = new[] + { "nin.mp3", "nin.flac" }.Select(x => new LocalTrack { Path = Path.Combine(TestContext.CurrentContext.TestDirectory, "Files", "Media", x) }).ToList(); @@ -125,14 +125,15 @@ FINGERPRINT=AQAHJlMURlEURcgP6cwRD43Y4Ptw9FowncWPWkf6GB9-JYdP9OgJHw8u4Apw4SsOHMdx [Test] public void should_lookup_list_when_fpcalc_fails_for_some_files() { - var files = new [] { + var files = new[] + { "nin.mp3", "missing.mp3", "nin.flac" }.Select(x => new LocalTrack { Path = Path.Combine(TestContext.CurrentContext.TestDirectory, "Files", "Media", x) }).ToList(); var idpairs = files.Select(x => Tuple.Create(x, Subject.GetFingerprint(x.Path))).ToList(); - + Subject.Lookup(idpairs, 0.5); files[0].AcoustIdResults.Should().Contain("30f3f33e-8d0c-4e69-8539-cbd701d18f28"); @@ -143,13 +144,14 @@ FINGERPRINT=AQAHJlMURlEURcgP6cwRD43Y4Ptw9FowncWPWkf6GB9-JYdP9OgJHw8u4Apw4SsOHMdx [Test] public void should_lookup_list_when_fpcalc_fails_for_all_files() { - var files = new [] { + var files = new[] + { "missing1.mp3", "missing2.mp3" }.Select(x => new LocalTrack { Path = Path.Combine(TestContext.CurrentContext.TestDirectory, "Files", "Media", x) }).ToList(); var idpairs = files.Select(x => Tuple.Create(x, null)).ToList(); - + Subject.Lookup(idpairs, 0.5); files[0].AcoustIdResults.Should().BeNull(); @@ -161,12 +163,13 @@ FINGERPRINT=AQAHJlMURlEURcgP6cwRD43Y4Ptw9FowncWPWkf6GB9-JYdP9OgJHw8u4Apw4SsOHMdx { var path = Path.Combine(TestContext.CurrentContext.TestDirectory, "Files", "Media", "missing.mp3"); var localTrack = new LocalTrack { Path = path }; - var acoustId = new AcoustId { + var acoustId = new AcoustId + { Duration = 0, Fingerprint = "fingerprint" }; - Subject.Lookup(new List> { Tuple.Create(localTrack, acoustId)}, 0.5); + Subject.Lookup(new List> { Tuple.Create(localTrack, acoustId) }, 0.5); } [Test] @@ -174,12 +177,13 @@ FINGERPRINT=AQAHJlMURlEURcgP6cwRD43Y4Ptw9FowncWPWkf6GB9-JYdP9OgJHw8u4Apw4SsOHMdx { var path = Path.Combine(TestContext.CurrentContext.TestDirectory, "Files", "Media", "missing.mp3"); var localTrack = new LocalTrack { Path = path }; - var acoustId = new AcoustId { + var acoustId = new AcoustId + { Duration = 1, Fingerprint = "fingerprint" }; - var files = new List> { Tuple.Create(localTrack, acoustId)}; + var files = new List> { Tuple.Create(localTrack, acoustId) }; Subject.Lookup(files, 0.5); files[0].Item1.AcoustIdResults.Should().BeNull(); } @@ -187,7 +191,8 @@ FINGERPRINT=AQAHJlMURlEURcgP6cwRD43Y4Ptw9FowncWPWkf6GB9-JYdP9OgJHw8u4Apw4SsOHMdx [Test] public void should_not_fail_for_some_invalid_fingerprints() { - var files = new [] { + var files = new[] + { "nin.mp3", "nin.flac" }.Select(x => new LocalTrack { Path = Path.Combine(TestContext.CurrentContext.TestDirectory, "Files", "Media", x) }).ToList(); @@ -195,7 +200,7 @@ FINGERPRINT=AQAHJlMURlEURcgP6cwRD43Y4Ptw9FowncWPWkf6GB9-JYdP9OgJHw8u4Apw4SsOHMdx var idpairs = files.Select(x => Tuple.Create(x, Subject.GetFingerprint(x.Path))).ToList(); idpairs.Add(Tuple.Create(new LocalTrack(), new AcoustId { Duration = 1, Fingerprint = "fingerprint" })); - + Subject.Lookup(idpairs, 0.5); idpairs[0].Item1.AcoustIdResults.Should().Contain("30f3f33e-8d0c-4e69-8539-cbd701d18f28"); diff --git a/src/NzbDrone.Core.Test/ParserTests/HashedReleaseFixture.cs b/src/NzbDrone.Core.Test/ParserTests/HashedReleaseFixture.cs index e78fb26c6..df542e252 100644 --- a/src/NzbDrone.Core.Test/ParserTests/HashedReleaseFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/HashedReleaseFixture.cs @@ -83,11 +83,13 @@ namespace NzbDrone.Core.Test.ParserTests } }; - [Test, TestCaseSource(nameof(HashedReleaseParserCases))] + [Test] + [TestCaseSource(nameof(HashedReleaseParserCases))] [Ignore("Hashed code is not currently called with track parsing")] public void should_properly_parse_hashed_releases(string path, string title, Quality quality, string releaseGroup) { var result = Parser.Parser.ParseMusicPath(path); + //result.SeriesTitle.Should().Be(title); result.Quality.Quality.Should().Be(quality); } diff --git a/src/NzbDrone.Core.Test/ParserTests/MusicParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/MusicParserFixture.cs index e1a7d3a86..82a9473db 100644 --- a/src/NzbDrone.Core.Test/ParserTests/MusicParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/MusicParserFixture.cs @@ -2,17 +2,12 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace NzbDrone.Core.Test.ParserTests { [TestFixture] public class MusicParserFixture : CoreTest { - //[TestCase("___▲▲▲___")] //[TestCase("Add N to (X)")] //[TestCase("Animal Collective")] diff --git a/src/NzbDrone.Core.Test/ParserTests/NormalizeTitleFixture.cs b/src/NzbDrone.Core.Test/ParserTests/NormalizeTitleFixture.cs index 7634a8fc5..f2af9134e 100644 --- a/src/NzbDrone.Core.Test/ParserTests/NormalizeTitleFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/NormalizeTitleFixture.cs @@ -5,7 +5,6 @@ using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.ParserTests { - [TestFixture] public class NormalizeTitleFixture : CoreTest { @@ -93,9 +92,8 @@ namespace NzbDrone.Core.Test.ParserTests foreach (var s in dirtyFormat) { var dirty = string.Format(s, word); - dirty.CleanArtistName().Should().Be(("word" + word.ToLower() + "word")); + dirty.CleanArtistName().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 6c4c31b82..921d1246f 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ParserFixture.cs @@ -9,11 +9,10 @@ using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.ParserTests { - [TestFixture] public class ParserFixture : CoreTest { - Artist _artist = new Artist(); + private Artist _artist = new Artist(); private List _albums = new List { new Album() }; [SetUp] @@ -101,14 +100,18 @@ namespace NzbDrone.Core.Test.ParserTests [TestCase("VA - The Best 101 Love Ballads (2017) MP3 [192 kbps]", "VA", "The Best 101 Love Ballads")] [TestCase("ATCQ - The Love Movement 1998 2CD 192kbps RIP", "ATCQ", "The Love Movement")] + //[TestCase("A Tribe Called Quest - The Love Movement 1998 2CD [192kbps] RIP", "A Tribe Called Quest", "The Love Movement")] [TestCase("Maula - Jism 2 [2012] Mp3 - 192Kbps [Extended]- TK", "Maula", "Jism 2")] [TestCase("VA - Complete Clubland - The Ultimate Ride Of Your Lfe [2014][MP3][192 kbps]", "VA", "Complete Clubland - The Ultimate Ride Of Your Lfe")] [TestCase("Complete Clubland - The Ultimate Ride Of Your Lfe [2014][MP3](192kbps)", "Complete Clubland", "The Ultimate Ride Of Your Lfe")] + //[TestCase("The Ultimate Ride Of Your Lfe [192 KBPS][2014][MP3]", "", "The Ultimate Ride Of Your Lfe")] [TestCase("Gary Clark Jr - Live North America 2016 (2017) MP3 192kbps", "Gary Clark Jr", "Live North America 2016")] + //[TestCase("Beyoncé Lemonade [320] 2016 Beyonce Lemonade [320] 2016", "Beyoncé", "Lemonade")] [TestCase("Childish Gambino - Awaken, My Love Album 2016 mp3 320 Kbps", "Childish Gambino", "Awaken, My Love Album")] + //[TestCase("Maluma – Felices Los 4 MP3 320 Kbps 2017 Download", "Maluma", "Felices Los 4")] [TestCase("Ricardo Arjona - APNEA (Single 2014) (320 kbps)", "Ricardo Arjona", "APNEA")] [TestCase("Kehlani - SweetSexySavage (Deluxe Edition) (2017) 320", "Kehlani", "SweetSexySavage")] @@ -121,6 +124,7 @@ namespace NzbDrone.Core.Test.ParserTests [TestCase("Clean Bandit - New Eyes [2014] [Mp3-256]-V3nom [GLT]", "Clean Bandit", "New Eyes")] [TestCase("Armin van Buuren - A State Of Trance 810 (20.04.2017) 256 kbps", "Armin van Buuren", "A State Of Trance 810")] [TestCase("PJ Harvey - Let England Shake [mp3-256-2011][trfkad]", "PJ Harvey", "Let England Shake")] + //[TestCase("X-Men Soundtracks (2006-2014) AAC, 256 kbps", "", "")] //[TestCase("Walk the Line Soundtrack (2005) [AAC, 256 kbps]", "", "Walk the Line Soundtrack")] //[TestCase("Emeli Sande Next To Me (512 Kbps)", "Emeli", "Next To Me")] @@ -133,9 +137,11 @@ namespace NzbDrone.Core.Test.ParserTests [TestCase("John Coltrane - Kulu Se Mama (1965) [EAC-FLAC]", "John Coltrane", "Kulu Se Mama")] [TestCase("The Rolling Stones - The Very Best Of '75-'94 (1995) {FLAC}", "The Rolling Stones", "The Very Best Of '75-'94")] [TestCase("Migos-No_Label_II-CD-FLAC-2014-FORSAKEN", "Migos", "No Label II")] + //[TestCase("ADELE 25 CD FLAC 2015 PERFECT", "Adele", "25")] [TestCase("A.I. - Sex & Robots [2007/MP3/V0(VBR)]", "A I", "Sex & Robots")] [TestCase("Jay-Z - 4:44 (Deluxe Edition) (2017) 320", "Jay-Z", "444")] + //[TestCase("Roberta Flack 2006 - The Very Best of", "Roberta Flack", "The Very Best of")] [TestCase("VA - NOW Thats What I Call Music 96 (2017) [Mp3~Kbps]", "VA", "NOW Thats What I Call Music 96")] [TestCase("Queen - The Ultimate Best Of Queen(2011)[mp3]", "Queen", "The Ultimate Best Of Queen")] @@ -154,12 +160,14 @@ namespace NzbDrone.Core.Test.ParserTests [TestCase("Brother Ali-The Undisputed Truth-2007-FTD", "Brother Ali", "The Undisputed Truth")] // ruTracker - [TestCase("(Eclectic Progressive Rock) [CD] Peter Hammill - From The Trees - 2017, FLAC (tracks + .cue), lossless", "Peter Hammill","From The Trees")] + [TestCase("(Eclectic Progressive Rock) [CD] Peter Hammill - From The Trees - 2017, FLAC (tracks + .cue), lossless", "Peter Hammill", "From The Trees")] [TestCase("(Folk Rock / Pop) Aztec Two-Step - Naked - 2017, MP3, 320 kbps", "Aztec Two-Step", "Naked")] [TestCase("(Zeuhl / Progressive Rock) [WEB] Dai Kaht - Dai Kaht - 2017, FLAC (tracks), lossless", "Dai Kaht", "Dai Kaht")] + //[TestCase("(Industrial Folk) Bumblebee(Shmely, AntiVirus) - Discography, 23 albums - 1998-2011, FLAC(image + .cue), lossless")] //[TestCase("(Heavy Metal) Sergey Mavrin(Mavrik) - Discography(14 CD) [1998-2010], FLAC(image + .cue), lossless")] [TestCase("(Heavy Metal) [CD] Black Obelisk - Discography - 1991-2015 (36 releases, 32 CDs), FLAC(image + .cue), lossless", "Black Obelisk", "Discography", true)] + //[TestCase("(R'n'B / Soul) Moyton - One of the Sta(2014) + Ocean(2014), MP3, 320 kbps", "Moyton", "")] [TestCase("(Heavy Metal) Aria - Discography(46 CD) [1985 - 2015], FLAC(image + .cue), lossless", "Aria", "Discography", true)] [TestCase("(Heavy Metal) [CD] Forces United - Discography(6 CDs), 2014-2016, FLAC(image + .cue), lossless", "Forces United", "Discography", true)] @@ -194,8 +202,7 @@ namespace NzbDrone.Core.Test.ParserTests [TestCase("Led Zeppelin - Studio Discography 1969-1982 (10 albums)(flac)", 1969, 1982)] [TestCase("Minor Threat - Complete Discography [1989] [Anthology]", 0, 1989)] [TestCase("Caetano Veloso Discografia Completa MP3 @256", 0, 0)] - public void should_parse_year_or_year_range_from_discography(string releaseTitle, int startyear, - int endyear) + public void should_parse_year_or_year_range_from_discography(string releaseTitle, int startyear, int endyear) { var parseResult = Parser.Parser.ParseAlbumTitle(releaseTitle); parseResult.Discography.Should().BeTrue(); @@ -214,6 +221,7 @@ namespace NzbDrone.Core.Test.ParserTests [TestCase("Ed Sheeran", "I See Fire", "Ed Sheeran I See Fire[Mimp3.eu].mp3 FLAC")] [TestCase("Ed Sheeran", "Divide", "Ed Sheeran ? Divide FLAC")] [TestCase("Ed Sheeran", "+", "Ed Sheeran + FLAC")] + //[TestCase("Glasvegas", @"EUPHORIC /// HEARTBREAK \\\", @"EUPHORIC /// HEARTBREAK \\\ FLAC")] // slashes not being escaped properly [TestCase("XXXTENTACION", "?", "XXXTENTACION ? FLAC")] [TestCase("Hey", "BŁYSK", "Hey - BŁYSK FLAC")] diff --git a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetAlbumsFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetAlbumsFixture.cs index 4a696478a..5973e1b8f 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetAlbumsFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetAlbumsFixture.cs @@ -1,14 +1,14 @@ +using System.Collections.Generic; +using System.Linq; +using FizzWare.NBuilder; +using FluentAssertions; using Moq; using NUnit.Framework; -using NzbDrone.Core.Parser; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; -using FizzWare.NBuilder; using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.Music; +using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; -using FluentAssertions; -using System.Linq; -using System.Collections.Generic; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests { @@ -20,15 +20,17 @@ namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests { var artist = Builder.CreateNew().Build(); var albums = Builder.CreateListOfSize(2).All().With(x => x.Title = "IdenticalTitle").Build().ToList(); - var criteria = new AlbumSearchCriteria { + var criteria = new AlbumSearchCriteria + { Artist = artist, Albums = albums }; - var parsed = new ParsedAlbumInfo { + var parsed = new ParsedAlbumInfo + { AlbumTitle = "IdenticalTitle" }; - + Subject.GetAlbums(parsed, artist, criteria).Should().BeEquivalentTo(new List()); Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetArtistFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetArtistFixture.cs index a24043507..784d510e6 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetArtistFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetArtistFixture.cs @@ -1,8 +1,8 @@ using Moq; using NUnit.Framework; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests { diff --git a/src/NzbDrone.Core.Test/ParserTests/PathParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/PathParserFixture.cs index 75aa18d49..d8b00613e 100644 --- a/src/NzbDrone.Core.Test/ParserTests/PathParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/PathParserFixture.cs @@ -1,11 +1,9 @@ -using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.ParserTests { - [TestFixture] public class PathParserFixture : CoreTest { @@ -30,16 +28,17 @@ namespace NzbDrone.Core.Test.ParserTests [TestCase(@"C:\Test\Series\Season 01\1 Pilot (1080p HD).mkv", 1, 1)] [TestCase(@"C:\Test\Series\Season 1\02 Honor Thy Father (1080p HD).m4v", 1, 2)] [TestCase(@"C:\Test\Series\Season 1\2 Honor Thy Father (1080p HD).m4v", 1, 2)] -// [TestCase(@"C:\CSI.NY.S02E04.720p.WEB-DL.DD5.1.H.264\73696S02-04.mkv", 2, 4)] //Gets treated as S01E04 (because it gets parsed as anime) + + // [TestCase(@"C:\CSI.NY.S02E04.720p.WEB-DL.DD5.1.H.264\73696S02-04.mkv", 2, 4)] //Gets treated as S01E04 (because it gets parsed as anime) public void should_parse_from_path(string path, int season, int episode) { var result = Parser.Parser.ParseMusicPath(path.AsOsAgnostic()); + //result.EpisodeNumbers.Should().HaveCount(1); //result.SeasonNumber.Should().Be(season); //result.EpisodeNumbers[0].Should().Be(episode); //result.AbsoluteEpisodeNumbers.Should().BeEmpty(); //result.FullSeason.Should().BeFalse(); - ExceptionVerification.IgnoreWarns(); } } diff --git a/src/NzbDrone.Core.Test/ParserTests/QualityParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/QualityParserFixture.cs index 747f78b25..98ffd96be 100644 --- a/src/NzbDrone.Core.Test/ParserTests/QualityParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/QualityParserFixture.cs @@ -12,19 +12,19 @@ namespace NzbDrone.Core.Test.ParserTests { public static object[] SelfQualityParserCases = { - new object[] {Quality.MP3_192}, - new object[] {Quality.MP3_VBR}, - new object[] {Quality.MP3_256}, - new object[] {Quality.MP3_320}, - new object[] {Quality.MP3_VBR_V2}, - new object[] {Quality.WAV}, - new object[] {Quality.WMA}, - new object[] {Quality.AAC_192}, - new object[] {Quality.AAC_256}, - new object[] {Quality.AAC_320}, - new object[] {Quality.AAC_VBR}, - new object[] {Quality.ALAC}, - new object[] {Quality.FLAC}, + new object[] { Quality.MP3_192 }, + new object[] { Quality.MP3_VBR }, + new object[] { Quality.MP3_256 }, + new object[] { Quality.MP3_320 }, + new object[] { Quality.MP3_VBR_V2 }, + new object[] { Quality.WAV }, + new object[] { Quality.WMA }, + new object[] { Quality.AAC_192 }, + new object[] { Quality.AAC_256 }, + new object[] { Quality.AAC_320 }, + new object[] { Quality.AAC_VBR }, + new object[] { Quality.ALAC }, + new object[] { Quality.FLAC }, }; [TestCase("", "MPEG Version 1 Audio, Layer 3", 96)] @@ -136,7 +136,6 @@ namespace NzbDrone.Core.Test.ParserTests ParseAndVerifyQuality(title, desc, bitrate, Quality.WAV); } - [TestCase("Chuck Berry Discography ALAC", null, 0)] [TestCase("A$AP Rocky - LONG LIVE A$AP Deluxe asap[ALAC]", null, 0)] [TestCase("", "MPEG-4 Audio (alac)", 0)] @@ -144,7 +143,7 @@ namespace NzbDrone.Core.Test.ParserTests { ParseAndVerifyQuality(title, desc, bitrate, Quality.ALAC); } - + [TestCase("Stevie Ray Vaughan Discography (1981-1987) [APE]", null, 0)] [TestCase("Brain Ape - Rig it [2014][ape]", null, 0)] [TestCase("", "Monkey's Audio", 0)] @@ -258,6 +257,7 @@ namespace NzbDrone.Core.Test.ParserTests [TestCase("The Chainsmokers & Coldplay - Something Just Like This")] [TestCase("Frank Ocean Blonde 2016")] + //TODO: This should be parsed as Unknown and not MP3-96 //[TestCase("A - NOW Thats What I Call Music 96 (2017) [Mp3~Kbps]")] [TestCase("Queen - The Ultimate Best Of Queen(2011)[mp3]")] @@ -267,7 +267,8 @@ namespace NzbDrone.Core.Test.ParserTests ParseAndVerifyQuality(title, null, 0, Quality.Unknown); } - [Test, TestCaseSource(nameof(SelfQualityParserCases))] + [Test] + [TestCaseSource(nameof(SelfQualityParserCases))] public void parsing_our_own_quality_enum_name(Quality quality) { var fileName = string.Format("Some album [{0}]", quality.Name); @@ -283,8 +284,9 @@ namespace NzbDrone.Core.Test.ParserTests [TestCase("01. Kanye West - Ultralight Beam.mp3")] [TestCase("01. Kanye West - Ultralight Beam.ogg")] + //These get detected by name as we are looking for the extensions as identifiers for release names - //[TestCase("01. Kanye West - Ultralight Beam.m4a")] + //[TestCase("01. Kanye West - Ultralight Beam.m4a")] //[TestCase("01. Kanye West - Ultralight Beam.wma")] //[TestCase("01. Kanye West - Ultralight Beam.wav")] public void should_parse_quality_from_extension(string title) @@ -313,6 +315,5 @@ namespace NzbDrone.Core.Test.ParserTests var result = QualityParser.ParseQuality(name, desc, bitrate, sampleSize); result.Quality.Should().Be(quality); } - } } diff --git a/src/NzbDrone.Core.Test/ParserTests/ReleaseGroupParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ReleaseGroupParserFixture.cs index 7977a3608..4dc5fd174 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ReleaseGroupParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ReleaseGroupParserFixture.cs @@ -14,6 +14,7 @@ namespace NzbDrone.Core.Test.ParserTests [TestCase("Olafur.Arnalds-Remember-WEB-2018-ENTiTLED-Pre", "ENTiTLED")] [TestCase("Olafur.Arnalds-Remember-WEB-2018-ENTiTLED-postbot", "ENTiTLED")] [TestCase("Olafur.Arnalds-Remember-WEB-2018-ENTiTLED-xpost", "ENTiTLED")] + //[TestCase("", "")] public void should_parse_release_group(string title, string expected) { @@ -32,6 +33,7 @@ namespace NzbDrone.Core.Test.ParserTests [TestCase("Olafur.Arnalds-Remember-WEB-2018-SKGTV English", "SKGTV")] [TestCase("Olafur.Arnalds-Remember-WEB-2018-SKGTV_English", "SKGTV")] [TestCase("Olafur.Arnalds-Remember-WEB-2018-SKGTV.English", "SKGTV")] + //[TestCase("", "")] public void should_not_include_language_in_release_group(string title, string expected) { @@ -56,6 +58,7 @@ namespace NzbDrone.Core.Test.ParserTests [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/Profiles/Delay/DelayProfileServiceFixture.cs b/src/NzbDrone.Core.Test/Profiles/Delay/DelayProfileServiceFixture.cs index 7fb8cbd6d..c0770aa81 100644 --- a/src/NzbDrone.Core.Test/Profiles/Delay/DelayProfileServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Profiles/Delay/DelayProfileServiceFixture.cs @@ -44,7 +44,7 @@ namespace NzbDrone.Core.Test.Profiles.Delay var moving = _last; var result = Subject.Reorder(moving.Id, null).OrderBy(d => d.Order).ToList(); var moved = result.First(); - + moved.Id.Should().Be(moving.Id); moved.Order.Should().Be(1); } @@ -75,7 +75,6 @@ namespace NzbDrone.Core.Test.Profiles.Delay { delayProfile.Order.Should().Be(int.MaxValue); } - else { delayProfile.Order.Should().Be(i + 1); diff --git a/src/NzbDrone.Core.Test/Profiles/Metadata/MetadataProfileRepositoryFixture.cs b/src/NzbDrone.Core.Test/Profiles/Metadata/MetadataProfileRepositoryFixture.cs index e5fd56ed9..5601eee4c 100644 --- a/src/NzbDrone.Core.Test/Profiles/Metadata/MetadataProfileRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/Profiles/Metadata/MetadataProfileRepositoryFixture.cs @@ -1,9 +1,9 @@ -using FluentAssertions; using System.Linq; +using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Music; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Profiles.Metadata; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Profiles.Metadata { diff --git a/src/NzbDrone.Core.Test/Profiles/Metadata/MetadataProfileServiceFixture.cs b/src/NzbDrone.Core.Test/Profiles/Metadata/MetadataProfileServiceFixture.cs index ffc369b22..080b84630 100644 --- a/src/NzbDrone.Core.Test/Profiles/Metadata/MetadataProfileServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Profiles/Metadata/MetadataProfileServiceFixture.cs @@ -1,14 +1,14 @@ +using System; +using System.Collections.Generic; using System.Linq; using FizzWare.NBuilder; using Moq; using NUnit.Framework; using NzbDrone.Core.ImportLists; using NzbDrone.Core.Lifecycle; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Music; using NzbDrone.Core.Profiles.Metadata; -using System.Collections.Generic; -using System; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Profiles.Metadata { @@ -26,6 +26,7 @@ namespace NzbDrone.Core.Test.Profiles.Metadata } [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() @@ -128,7 +129,6 @@ namespace NzbDrone.Core.Test.Profiles.Metadata Assert.Throws(() => Subject.Delete(profile.Id)); Mocker.GetMock().Verify(c => c.Delete(It.IsAny()), Times.Never()); - } [Test] @@ -155,7 +155,6 @@ namespace NzbDrone.Core.Test.Profiles.Metadata Assert.Throws(() => Subject.Delete(profile.Id)); Mocker.GetMock().Verify(c => c.Delete(It.IsAny()), Times.Never()); - } [Test] diff --git a/src/NzbDrone.Core.Test/Profiles/ProfileRepositoryFixture.cs b/src/NzbDrone.Core.Test/Profiles/ProfileRepositoryFixture.cs index 7ad4f2a83..1d6fbb587 100644 --- a/src/NzbDrone.Core.Test/Profiles/ProfileRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/Profiles/ProfileRepositoryFixture.cs @@ -13,11 +13,11 @@ namespace NzbDrone.Core.Test.Profiles public void should_be_able_to_read_and_write() { var profile = new QualityProfile - { - Items = Qualities.QualityFixture.GetDefaultQualities(Quality.MP3_320, Quality.MP3_192, Quality.MP3_256), - Cutoff = Quality.MP3_320.Id, - Name = "TestProfile" - }; + { + Items = Qualities.QualityFixture.GetDefaultQualities(Quality.MP3_320, Quality.MP3_192, Quality.MP3_256), + Cutoff = Quality.MP3_320.Id, + Name = "TestProfile" + }; Subject.Insert(profile); @@ -25,8 +25,6 @@ namespace NzbDrone.Core.Test.Profiles 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 d7edea846..437e3d19d 100644 --- a/src/NzbDrone.Core.Test/Profiles/ProfileServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Profiles/ProfileServiceFixture.cs @@ -4,9 +4,9 @@ using Moq; using NUnit.Framework; using NzbDrone.Core.ImportLists; using NzbDrone.Core.Lifecycle; +using NzbDrone.Core.Music; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.Profiles { @@ -24,6 +24,7 @@ namespace NzbDrone.Core.Test.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() @@ -38,7 +39,6 @@ namespace NzbDrone.Core.Test.Profiles .Verify(v => v.Insert(It.IsAny()), Times.Never()); } - [Test] public void should_not_be_able_to_delete_profile_if_assigned_to_artist() { @@ -63,7 +63,6 @@ namespace NzbDrone.Core.Test.Profiles Assert.Throws(() => Subject.Delete(profile.Id)); Mocker.GetMock().Verify(c => c.Delete(It.IsAny()), Times.Never()); - } [Test] @@ -90,7 +89,6 @@ namespace NzbDrone.Core.Test.Profiles Assert.Throws(() => Subject.Delete(profile.Id)); Mocker.GetMock().Verify(c => c.Delete(It.IsAny()), Times.Never()); - } [Test] diff --git a/src/NzbDrone.Core.Test/Profiles/Qualities/QualityIndexCompareToFixture.cs b/src/NzbDrone.Core.Test/Profiles/Qualities/QualityIndexCompareToFixture.cs index b11c046d5..9798b78d5 100644 --- a/src/NzbDrone.Core.Test/Profiles/Qualities/QualityIndexCompareToFixture.cs +++ b/src/NzbDrone.Core.Test/Profiles/Qualities/QualityIndexCompareToFixture.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Profiles.Qualities; diff --git a/src/NzbDrone.Core.Test/Profiles/Releases/PreferredWordService/CalculateFixture.cs b/src/NzbDrone.Core.Test/Profiles/Releases/PreferredWordService/CalculateFixture.cs index 5c7693bae..77f0e7e41 100644 --- a/src/NzbDrone.Core.Test/Profiles/Releases/PreferredWordService/CalculateFixture.cs +++ b/src/NzbDrone.Core.Test/Profiles/Releases/PreferredWordService/CalculateFixture.cs @@ -4,9 +4,9 @@ using FizzWare.NBuilder; using FluentAssertions; using Moq; using NUnit.Framework; +using NzbDrone.Core.Music; using NzbDrone.Core.Profiles.Releases; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.Profiles.Releases.PreferredWordService { @@ -21,26 +21,25 @@ namespace NzbDrone.Core.Test.Profiles.Releases.PreferredWordService public void Setup() { _artist = Builder.CreateNew() - .With(s => s.Tags = new HashSet(new[] {1, 2})) + .With(s => s.Tags = new HashSet(new[] { 1, 2 })) .Build(); _releaseProfiles = new List(); _releaseProfiles.Add(new ReleaseProfile - { - Preferred = new List> + { + Preferred = new List> { new KeyValuePair("24bit", 5), new KeyValuePair("16bit", -10) } - }); + }); Mocker.GetMock() .Setup(s => s.AllForTags(It.IsAny>())) .Returns(_releaseProfiles); } - private void GivenMatchingTerms(params string[] terms) { Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/Profiles/Releases/PreferredWordService/GetMatchingPreferredWordsFixture.cs b/src/NzbDrone.Core.Test/Profiles/Releases/PreferredWordService/GetMatchingPreferredWordsFixture.cs index d261bf18a..5353836b6 100644 --- a/src/NzbDrone.Core.Test/Profiles/Releases/PreferredWordService/GetMatchingPreferredWordsFixture.cs +++ b/src/NzbDrone.Core.Test/Profiles/Releases/PreferredWordService/GetMatchingPreferredWordsFixture.cs @@ -4,9 +4,9 @@ using FizzWare.NBuilder; using FluentAssertions; using Moq; using NUnit.Framework; +using NzbDrone.Core.Music; using NzbDrone.Core.Profiles.Releases; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Test.Profiles.Releases.PreferredWordService { @@ -35,13 +35,11 @@ namespace NzbDrone.Core.Test.Profiles.Releases.PreferredWordService } }); - Mocker.GetMock() .Setup(s => s.MatchingTerm(It.IsAny(), _title)) .Returns((term, title) => title.Contains(term) ? term : null); } - private void GivenReleaseProfile() { Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/ProviderTests/DiskProviderTests/ArchiveProviderFixture.cs b/src/NzbDrone.Core.Test/ProviderTests/DiskProviderTests/ArchiveProviderFixture.cs index 5e9d6c6a8..504fa1a3a 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/GetAudioFilesFixture.cs b/src/NzbDrone.Core.Test/ProviderTests/DiskScanProviderTests/GetAudioFilesFixture.cs index bd54f2f88..09959a42d 100644 --- a/src/NzbDrone.Core.Test/ProviderTests/DiskScanProviderTests/GetAudioFilesFixture.cs +++ b/src/NzbDrone.Core.Test/ProviderTests/DiskScanProviderTests/GetAudioFilesFixture.cs @@ -1,21 +1,21 @@ using System.Collections.Generic; using System.IO; +using System.IO.Abstractions; using System.Linq; using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Common.Disk; -using NzbDrone.Test.Common; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Test.Framework; -using System.IO.Abstractions; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.ProviderTests.DiskScanProviderTests { public class GetAudioFilesFixture : CoreTest { + private readonly string _path = @"C:\Test\".AsOsAgnostic(); private string[] _fileNames; - private readonly string path = @"C:\Test\".AsOsAgnostic(); [SetUp] public void Setup() @@ -49,7 +49,7 @@ namespace NzbDrone.Core.Test.ProviderTests.DiskScanProviderTests { TestLogger.Debug(file.Name); } - + Mocker.GetMock() .Setup(s => s.GetFileInfos(It.IsAny(), SearchOption.AllDirectories)) .Returns(filesToReturn); @@ -58,36 +58,36 @@ namespace NzbDrone.Core.Test.ProviderTests.DiskScanProviderTests [Test] public void should_check_all_directories() { - Subject.GetAudioFiles(path); + Subject.GetAudioFiles(_path); - Mocker.GetMock().Verify(s => s.GetFileInfos(path, SearchOption.AllDirectories), Times.Once()); - Mocker.GetMock().Verify(s => s.GetFileInfos(path, SearchOption.TopDirectoryOnly), Times.Never()); + Mocker.GetMock().Verify(s => s.GetFileInfos(_path, SearchOption.AllDirectories), Times.Once()); + Mocker.GetMock().Verify(s => s.GetFileInfos(_path, SearchOption.TopDirectoryOnly), Times.Never()); } [Test] public void should_check_all_directories_when_allDirectories_is_true() { - Subject.GetAudioFiles(path, true); + Subject.GetAudioFiles(_path, true); - Mocker.GetMock().Verify(s => s.GetFileInfos(path, SearchOption.AllDirectories), Times.Once()); - Mocker.GetMock().Verify(s => s.GetFileInfos(path, SearchOption.TopDirectoryOnly), Times.Never()); + Mocker.GetMock().Verify(s => s.GetFileInfos(_path, SearchOption.AllDirectories), Times.Once()); + Mocker.GetMock().Verify(s => s.GetFileInfos(_path, SearchOption.TopDirectoryOnly), Times.Never()); } [Test] public void should_check_top_level_directory_only_when_allDirectories_is_false() { - Subject.GetAudioFiles(path, false); + Subject.GetAudioFiles(_path, false); - Mocker.GetMock().Verify(s => s.GetFileInfos(path, SearchOption.AllDirectories), Times.Never()); - Mocker.GetMock().Verify(s => s.GetFileInfos(path, SearchOption.TopDirectoryOnly), Times.Once()); + Mocker.GetMock().Verify(s => s.GetFileInfos(_path, SearchOption.AllDirectories), Times.Never()); + Mocker.GetMock().Verify(s => s.GetFileInfos(_path, SearchOption.TopDirectoryOnly), Times.Once()); } [Test] public void should_return_audio_files_only() { - GivenFiles(GetFiles(path)); + GivenFiles(GetFiles(_path)); - Subject.GetAudioFiles(path).Should().HaveCount(4); + Subject.GetAudioFiles(_path).Should().HaveCount(4); } [TestCase("Extras")] @@ -99,11 +99,11 @@ namespace NzbDrone.Core.Test.ProviderTests.DiskScanProviderTests [TestCase(".unwanted")] public void should_filter_certain_sub_folders(string subFolder) { - var files = GetFiles(path).ToList(); - var specialFiles = GetFiles(path, subFolder).ToList(); + var files = GetFiles(_path).ToList(); + var specialFiles = GetFiles(_path, subFolder).ToList(); var allFiles = files.Concat(specialFiles); - var filteredFiles = Subject.FilterFiles(path, allFiles); + var filteredFiles = Subject.FilterFiles(_path, allFiles); filteredFiles.Should().NotContain(specialFiles); filteredFiles.Count.Should().BeGreaterThan(0); } diff --git a/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/CleanupFixture.cs b/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/CleanupFixture.cs index 5e336420b..7fb282fa2 100644 --- a/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/CleanupFixture.cs +++ b/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/CleanupFixture.cs @@ -10,7 +10,7 @@ using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.ProviderTests.RecycleBinProviderTests { [TestFixture] - + public class CleanupFixture : CoreTest { private const string RecycleBin = @"C:\Test\RecycleBin"; @@ -40,10 +40,10 @@ namespace NzbDrone.Core.Test.ProviderTests.RecycleBinProviderTests 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 4f5433a88..09404ae0d 100644 --- a/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/DeleteFileFixture.cs +++ b/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/DeleteFileFixture.cs @@ -70,7 +70,6 @@ namespace NzbDrone.Core.Test.ProviderTests.RecycleBinProviderTests 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 fbb0b1c0a..f061c1388 100644 --- a/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/EmptyFixture.cs +++ b/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/EmptyFixture.cs @@ -9,7 +9,7 @@ using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.ProviderTests.RecycleBinProviderTests { [TestFixture] - + public class EmptyFixture : CoreTest { private const string RecycleBin = @"C:\Test\RecycleBin"; @@ -20,10 +20,10 @@ namespace NzbDrone.Core.Test.ProviderTests.RecycleBinProviderTests 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] @@ -38,7 +38,7 @@ namespace NzbDrone.Core.Test.ProviderTests.RecycleBinProviderTests [Test] public void should_delete_all_folders() - { + { Mocker.Resolve().Empty(); Mocker.GetMock().Verify(v => v.DeleteFolder(It.IsAny(), true), Times.Exactly(3)); diff --git a/src/NzbDrone.Core.Test/Qualities/QualityDefinitionServiceFixture.cs b/src/NzbDrone.Core.Test/Qualities/QualityDefinitionServiceFixture.cs index 27b301615..f7a659578 100644 --- a/src/NzbDrone.Core.Test/Qualities/QualityDefinitionServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Qualities/QualityDefinitionServiceFixture.cs @@ -32,7 +32,7 @@ namespace NzbDrone.Core.Test.Qualities 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] @@ -58,7 +58,7 @@ namespace NzbDrone.Core.Test.Qualities .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 013353a12..3a72522c8 100644 --- a/src/NzbDrone.Core.Test/Qualities/QualityFixture.cs +++ b/src/NzbDrone.Core.Test/Qualities/QualityFixture.cs @@ -1,5 +1,5 @@ -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Profiles.Qualities; @@ -13,32 +13,34 @@ namespace NzbDrone.Core.Test.Qualities { public static object[] FromIntCases = { - new object[] {0, Quality.Unknown}, - new object[] {1, Quality.MP3_192}, - new object[] {2, Quality.MP3_VBR}, - new object[] {3, Quality.MP3_256}, - new object[] {4, Quality.MP3_320}, - new object[] {6, Quality.FLAC}, + new object[] { 0, Quality.Unknown }, + new object[] { 1, Quality.MP3_192 }, + new object[] { 2, Quality.MP3_VBR }, + new object[] { 3, Quality.MP3_256 }, + new object[] { 4, Quality.MP3_320 }, + new object[] { 6, Quality.FLAC }, }; public static object[] ToIntCases = { - new object[] {Quality.Unknown, 0}, - new object[] {Quality.MP3_192, 1}, - new object[] {Quality.MP3_VBR, 2}, - new object[] {Quality.MP3_256, 3}, - new object[] {Quality.MP3_320, 4}, - new object[] {Quality.FLAC, 6}, + new object[] { Quality.Unknown, 0 }, + new object[] { Quality.MP3_192, 1 }, + new object[] { Quality.MP3_VBR, 2 }, + new object[] { Quality.MP3_256, 3 }, + new object[] { Quality.MP3_320, 4 }, + new object[] { Quality.FLAC, 6 }, }; - [Test, TestCaseSource(nameof(FromIntCases))] + [Test] + [TestCaseSource(nameof(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(nameof(ToIntCases))] + [Test] + [TestCaseSource(nameof(ToIntCases))] public void should_be_able_to_convert_qualityTypes_to_int(Quality source, int expected) { var i = (int)source; @@ -58,7 +60,9 @@ namespace NzbDrone.Core.Test.Qualities }; 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 85f97ba62..67c57f5ae 100644 --- a/src/NzbDrone.Core.Test/Qualities/QualityModelComparerFixture.cs +++ b/src/NzbDrone.Core.Test/Qualities/QualityModelComparerFixture.cs @@ -61,7 +61,6 @@ namespace NzbDrone.Core.Test.Qualities Subject = new QualityModelComparer(profile); } - [Test] public void should_be_greater_when_first_quality_is_greater_than_second() { diff --git a/src/NzbDrone.Core.Test/Qualities/RevisionComparableFixture.cs b/src/NzbDrone.Core.Test/Qualities/RevisionComparableFixture.cs index e67640c58..5756ede70 100644 --- a/src/NzbDrone.Core.Test/Qualities/RevisionComparableFixture.cs +++ b/src/NzbDrone.Core.Test/Qualities/RevisionComparableFixture.cs @@ -134,10 +134,10 @@ namespace NzbDrone.Core.Test.Qualities [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 17bb19323..7cb205af4 100644 --- a/src/NzbDrone.Core.Test/QueueTests/QueueServiceFixture.cs +++ b/src/NzbDrone.Core.Test/QueueTests/QueueServiceFixture.cs @@ -1,17 +1,16 @@ using System; using System.Collections.Generic; using System.Linq; -using NUnit.Framework; using FizzWare.NBuilder; using FluentAssertions; using Moq; -using NzbDrone.Core.Test.Framework; +using NUnit.Framework; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.History; using NzbDrone.Core.Music; -using NzbDrone.Core.Queue; using NzbDrone.Core.Parser.Model; - +using NzbDrone.Core.Queue; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.QueueTests { @@ -52,10 +51,8 @@ namespace NzbDrone.Core.Test.QueueTests .Build(); Mocker.GetMock() - .Setup(c => c.Find(It.IsAny(), HistoryEventType.Grabbed)).Returns - ( - new List { historyItem } - ); + .Setup(c => c.Find(It.IsAny(), HistoryEventType.Grabbed)).Returns( + new List { historyItem }); } [Test] diff --git a/src/NzbDrone.Core.Test/RemotePathMappingsTests/RemotePathMappingServiceFixture.cs b/src/NzbDrone.Core.Test/RemotePathMappingsTests/RemotePathMappingServiceFixture.cs index 15bda4fd9..47f023c1b 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.Common.Disk; using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; -using FizzWare.NBuilder; namespace NzbDrone.Core.Test.RemotePathMappingsTests { @@ -72,7 +72,7 @@ namespace NzbDrone.Core.Test.RemotePathMappingsTests Subject.Remove(1); Mocker.GetMock().Verify(c => c.Delete(1), Times.Once()); } - + [TestCase("my-server.localdomain", "/mnt/storage", @"D:\mountedstorage")] [TestCase("my-server.localdomain", "/mnt/storage", @"D:\mountedstorage2")] public void adding_duplicated_mapping_should_throw(string host, string remotePath, string localPath) @@ -128,7 +128,7 @@ namespace NzbDrone.Core.Test.RemotePathMappingsTests { Host = "my-server.localdomain", RemotePath = remotePath, - LocalPath = @"D:\mountedstorage\downloads\tv" .AsOsAgnostic() + LocalPath = @"D:\mountedstorage\downloads\tv".AsOsAgnostic() }; var result = Subject.Add(mapping); @@ -136,4 +136,4 @@ namespace NzbDrone.Core.Test.RemotePathMappingsTests result.RemotePath.Should().Be(cleanedPath); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/RootFolderTests/RootFolderServiceFixture.cs b/src/NzbDrone.Core.Test/RootFolderTests/RootFolderServiceFixture.cs index c86968c18..7f5a33608 100644 --- a/src/NzbDrone.Core.Test/RootFolderTests/RootFolderServiceFixture.cs +++ b/src/NzbDrone.Core.Test/RootFolderTests/RootFolderServiceFixture.cs @@ -7,9 +7,9 @@ using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Common.Disk; +using NzbDrone.Core.Music; using NzbDrone.Core.RootFolders; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Music; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.RootFolderTests @@ -73,8 +73,7 @@ namespace NzbDrone.Core.Test.RootFolderTests 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] diff --git a/src/NzbDrone.Core.Test/ThingiProviderTests/NullConfigFixture.cs b/src/NzbDrone.Core.Test/ThingiProviderTests/NullConfigFixture.cs index 0f47d9a91..efc5c58bd 100644 --- a/src/NzbDrone.Core.Test/ThingiProviderTests/NullConfigFixture.cs +++ b/src/NzbDrone.Core.Test/ThingiProviderTests/NullConfigFixture.cs @@ -14,4 +14,4 @@ namespace NzbDrone.Core.Test.ThingiProviderTests Subject.Validate().IsValid.Should().BeTrue(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderBaseFixture.cs b/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderBaseFixture.cs index 88a35b910..600206a24 100644 --- a/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderBaseFixture.cs +++ b/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderBaseFixture.cs @@ -23,7 +23,7 @@ namespace NzbDrone.Core.Test.ThingiProviderTests 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 74f2480f7..7d91d7d91 100644 --- a/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderStatusServiceFixture.cs +++ b/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderStatusServiceFixture.cs @@ -29,7 +29,6 @@ namespace NzbDrone.Core.Test.ThingiProviderTests public MockProviderStatusService(IMockProviderStatusRepository providerStatusRepository, IEventAggregator eventAggregator, IRuntimeInfo runtimeInfo, Logger logger) : base(providerStatusRepository, eventAggregator, runtimeInfo, logger) { - } } diff --git a/src/NzbDrone.Core.Test/UpdateTests/UpdatePackageProviderFixture.cs b/src/NzbDrone.Core.Test/UpdateTests/UpdatePackageProviderFixture.cs index 3a88bda18..c61c3e9e6 100644 --- a/src/NzbDrone.Core.Test/UpdateTests/UpdatePackageProviderFixture.cs +++ b/src/NzbDrone.Core.Test/UpdateTests/UpdatePackageProviderFixture.cs @@ -25,7 +25,7 @@ namespace NzbDrone.Core.Test.UpdateTests } [Test] - [Platform(Exclude="NetCore")] + [Platform(Exclude = "NetCore")] public void finds_update_when_version_lower() { UseRealHttp(); @@ -40,7 +40,6 @@ namespace NzbDrone.Core.Test.UpdateTests Subject.GetLatestUpdate("invalid_branch", new Version(0, 2)).Should().NotBeNull(); } - [Test] public void should_get_recent_updates() { diff --git a/src/NzbDrone.Core.Test/UpdateTests/UpdateServiceFixture.cs b/src/NzbDrone.Core.Test/UpdateTests/UpdateServiceFixture.cs index 2701e878e..1d5c41577 100644 --- a/src/NzbDrone.Core.Test/UpdateTests/UpdateServiceFixture.cs +++ b/src/NzbDrone.Core.Test/UpdateTests/UpdateServiceFixture.cs @@ -40,7 +40,6 @@ namespace NzbDrone.Core.Test.UpdateTests Version = new Version("0.6.2.883") }; } - else { _updatePackage = new UpdatePackage @@ -115,7 +114,6 @@ namespace NzbDrone.Core.Test.UpdateTests Subject.Execute(new ApplicationUpdateCommand()); - Mocker.GetMock().Verify(c => c.DeleteFolder(_sandboxFolder, true), Times.Never()); } @@ -166,7 +164,6 @@ namespace NzbDrone.Core.Test.UpdateTests Subject.Execute(new ApplicationUpdateCommand()); - ExceptionVerification.AssertNoUnexpectedLogs(); } @@ -181,7 +178,7 @@ namespace NzbDrone.Core.Test.UpdateTests } [Test] - [Platform(Exclude="Win")] + [Platform(Exclude = "Win")] public void should_run_script_if_configured() { const string scriptPath = "/tmp/lidarr/update.sh"; @@ -194,7 +191,7 @@ namespace NzbDrone.Core.Test.UpdateTests } [Test] - [Platform(Exclude="Win")] + [Platform(Exclude = "Win")] public void should_throw_if_script_is_not_set() { const string scriptPath = "/tmp/lidarr/update.sh"; @@ -208,7 +205,7 @@ namespace NzbDrone.Core.Test.UpdateTests } [Test] - [Platform(Exclude="Win")] + [Platform(Exclude = "Win")] public void should_throw_if_script_is_null() { const string scriptPath = "/tmp/lidarr/update.sh"; @@ -222,7 +219,7 @@ namespace NzbDrone.Core.Test.UpdateTests } [Test] - [Platform(Exclude="Win")] + [Platform(Exclude = "Win")] public void should_throw_if_script_path_does_not_exist() { const string scriptPath = "/tmp/lidarr/update.sh"; diff --git a/src/NzbDrone.Core.Test/ValidationTests/GuidValidationFixture.cs b/src/NzbDrone.Core.Test/ValidationTests/GuidValidationFixture.cs index 6c03bedf4..6f73b1628 100644 --- a/src/NzbDrone.Core.Test/ValidationTests/GuidValidationFixture.cs +++ b/src/NzbDrone.Core.Test/ValidationTests/GuidValidationFixture.cs @@ -1,10 +1,10 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; +using NzbDrone.Core.ImportLists.Exclusions; using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Validation; using NzbDrone.Test.Common; -using NzbDrone.Core.ImportLists.Exclusions; namespace NzbDrone.Core.Test.ValidationTests { diff --git a/src/NzbDrone.Core.Test/ValidationTests/SystemFolderValidatorFixture.cs b/src/NzbDrone.Core.Test/ValidationTests/SystemFolderValidatorFixture.cs index cff197390..025771e42 100644 --- a/src/NzbDrone.Core.Test/ValidationTests/SystemFolderValidatorFixture.cs +++ b/src/NzbDrone.Core.Test/ValidationTests/SystemFolderValidatorFixture.cs @@ -3,11 +3,11 @@ using System.IO; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; -using NzbDrone.Core.Test.Framework; +using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Core.Music; +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 ee6ca8605..c622bc088 100644 --- a/src/NzbDrone.Core/Analytics/AnalyticsService.cs +++ b/src/NzbDrone.Core/Analytics/AnalyticsService.cs @@ -24,7 +24,7 @@ namespace NzbDrone.Core.Analytics _historyService = historyService; } - public bool IsEnabled => _configFileProvider.AnalyticsEnabled && RuntimeInfo.IsProduction || RuntimeInfo.IsDevelopment; + public bool IsEnabled => (_configFileProvider.AnalyticsEnabled && RuntimeInfo.IsProduction) || RuntimeInfo.IsDevelopment; public bool InstallIsActive { @@ -33,7 +33,7 @@ namespace NzbDrone.Core.Analytics var lastRecord = _historyService.Paged(new PagingSpec() { Page = 0, PageSize = 1, SortKey = "date", SortDirection = SortDirection.Descending }); var monthAgo = DateTime.UtcNow.AddMonths(-1); - return lastRecord.Records.Any(v => v.Date > monthAgo); + return lastRecord.Records.Any(v => v.Date > monthAgo); } } } diff --git a/src/NzbDrone.Core/ArtistStats/AlbumStatistics.cs b/src/NzbDrone.Core/ArtistStats/AlbumStatistics.cs index dfcb9f4d9..ffc84ad82 100644 --- a/src/NzbDrone.Core/ArtistStats/AlbumStatistics.cs +++ b/src/NzbDrone.Core/ArtistStats/AlbumStatistics.cs @@ -1,4 +1,3 @@ -using System; using NzbDrone.Core.Datastore; namespace NzbDrone.Core.ArtistStats diff --git a/src/NzbDrone.Core/ArtistStats/ArtistStatistics.cs b/src/NzbDrone.Core/ArtistStats/ArtistStatistics.cs index 3989393f4..9315eb4c5 100644 --- a/src/NzbDrone.Core/ArtistStats/ArtistStatistics.cs +++ b/src/NzbDrone.Core/ArtistStats/ArtistStatistics.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using NzbDrone.Core.Datastore; namespace NzbDrone.Core.ArtistStats diff --git a/src/NzbDrone.Core/ArtistStats/ArtistStatisticsService.cs b/src/NzbDrone.Core/ArtistStats/ArtistStatisticsService.cs index 2ebf8d61c..5810387a7 100644 --- a/src/NzbDrone.Core/ArtistStats/ArtistStatisticsService.cs +++ b/src/NzbDrone.Core/ArtistStats/ArtistStatisticsService.cs @@ -44,7 +44,10 @@ namespace NzbDrone.Core.ArtistStats { var stats = _cache.Get(artistId.ToString(), () => _artistStatisticsRepository.ArtistStatistics(artistId)); - if (stats == null || stats.Count == 0) return new ArtistStatistics(); + if (stats == null || stats.Count == 0) + { + return new ArtistStatistics(); + } return MapArtistStatistics(stats); } @@ -52,15 +55,15 @@ namespace NzbDrone.Core.ArtistStats private ArtistStatistics MapArtistStatistics(List albumStatistics) { var artistStatistics = new ArtistStatistics - { - AlbumStatistics = albumStatistics, - AlbumCount = albumStatistics.Count, - ArtistId = albumStatistics.First().ArtistId, - TrackFileCount = albumStatistics.Sum(s => s.TrackFileCount), - TrackCount = albumStatistics.Sum(s => s.TrackCount), - TotalTrackCount = albumStatistics.Sum(s => s.TotalTrackCount), - SizeOnDisk = albumStatistics.Sum(s => s.SizeOnDisk) - }; + { + AlbumStatistics = albumStatistics, + AlbumCount = albumStatistics.Count, + ArtistId = albumStatistics.First().ArtistId, + TrackFileCount = albumStatistics.Sum(s => s.TrackFileCount), + TrackCount = albumStatistics.Sum(s => s.TrackCount), + TotalTrackCount = albumStatistics.Sum(s => s.TotalTrackCount), + SizeOnDisk = albumStatistics.Sum(s => s.SizeOnDisk) + }; return artistStatistics; } diff --git a/src/NzbDrone.Core/Authentication/UserService.cs b/src/NzbDrone.Core/Authentication/UserService.cs index 4e4bc9aed..55e5ef350 100644 --- a/src/NzbDrone.Core/Authentication/UserService.cs +++ b/src/NzbDrone.Core/Authentication/UserService.cs @@ -35,11 +35,11 @@ namespace NzbDrone.Core.Authentication 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 43def029c..6e907c8d4 100644 --- a/src/NzbDrone.Core/Backup/BackupService.cs +++ b/src/NzbDrone.Core/Backup/BackupService.cs @@ -78,7 +78,7 @@ namespace NzbDrone.Core.Backup { CleanupOldBackups(backupType); } - + BackupConfigFile(); BackupDatabase(); CreateVersionInfo(); @@ -104,11 +104,11 @@ namespace NzbDrone.Core.Backup 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 6460daab1..b45280c0e 100644 --- a/src/NzbDrone.Core/Backup/MakeDatabaseBackup.cs +++ b/src/NzbDrone.Core/Backup/MakeDatabaseBackup.cs @@ -1,12 +1,7 @@ -using System; -using System.Collections.Generic; using System.Data.SQLite; using System.IO; -using System.Linq; -using System.Text; using NLog; using NzbDrone.Core.Datastore; -using System.Data; namespace NzbDrone.Core.Backup { @@ -30,6 +25,7 @@ namespace NzbDrone.Core.Backup 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 3a06b1b1b..40c4d2216 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 6d179db61..301220de9 100644 --- a/src/NzbDrone.Core/Blacklisting/Blacklist.cs +++ b/src/NzbDrone.Core/Blacklisting/Blacklist.cs @@ -2,8 +2,8 @@ using System; using System.Collections.Generic; using NzbDrone.Core.Datastore; using NzbDrone.Core.Indexers; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Music; +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 9d6e736c4..369664df6 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.Music; namespace NzbDrone.Core.Blacklisting @@ -15,8 +15,8 @@ namespace NzbDrone.Core.Blacklisting 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 9df920ac1..2ce1f9d7d 100644 --- a/src/NzbDrone.Core/Blacklisting/BlacklistService.cs +++ b/src/NzbDrone.Core/Blacklisting/BlacklistService.cs @@ -7,8 +7,8 @@ using NzbDrone.Core.Download; using NzbDrone.Core.Indexers; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Music.Events; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.Blacklisting { @@ -18,6 +18,7 @@ namespace NzbDrone.Core.Blacklisting PagingSpec Paged(PagingSpec pagingSpec); void Delete(int id); } + public class BlacklistService : IBlacklistService, IExecute, @@ -34,12 +35,15 @@ namespace NzbDrone.Core.Blacklisting public bool Blacklisted(int artistId, ReleaseInfo release) { var blacklistedByTitle = _blacklistRepository.BlacklistedByTitle(artistId, release.Title); - + if (release.DownloadProtocol == DownloadProtocol.Torrent) { var torrentInfo = release as TorrentInfo; - if (torrentInfo == null) return false; + if (torrentInfo == null) + { + return false; + } if (torrentInfo.InfoHash.IsNullOrWhiteSpace()) { @@ -105,7 +109,10 @@ namespace NzbDrone.Core.Blacklisting 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 @@ namespace NzbDrone.Core.Blacklisting 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,18 +138,18 @@ namespace NzbDrone.Core.Blacklisting public void Handle(DownloadFailedEvent message) { var blacklist = new Blacklist - { - ArtistId = message.ArtistId, - AlbumIds = message.AlbumIds, - 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") + { + ArtistId = message.ArtistId, + AlbumIds = message.AlbumIds, + 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") }; _blacklistRepository.Insert(blacklist); diff --git a/src/NzbDrone.Core/Blacklisting/ClearBlacklistCommand.cs b/src/NzbDrone.Core/Blacklisting/ClearBlacklistCommand.cs index d8aa3af0a..c2608aa06 100644 --- a/src/NzbDrone.Core/Blacklisting/ClearBlacklistCommand.cs +++ b/src/NzbDrone.Core/Blacklisting/ClearBlacklistCommand.cs @@ -6,4 +6,4 @@ namespace NzbDrone.Core.Blacklisting { public override bool SendUpdatesToClient => true; } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Configuration/AccessDeniedConfigFileException.cs b/src/NzbDrone.Core/Configuration/AccessDeniedConfigFileException.cs index 64b23a290..10137c493 100644 --- a/src/NzbDrone.Core/Configuration/AccessDeniedConfigFileException.cs +++ b/src/NzbDrone.Core/Configuration/AccessDeniedConfigFileException.cs @@ -5,11 +5,13 @@ namespace NzbDrone.Core.Configuration { public class AccessDeniedConfigFileException : NzbDroneException { - public AccessDeniedConfigFileException(string message) : base(message) + public AccessDeniedConfigFileException(string message) + : base(message) { } - public AccessDeniedConfigFileException(string message, Exception innerException) : base(message, innerException) + public AccessDeniedConfigFileException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/Configuration/Config.cs b/src/NzbDrone.Core/Configuration/Config.cs index 7aa02522a..ba380e5b5 100644 --- a/src/NzbDrone.Core/Configuration/Config.cs +++ b/src/NzbDrone.Core/Configuration/Config.cs @@ -14,4 +14,4 @@ namespace NzbDrone.Core.Configuration public string Value { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Configuration/ConfigFileProvider.cs b/src/NzbDrone.Core/Configuration/ConfigFileProvider.cs index af9cbb9ab..99d6f7d13 100644 --- a/src/NzbDrone.Core/Configuration/ConfigFileProvider.cs +++ b/src/NzbDrone.Core/Configuration/ConfigFileProvider.cs @@ -99,7 +99,10 @@ namespace NzbDrone.Core.Configuration object currentValue; allWithDefaults.TryGetValue(configValue.Key, out currentValue); - if (currentValue == null) continue; + if (currentValue == null) + { + continue; + } var equal = configValue.Value.ToString().Equals(currentValue.ToString()); @@ -257,7 +260,6 @@ namespace NzbDrone.Core.Configuration { parentContainer.Add(new XElement(key, valueString)); } - else { parentContainer.Descendants(key).Single().Value = valueString; @@ -331,12 +333,10 @@ namespace NzbDrone.Core.Configuration return xDoc; } } - catch (XmlException ex) { throw new InvalidConfigFileException($"{_configFile} is corrupt is invalid. Please delete the config file and Lidarr will recreate it.", ex); } - catch (UnauthorizedAccessException ex) { throw new AccessDeniedConfigFileException($"Lidarr does not have access to config file: {_configFile}. Please fix permissions", ex); @@ -356,7 +356,6 @@ namespace NzbDrone.Core.Configuration { throw new AccessDeniedConfigFileException($"Lidarr does not have access to config file: {_configFile}. Please fix permissions", ex); } - } private string GenerateApiKey() diff --git a/src/NzbDrone.Core/Configuration/ConfigRepository.cs b/src/NzbDrone.Core/Configuration/ConfigRepository.cs index c9092c7e5..c8ae80c21 100644 --- a/src/NzbDrone.Core/Configuration/ConfigRepository.cs +++ b/src/NzbDrone.Core/Configuration/ConfigRepository.cs @@ -2,7 +2,6 @@ using System.Linq; using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; - namespace NzbDrone.Core.Configuration { public interface IConfigRepository : IBasicRepository @@ -18,7 +17,6 @@ namespace NzbDrone.Core.Configuration { } - public Config Get(string key) { return Query.Where(c => c.Key == key).SingleOrDefault(); @@ -30,7 +28,7 @@ namespace NzbDrone.Core.Configuration if (dbValue == null) { - return Insert(new Config {Key = key, Value = value}); + return Insert(new Config { Key = key, Value = value }); } dbValue.Value = value; @@ -38,4 +36,4 @@ namespace NzbDrone.Core.Configuration return Update(dbValue); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Configuration/ConfigService.cs b/src/NzbDrone.Core/Configuration/ConfigService.cs index b3631f131..8f0a5fa26 100644 --- a/src/NzbDrone.Core/Configuration/ConfigService.cs +++ b/src/NzbDrone.Core/Configuration/ConfigService.cs @@ -4,10 +4,10 @@ using System.Globalization; 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.Qualities; using NzbDrone.Core.Security; @@ -57,7 +57,10 @@ namespace NzbDrone.Core.Configuration { 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()); @@ -108,9 +111,9 @@ namespace NzbDrone.Core.Configuration public int MaximumSize { - get { return GetValueInt("MaximumSize", 0);} + get { return GetValueInt("MaximumSize", 0); } - set { SetValue("MaximumSize", value);} + set { SetValue("MaximumSize", value); } } public int MinimumAge diff --git a/src/NzbDrone.Core/Configuration/IConfigService.cs b/src/NzbDrone.Core/Configuration/IConfigService.cs index 7430f7a7b..7db24c4b4 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.Qualities; using NzbDrone.Core.Security; @@ -61,7 +61,7 @@ namespace NzbDrone.Core.Configuration string TimeFormat { get; set; } bool ShowRelativeDates { get; set; } bool EnableColorImpairedMode { get; set; } - + bool ExpandAlbumByDefault { get; set; } bool ExpandSingleByDefault { get; set; } bool ExpandEPByDefault { get; set; } diff --git a/src/NzbDrone.Core/Configuration/InvalidConfigFileException.cs b/src/NzbDrone.Core/Configuration/InvalidConfigFileException.cs index 1251cf30a..4bed2f2a2 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/Datastore/BasicRepository.cs b/src/NzbDrone.Core/Datastore/BasicRepository.cs index 3c823b531..b2c88f314 100644 --- a/src/NzbDrone.Core/Datastore/BasicRepository.cs +++ b/src/NzbDrone.Core/Datastore/BasicRepository.cs @@ -5,14 +5,14 @@ using System.Linq; using System.Linq.Expressions; using Marr.Data; using Marr.Data.QGen; -using NzbDrone.Common.Extensions; using NzbDrone.Core.Datastore.Events; using NzbDrone.Core.Datastore.Extensions; using NzbDrone.Core.Messaging.Events; namespace NzbDrone.Core.Datastore { - public interface IBasicRepository where TModel : ModelBase, new() + public interface IBasicRepository + where TModel : ModelBase, new() { IEnumerable All(); int Count(); @@ -36,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; @@ -184,6 +185,7 @@ namespace NzbDrone.Core.Datastore Insert(model); return model; } + Update(model); return model; } diff --git a/src/NzbDrone.Core/Datastore/ConnectionStringFactory.cs b/src/NzbDrone.Core/Datastore/ConnectionStringFactory.cs index a69883dc1..cc087b450 100644 --- a/src/NzbDrone.Core/Datastore/ConnectionStringFactory.cs +++ b/src/NzbDrone.Core/Datastore/ConnectionStringFactory.cs @@ -35,12 +35,12 @@ namespace NzbDrone.Core.Datastore var connectionBuilder = new SQLiteConnectionStringBuilder(); connectionBuilder.DataSource = dbPath; - connectionBuilder.CacheSize = (int)-10000; + connectionBuilder.CacheSize = -10000; connectionBuilder.DateTimeKind = DateTimeKind.Utc; connectionBuilder.JournalMode = OsInfo.IsOsx ? SQLiteJournalModeEnum.Truncate : SQLiteJournalModeEnum.Wal; connectionBuilder.Pooling = true; connectionBuilder.Version = 3; - + if (OsInfo.IsOsx) { connectionBuilder.Add("Full FSync", true); @@ -49,4 +49,4 @@ namespace NzbDrone.Core.Datastore return connectionBuilder.ConnectionString; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Converters/BooleanIntConverter.cs b/src/NzbDrone.Core/Datastore/Converters/BooleanIntConverter.cs index 397746b23..bf68e751a 100644 --- a/src/NzbDrone.Core/Datastore/Converters/BooleanIntConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/BooleanIntConverter.cs @@ -33,7 +33,7 @@ namespace NzbDrone.Core.Datastore.Converters public object ToDB(object clrValue) { - var val = (Nullable)clrValue; + var val = (bool?)clrValue; switch (val) { @@ -48,4 +48,4 @@ namespace NzbDrone.Core.Datastore.Converters public Type DbType => typeof(int); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Converters/CommandConverter.cs b/src/NzbDrone.Core/Datastore/Converters/CommandConverter.cs index 0bb97f23a..a6c641206 100644 --- a/src/NzbDrone.Core/Datastore/Converters/CommandConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/CommandConverter.cs @@ -25,7 +25,7 @@ namespace NzbDrone.Core.Datastore.Converters 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/EmbeddedDocumentConverter.cs b/src/NzbDrone.Core/Datastore/Converters/EmbeddedDocumentConverter.cs index d2b9146f2..045ba64e2 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 @@ namespace NzbDrone.Core.Datastore.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 @@ namespace NzbDrone.Core.Datastore.Converters { 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,12 +55,19 @@ namespace NzbDrone.Core.Datastore.Converters 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); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Converters/EnumIntConverter.cs b/src/NzbDrone.Core/Datastore/Converters/EnumIntConverter.cs index 22d6b5336..ae1e8c46d 100644 --- a/src/NzbDrone.Core/Datastore/Converters/EnumIntConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/EnumIntConverter.cs @@ -33,4 +33,4 @@ namespace NzbDrone.Core.Datastore.Converters return DBNull.Value; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Converters/PrimaryAlbumTypeIntConverter.cs b/src/NzbDrone.Core/Datastore/Converters/PrimaryAlbumTypeIntConverter.cs index 6bce7a347..e84b50e5f 100644 --- a/src/NzbDrone.Core/Datastore/Converters/PrimaryAlbumTypeIntConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/PrimaryAlbumTypeIntConverter.cs @@ -1,8 +1,8 @@ +using System; using Marr.Data.Converters; using Marr.Data.Mapping; using Newtonsoft.Json; using NzbDrone.Core.Music; -using System; namespace NzbDrone.Core.Datastore.Converters { @@ -17,12 +17,12 @@ namespace NzbDrone.Core.Datastore.Converters var val = Convert.ToInt32(context.DbValue); - return (PrimaryAlbumType) val; + return (PrimaryAlbumType)val; } 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) @@ -37,8 +37,8 @@ namespace NzbDrone.Core.Datastore.Converters throw new InvalidOperationException("Attempted to save an album type that isn't really an album type"); } - var primType = (PrimaryAlbumType) clrValue; - return (int) primType; + var primType = (PrimaryAlbumType)clrValue; + return (int)primType; } public Type DbType => typeof(int); @@ -48,11 +48,10 @@ namespace NzbDrone.Core.Datastore.Converters return objectType == typeof(PrimaryAlbumType); } - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, - JsonSerializer serializer) + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var item = reader.Value; - return (PrimaryAlbumType) Convert.ToInt32(item); + return (PrimaryAlbumType)Convert.ToInt32(item); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) diff --git a/src/NzbDrone.Core/Datastore/Converters/ProviderSettingConverter.cs b/src/NzbDrone.Core/Datastore/Converters/ProviderSettingConverter.cs index ace64d6af..17590c4f1 100644 --- a/src/NzbDrone.Core/Datastore/Converters/ProviderSettingConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/ProviderSettingConverter.cs @@ -25,8 +25,7 @@ namespace NzbDrone.Core.Datastore.Converters 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 @@ namespace NzbDrone.Core.Datastore.Converters return Json.Deserialize(stringValue, impType); } - } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Converters/QualityIntConverter.cs b/src/NzbDrone.Core/Datastore/Converters/QualityIntConverter.cs index 0b225a8a2..e8b72b206 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 @@ namespace NzbDrone.Core.Datastore.Converters 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/ReleaseStatusIntConverter.cs b/src/NzbDrone.Core/Datastore/Converters/ReleaseStatusIntConverter.cs index 31a41ec5e..1805d9f27 100644 --- a/src/NzbDrone.Core/Datastore/Converters/ReleaseStatusIntConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/ReleaseStatusIntConverter.cs @@ -1,8 +1,8 @@ +using System; using Marr.Data.Converters; using Marr.Data.Mapping; using Newtonsoft.Json; using NzbDrone.Core.Music; -using System; namespace NzbDrone.Core.Datastore.Converters { @@ -17,12 +17,12 @@ namespace NzbDrone.Core.Datastore.Converters var val = Convert.ToInt32(context.DbValue); - return (ReleaseStatus) val; + return (ReleaseStatus)val; } 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) @@ -37,8 +37,8 @@ namespace NzbDrone.Core.Datastore.Converters throw new InvalidOperationException("Attempted to save a release status that isn't really a release status"); } - var releaseStatus = (ReleaseStatus) clrValue; - return (int) releaseStatus; + var releaseStatus = (ReleaseStatus)clrValue; + return (int)releaseStatus; } public Type DbType => typeof(int); @@ -48,11 +48,10 @@ namespace NzbDrone.Core.Datastore.Converters return objectType == typeof(ReleaseStatus); } - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, - JsonSerializer serializer) + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var item = reader.Value; - return (ReleaseStatus) Convert.ToInt32(item); + return (ReleaseStatus)Convert.ToInt32(item); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) diff --git a/src/NzbDrone.Core/Datastore/Converters/SecondaryAlbumTypeIntConverter.cs b/src/NzbDrone.Core/Datastore/Converters/SecondaryAlbumTypeIntConverter.cs index 87ae2ee5f..f21f66f7a 100644 --- a/src/NzbDrone.Core/Datastore/Converters/SecondaryAlbumTypeIntConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/SecondaryAlbumTypeIntConverter.cs @@ -17,12 +17,12 @@ namespace NzbDrone.Core.Datastore.Converters var val = Convert.ToInt32(context.DbValue); - return (SecondaryAlbumType) val; + return (SecondaryAlbumType)val; } 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) @@ -37,8 +37,8 @@ namespace NzbDrone.Core.Datastore.Converters throw new InvalidOperationException("Attempted to save an album type that isn't really an album type"); } - var secType = (SecondaryAlbumType) clrValue; - return (int) secType; + var secType = (SecondaryAlbumType)clrValue; + return (int)secType; } public Type DbType => typeof(int); @@ -48,11 +48,13 @@ namespace NzbDrone.Core.Datastore.Converters return objectType == typeof(SecondaryAlbumType); } - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, + public override object ReadJson(JsonReader reader, + Type objectType, + object existingValue, JsonSerializer serializer) { var item = reader.Value; - return (SecondaryAlbumType) Convert.ToInt32(item); + return (SecondaryAlbumType)Convert.ToInt32(item); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) diff --git a/src/NzbDrone.Core/Datastore/Converters/TimeSpanConverter.cs b/src/NzbDrone.Core/Datastore/Converters/TimeSpanConverter.cs index 579a719a0..f8080fdff 100644 --- a/src/NzbDrone.Core/Datastore/Converters/TimeSpanConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/TimeSpanConverter.cs @@ -25,7 +25,7 @@ namespace NzbDrone.Core.Datastore.Converters 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/NzbDrone.Core/Datastore/Converters/UtcConverter.cs b/src/NzbDrone.Core/Datastore/Converters/UtcConverter.cs index 1225f0806..3fd28d8a8 100644 --- a/src/NzbDrone.Core/Datastore/Converters/UtcConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/UtcConverter.cs @@ -29,4 +29,4 @@ namespace NzbDrone.Core.Datastore.Converters public Type DbType => typeof(DateTime); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/CorruptDatabaseException.cs b/src/NzbDrone.Core/Datastore/CorruptDatabaseException.cs index ba73f6b5c..f6ddb2a66 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 : LidarrStartupException { - 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/DbFactory.cs b/src/NzbDrone.Core/Datastore/DbFactory.cs index ed7698286..742384c4f 100644 --- a/src/NzbDrone.Core/Datastore/DbFactory.cs +++ b/src/NzbDrone.Core/Datastore/DbFactory.cs @@ -10,7 +10,6 @@ using NzbDrone.Common.Exceptions; using NzbDrone.Common.Instrumentation; using NzbDrone.Core.Datastore.Migration.Framework; - namespace NzbDrone.Core.Datastore { public interface IDbFactory @@ -73,7 +72,7 @@ namespace NzbDrone.Core.Datastore public IDatabase Create(MigrationContext migrationContext) { string connectionString; - + switch (migrationContext.MigrationType) { case MigrationType.Main: @@ -83,6 +82,7 @@ namespace NzbDrone.Core.Datastore break; } + case MigrationType.Log: { connectionString = _connectionStringFactory.LogDbConnectionString; @@ -90,6 +90,7 @@ namespace NzbDrone.Core.Datastore break; } + default: { throw new ArgumentException("Invalid MigrationType"); @@ -111,7 +112,6 @@ namespace NzbDrone.Core.Datastore private void CreateMain(string connectionString, MigrationContext migrationContext) { - try { _restoreDatabaseService.Restore(); diff --git a/src/NzbDrone.Core/Datastore/Events/ModelEvent.cs b/src/NzbDrone.Core/Datastore/Events/ModelEvent.cs index 72ff55296..d5b02c8cb 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; } @@ -22,4 +22,4 @@ namespace NzbDrone.Core.Datastore.Events Deleted = 3, Sync = 4 } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Extensions/MappingExtensions.cs b/src/NzbDrone.Core/Datastore/Extensions/MappingExtensions.cs index 4d635024a..96cdd9c0d 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 @@ namespace NzbDrone.Core.Datastore.Extensions { 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()) { @@ -60,4 +64,4 @@ namespace NzbDrone.Core.Datastore.Extensions return false; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/Extensions/PagingSpecExtensions.cs b/src/NzbDrone.Core/Datastore/Extensions/PagingSpecExtensions.cs index 39cc5b7a6..46d217585 100644 --- a/src/NzbDrone.Core/Datastore/Extensions/PagingSpecExtensions.cs +++ b/src/NzbDrone.Core/Datastore/Extensions/PagingSpecExtensions.cs @@ -13,12 +13,15 @@ namespace NzbDrone.Core.Datastore.Extensions 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 @@ namespace NzbDrone.Core.Datastore.Extensions } } } - \ No newline at end of file diff --git a/src/NzbDrone.Core/Datastore/Extensions/RelationshipExtensions.cs b/src/NzbDrone.Core/Datastore/Extensions/RelationshipExtensions.cs index 4fdc76a2e..98df74317 100644 --- a/src/NzbDrone.Core/Datastore/Extensions/RelationshipExtensions.cs +++ b/src/NzbDrone.Core/Datastore/Extensions/RelationshipExtensions.cs @@ -15,12 +15,11 @@ namespace NzbDrone.Core.Datastore.Extensions return relationshipBuilder.For(portalExpression.GetMemberName()) .LazyLoad( condition: parent => childIdSelector(parent) > 0, - query: (db, parent) => - { + query: (db, parent) => + { var id = childIdSelector(parent); return db.Query().Where(c => c.Id == id).SingleOrDefault(); - } - ); + }); } public static RelationshipBuilder Relationship(this ColumnMapBuilder mapBuilder) @@ -40,4 +39,4 @@ namespace NzbDrone.Core.Datastore.Extensions return expression.Member.Name; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/IEmbeddedDocument.cs b/src/NzbDrone.Core/Datastore/IEmbeddedDocument.cs index 14a1587b7..d1fada65f 100644 --- a/src/NzbDrone.Core/Datastore/IEmbeddedDocument.cs +++ b/src/NzbDrone.Core/Datastore/IEmbeddedDocument.cs @@ -3,4 +3,4 @@ public interface IEmbeddedDocument { } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/LazyList.cs b/src/NzbDrone.Core/Datastore/LazyList.cs index 17d0aba02..193a11812 100644 --- a/src/NzbDrone.Core/Datastore/LazyList.cs +++ b/src/NzbDrone.Core/Datastore/LazyList.cs @@ -8,13 +8,11 @@ namespace NzbDrone.Core.Datastore public LazyList() : this(new List()) { - } public LazyList(IEnumerable items) : base(new List(items)) { - } public static implicit operator LazyList(List val) @@ -27,4 +25,4 @@ namespace NzbDrone.Core.Datastore return lazy.Value; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/LogDatabase.cs b/src/NzbDrone.Core/Datastore/LogDatabase.cs index e9267ea37..7e15d1549 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 52736828c..4e5cbd780 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 d6cdaa68c..7d6d9a190 100644 --- a/src/NzbDrone.Core/Datastore/Migration/001_initial_setup.cs +++ b/src/NzbDrone.Core/Datastore/Migration/001_initial_setup.cs @@ -76,7 +76,6 @@ namespace NzbDrone.Core.Datastore.Migration .WithColumn("AddOptions").AsString().Nullable() .WithColumn("Duration").AsInt32().WithDefaultValue(0); - Create.TableForModel("Tracks") .WithColumn("ForeignTrackId").AsString().Unique() .WithColumn("ArtistId").AsInt32().Indexed() @@ -208,7 +207,6 @@ namespace NzbDrone.Core.Datastore.Migration .WithColumn("ArtistId").AsInt32().WithDefaultValue(0) .WithColumn("ParsedAlbumInfo").AsString().WithDefaultValue(""); - Create.TableForModel("RemotePathMappings") .WithColumn("Host").AsString() .WithColumn("RemotePath").AsString() diff --git a/src/NzbDrone.Core/Datastore/Migration/003_add_medium_support.cs b/src/NzbDrone.Core/Datastore/Migration/003_add_medium_support.cs index aed0dab79..f0b68d390 100644 --- a/src/NzbDrone.Core/Datastore/Migration/003_add_medium_support.cs +++ b/src/NzbDrone.Core/Datastore/Migration/003_add_medium_support.cs @@ -13,10 +13,9 @@ namespace NzbDrone.Core.Datastore.Migration Alter.Table("Tracks").AddColumn("AbsoluteTrackNumber").AsInt32().WithDefaultValue(0); Execute.Sql("UPDATE Tracks SET AbsoluteTrackNumber = TrackNumber"); - + Delete.Column("TrackNumber").FromTable("Tracks"); Alter.Table("Tracks").AddColumn("TrackNumber").AsString().Nullable(); - } } } diff --git a/src/NzbDrone.Core/Datastore/Migration/004_add_various_qualities_in_profile.cs b/src/NzbDrone.Core/Datastore/Migration/004_add_various_qualities_in_profile.cs index 9d74ba404..cabed21e5 100644 --- a/src/NzbDrone.Core/Datastore/Migration/004_add_various_qualities_in_profile.cs +++ b/src/NzbDrone.Core/Datastore/Migration/004_add_various_qualities_in_profile.cs @@ -25,45 +25,62 @@ namespace NzbDrone.Core.Datastore.Migration updater.MoveQuality(Qualities4.MP3_160, Qualities4.Unknown); - updater.CreateNewGroup(Qualities4.Unknown, 1000, "Trash Quality Lossy", new[] { Qualities4.MP3_080, - Qualities4.MP3_064, - Qualities4.MP3_056, - Qualities4.MP3_048, - Qualities4.MP3_040, - Qualities4.MP3_032, - Qualities4.MP3_024, - Qualities4.MP3_016, - Qualities4.MP3_008 }); + updater.CreateNewGroup(Qualities4.Unknown, 1000, "Trash Quality Lossy", new[] + { + Qualities4.MP3_080, + Qualities4.MP3_064, + Qualities4.MP3_056, + Qualities4.MP3_048, + Qualities4.MP3_040, + Qualities4.MP3_032, + Qualities4.MP3_024, + Qualities4.MP3_016, + Qualities4.MP3_008 + }); - updater.CreateGroupAt(Qualities4.MP3_160, 1001, "Poor Quality Lossy", new[] { Qualities4.MP3_160, - Qualities4.VORBIS_Q5, - Qualities4.MP3_128, - Qualities4.MP3_096, - Qualities4.MP3_112 }); // Group Vorbis-Q5 with MP3-160 + updater.CreateGroupAt(Qualities4.MP3_160, 1001, "Poor Quality Lossy", new[] + { + Qualities4.MP3_160, + Qualities4.VORBIS_Q5, + Qualities4.MP3_128, + Qualities4.MP3_096, + Qualities4.MP3_112 + }); // Group Vorbis-Q5 with MP3-160 - updater.CreateGroupAt(Qualities4.MP3_192, 1002, "Low Quality Lossy", new[] { Qualities4.MP3_192, - Qualities4.AAC_192, - Qualities4.VORBIS_Q6, - Qualities4.WMA, - Qualities4.MP3_224 }); // Group Vorbis-Q6, AAC 192, WMA with MP3-190 + updater.CreateGroupAt(Qualities4.MP3_192, 1002, "Low Quality Lossy", new[] + { + Qualities4.MP3_192, + Qualities4.AAC_192, + Qualities4.VORBIS_Q6, + Qualities4.WMA, + Qualities4.MP3_224 + }); // Group Vorbis-Q6, AAC 192, WMA with MP3-190 - updater.CreateGroupAt(Qualities4.MP3_256, 1003, "Mid Quality Lossy", new[] { Qualities4.MP3_256, - Qualities4.MP3_VBR_V2, - Qualities4.VORBIS_Q8, - Qualities4.VORBIS_Q7, - Qualities4.AAC_256 }); // Group Mp3-VBR-V2, Vorbis-Q7, Q8, AAC-256 with MP3-256 + updater.CreateGroupAt(Qualities4.MP3_256, 1003, "Mid Quality Lossy", new[] + { + Qualities4.MP3_256, + Qualities4.MP3_VBR_V2, + Qualities4.VORBIS_Q8, + Qualities4.VORBIS_Q7, + Qualities4.AAC_256 + }); // Group Mp3-VBR-V2, Vorbis-Q7, Q8, AAC-256 with MP3-256 - updater.CreateGroupAt(Qualities4.MP3_320, 1004, "High Quality Lossy", new[] { Qualities4.MP3_VBR, - Qualities4.MP3_320, - Qualities4.AAC_320, - Qualities4.AAC_VBR, - Qualities4.VORBIS_Q10, - Qualities4.VORBIS_Q9 }); // Group MP3-VBR-V0, AAC-VBR, Vorbis-Q10, Q9, AAC-320 with MP3-320 - - updater.CreateGroupAt(Qualities4.FLAC, 1005, "Lossless", new[] { Qualities4.FLAC, - Qualities4.ALAC, - Qualities4.FLAC_24 }); // Group ALAC with FLAC + updater.CreateGroupAt(Qualities4.MP3_320, 1004, "High Quality Lossy", new[] + { + Qualities4.MP3_VBR, + Qualities4.MP3_320, + Qualities4.AAC_320, + Qualities4.AAC_VBR, + Qualities4.VORBIS_Q10, + Qualities4.VORBIS_Q9 + }); // Group MP3-VBR-V0, AAC-VBR, Vorbis-Q10, Q9, AAC-320 with MP3-320 + updater.CreateGroupAt(Qualities4.FLAC, 1005, "Lossless", new[] + { + Qualities4.FLAC, + Qualities4.ALAC, + Qualities4.FLAC_24 + }); // Group ALAC with FLAC updater.Commit(); } @@ -179,7 +196,6 @@ namespace NzbDrone.Core.Datastore.Migration Allowed = false }); } - } public void CreateGroupAt(Qualities4 find, int groupId, string name, Qualities4[] qualities) @@ -208,7 +224,6 @@ namespace NzbDrone.Core.Datastore.Migration else { // If the ID isn't found for some reason (mangled migration 71?) - profile.Items.Add(new ProfileItem4 { Id = groupId, @@ -250,7 +265,6 @@ namespace NzbDrone.Core.Datastore.Migration if (findIndex > -1) { - profile.Items.Insert(findIndex, new ProfileItem4 { Id = groupId, @@ -266,7 +280,6 @@ namespace NzbDrone.Core.Datastore.Migration } else { - profile.Items.Add(new ProfileItem4 { Id = groupId, @@ -300,8 +313,6 @@ namespace NzbDrone.Core.Datastore.Migration Allowed = allowed }); } - - } } diff --git a/src/NzbDrone.Core/Datastore/Migration/005_metadata_profiles.cs b/src/NzbDrone.Core/Datastore/Migration/005_metadata_profiles.cs index 8f226de3f..6ed887581 100644 --- a/src/NzbDrone.Core/Datastore/Migration/005_metadata_profiles.cs +++ b/src/NzbDrone.Core/Datastore/Migration/005_metadata_profiles.cs @@ -19,7 +19,6 @@ namespace NzbDrone.Core.Datastore.Migration Delete.Column("SecondaryAlbumTypes").FromTable("Artists"); Alter.Table("Albums").AddColumn("SecondaryTypes").AsString().Nullable(); - } } } diff --git a/src/NzbDrone.Core/Datastore/Migration/012_add_release_status.cs b/src/NzbDrone.Core/Datastore/Migration/012_add_release_status.cs index c586d533c..cd1de385b 100644 --- a/src/NzbDrone.Core/Datastore/Migration/012_add_release_status.cs +++ b/src/NzbDrone.Core/Datastore/Migration/012_add_release_status.cs @@ -1,8 +1,6 @@ using System.Collections.Generic; using System.Data; -using System.Linq; using FluentMigrator; -using Newtonsoft.Json; using NzbDrone.Common.Serializer; using NzbDrone.Core.Datastore.Migration.Framework; @@ -45,7 +43,7 @@ namespace NzbDrone.Core.Datastore.Migration Bootleg = 2, Pseudo = 3 } - + public class ProfileUpdater11 { private readonly IDbConnection _connection; diff --git a/src/NzbDrone.Core/Datastore/Migration/019_add_ape_quality_in_profiles.cs b/src/NzbDrone.Core/Datastore/Migration/019_add_ape_quality_in_profiles.cs index 97b4e0938..1bb698528 100644 --- a/src/NzbDrone.Core/Datastore/Migration/019_add_ape_quality_in_profiles.cs +++ b/src/NzbDrone.Core/Datastore/Migration/019_add_ape_quality_in_profiles.cs @@ -21,7 +21,7 @@ namespace NzbDrone.Core.Datastore.Migration var updater = new ProfileUpdater19(conn, tran); updater.SplitQualityAppend(6, 35); // APE after Flac - updater.SplitQualityAppend(6, 36); // WavPack after Flac + updater.SplitQualityAppend(6, 36); // WavPack after Flac updater.Commit(); } @@ -88,7 +88,10 @@ namespace NzbDrone.Core.Datastore.Migration { 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 => { diff --git a/src/NzbDrone.Core/Datastore/Migration/023_add_release_groups_etc.cs b/src/NzbDrone.Core/Datastore/Migration/023_add_release_groups_etc.cs index 8995d07b6..5e5a58c0a 100644 --- a/src/NzbDrone.Core/Datastore/Migration/023_add_release_groups_etc.cs +++ b/src/NzbDrone.Core/Datastore/Migration/023_add_release_groups_etc.cs @@ -1,12 +1,12 @@ -using FluentMigrator; -using NzbDrone.Core.Datastore.Migration.Framework; -using NzbDrone.Common.Serializer; -using System.Collections.Generic; -using NzbDrone.Core.Music; -using System.Data; using System; +using System.Collections.Generic; +using System.Data; using System.Linq; +using FluentMigrator; using NzbDrone.Common.Extensions; +using NzbDrone.Common.Serializer; +using NzbDrone.Core.Datastore.Migration.Framework; +using NzbDrone.Core.Music; namespace NzbDrone.Core.Datastore.Migration { @@ -16,7 +16,6 @@ namespace NzbDrone.Core.Datastore.Migration protected override void MainDbUpgrade() { // ARTISTS TABLE - Create.TableForModel("ArtistMetadata") .WithColumn("ForeignArtistId").AsString().Unique() .WithColumn("Name").AsString() @@ -34,7 +33,7 @@ namespace NzbDrone.Core.Datastore.Migration Execute.Sql(@"INSERT INTO ArtistMetadata (ForeignArtistId, Name, Overview, Disambiguation, Type, Status, Images, Links, Genres, Ratings, Members) SELECT ForeignArtistId, Name, Overview, Disambiguation, ArtistType, Status, Images, Links, Genres, Ratings, Members FROM Artists"); - + // Add an ArtistMetadataId column to Artists Alter.Table("Artists").AddColumn("ArtistMetadataId").AsInt32().WithDefaultValue(0); @@ -45,7 +44,6 @@ namespace NzbDrone.Core.Datastore.Migration WHERE ArtistMetadata.ForeignArtistId = Artists.ForeignArtistId)"); // ALBUM RELEASES TABLE - Do this before we mess with the Albums table - Create.TableForModel("AlbumReleases") .WithColumn("ForeignReleaseId").AsString().Unique() .WithColumn("AlbumId").AsInt32().Indexed() @@ -75,12 +73,12 @@ namespace NzbDrone.Core.Datastore.Migration FROM ArtistMetadata JOIN Artists ON ArtistMetadata.Id = Artists.ArtistMetadataId WHERE Albums.ArtistId = Artists.Id)"); - + // TRACKS TABLE Alter.Table("Tracks").AddColumn("ForeignRecordingId").AsString().WithDefaultValue("0"); Alter.Table("Tracks").AddColumn("AlbumReleaseId").AsInt32().WithDefaultValue(0); Alter.Table("Tracks").AddColumn("ArtistMetadataId").AsInt32().WithDefaultValue(0); - + // Set track release to the only release we've bothered populating Execute.Sql(@"UPDATE Tracks SET AlbumReleaseId = (SELECT AlbumReleases.Id @@ -109,6 +107,7 @@ namespace NzbDrone.Core.Datastore.Migration .Column("Genres") .Column("Ratings") .Column("Members") + // as well as the ones no longer used .Column("MBId") .Column("AMId") @@ -146,7 +145,7 @@ namespace NzbDrone.Core.Datastore.Migration // Remove old columns from TrackFiles Delete.Column("ArtistId").FromTable("TrackFiles"); - + // Add indices Create.Index().OnTable("Artists").OnColumn("ArtistMetadataId").Ascending(); Create.Index().OnTable("Artists").OnColumn("Monitored").Ascending(); @@ -156,12 +155,11 @@ namespace NzbDrone.Core.Datastore.Migration Create.Index().OnTable("Tracks").OnColumn("ForeignRecordingId").Ascending(); // Force a metadata refresh - Update.Table("Artists").Set(new { LastInfoSync = new System.DateTime(2018, 1, 1, 0, 0, 1)}).AllRows(); - Update.Table("Albums").Set(new { LastInfoSync = new System.DateTime(2018, 1, 1, 0, 0, 1)}).AllRows(); + Update.Table("Artists").Set(new { LastInfoSync = new System.DateTime(2018, 1, 1, 0, 0, 1) }).AllRows(); + Update.Table("Albums").Set(new { LastInfoSync = new System.DateTime(2018, 1, 1, 0, 0, 1) }).AllRows(); Update.Table("ScheduledTasks") - .Set(new { LastExecution = new System.DateTime(2018, 1, 1, 0, 0, 1)}) + .Set(new { LastExecution = new System.DateTime(2018, 1, 1, 0, 0, 1) }) .Where(new { TypeName = "NzbDrone.Core.Music.Commands.RefreshArtistCommand" }); - } private void PopulateReleases(IDbConnection conn, IDbTransaction tran) @@ -173,6 +171,7 @@ namespace NzbDrone.Core.Datastore.Migration { release.ForeignReleaseId = release.AlbumId.ToString(); } + WriteReleasesToReleases(releases, conn, tran); } @@ -191,7 +190,6 @@ namespace NzbDrone.Core.Datastore.Migration private List ReadReleasesFromAlbums(IDbConnection conn, IDbTransaction tran) { - // need to get all the old albums var releases = new List(); @@ -213,26 +211,28 @@ namespace NzbDrone.Core.Datastore.Migration var media = new List(); for (var i = 1; i <= Math.Max(albumRelease.MediaCount, 1); i++) { - media.Add(new Medium { Number = i, Name = "", Format = albumRelease.Format ?? "Unknown" } ); + media.Add(new Medium { Number = i, Name = "", Format = albumRelease.Format ?? "Unknown" }); } - - toInsert = new AlbumRelease { - AlbumId = albumId, - ForeignReleaseId = albumRelease.Id.IsNotNullOrWhiteSpace() ? albumRelease.Id : albumId.ToString(), - Title = albumRelease.Title.IsNotNullOrWhiteSpace() ? albumRelease.Title : "", - Status = "", - Duration = 0, - Label = albumRelease.Label, - Disambiguation = albumRelease.Disambiguation, - Country = albumRelease.Country, - Media = media, - TrackCount = albumRelease.TrackCount, - Monitored = true - }; + + toInsert = new AlbumRelease + { + AlbumId = albumId, + ForeignReleaseId = albumRelease.Id.IsNotNullOrWhiteSpace() ? albumRelease.Id : albumId.ToString(), + Title = albumRelease.Title.IsNotNullOrWhiteSpace() ? albumRelease.Title : "", + Status = "", + Duration = 0, + Label = albumRelease.Label, + Disambiguation = albumRelease.Disambiguation, + Country = albumRelease.Country, + Media = media, + TrackCount = albumRelease.TrackCount, + Monitored = true + }; } else { - toInsert = new AlbumRelease { + toInsert = new AlbumRelease + { AlbumId = albumId, ForeignReleaseId = albumId.ToString(), Title = "", diff --git a/src/NzbDrone.Core/Datastore/Migration/029_health_issue_notification.cs b/src/NzbDrone.Core/Datastore/Migration/029_health_issue_notification.cs index 9456f8544..4407daef6 100644 --- a/src/NzbDrone.Core/Datastore/Migration/029_health_issue_notification.cs +++ b/src/NzbDrone.Core/Datastore/Migration/029_health_issue_notification.cs @@ -16,7 +16,7 @@ namespace NzbDrone.Core.Datastore.Migration Alter.Table("Notifications").AddColumn("OnTrackRetag").AsBoolean().WithDefaultValue(0); Delete.Column("OnDownload").FromTable("Notifications"); - + Rename.Column("OnAlbumDownload").OnTable("Notifications").To("OnReleaseImport"); } } diff --git a/src/NzbDrone.Core/Datastore/Migration/030_add_mediafilerepository_mtime.cs b/src/NzbDrone.Core/Datastore/Migration/030_add_mediafilerepository_mtime.cs index 0645eb54b..971f1cc41 100644 --- a/src/NzbDrone.Core/Datastore/Migration/030_add_mediafilerepository_mtime.cs +++ b/src/NzbDrone.Core/Datastore/Migration/030_add_mediafilerepository_mtime.cs @@ -45,7 +45,7 @@ namespace NzbDrone.Core.Datastore.Migration FROM Artists JOIN Albums ON Albums.ArtistMetadataId = Artists.ArtistMetadataId WHERE TrackFiles.AlbumId = Albums.Id)"); - + // Belt and braces to ensure uniqueness Execute.Sql(@"DELETE FROM TrackFiles WHERE rowid NOT IN ( @@ -53,7 +53,7 @@ namespace NzbDrone.Core.Datastore.Migration FROM TrackFiles GROUP BY Path )"); - + // Now enforce the uniqueness constraint Alter.Table("TrackFiles").AlterColumn("Path").AsString().NotNullable().Unique(); diff --git a/src/NzbDrone.Core/Datastore/Migration/031_add_artistmetadataid_constraint.cs b/src/NzbDrone.Core/Datastore/Migration/031_add_artistmetadataid_constraint.cs index 8dfefa4b8..0f7fda558 100644 --- a/src/NzbDrone.Core/Datastore/Migration/031_add_artistmetadataid_constraint.cs +++ b/src/NzbDrone.Core/Datastore/Migration/031_add_artistmetadataid_constraint.cs @@ -17,7 +17,7 @@ namespace NzbDrone.Core.Datastore.Migration // The index exists but will be recreated as part of unique constraint Delete.Index().OnTable("Artists").OnColumn("ArtistMetadataId"); - + // Add a constraint to prevent any more duplicates Alter.Column("ArtistMetadataId").OnTable("Artists").AsInt32().Unique(); } diff --git a/src/NzbDrone.Core/Datastore/Migration/032_old_ids_and_artist_alias.cs b/src/NzbDrone.Core/Datastore/Migration/032_old_ids_and_artist_alias.cs index f2df39fdc..7e535b477 100644 --- a/src/NzbDrone.Core/Datastore/Migration/032_old_ids_and_artist_alias.cs +++ b/src/NzbDrone.Core/Datastore/Migration/032_old_ids_and_artist_alias.cs @@ -9,7 +9,7 @@ namespace NzbDrone.Core.Datastore.Migration protected override void MainDbUpgrade() { Alter.Table("ArtistMetadata").AddColumn("Aliases").AsString().WithDefaultValue("[]"); - + Alter.Table("ArtistMetadata").AddColumn("OldForeignArtistIds").AsString().WithDefaultValue("[]"); Alter.Table("Albums").AddColumn("OldForeignAlbumIds").AsString().WithDefaultValue("[]"); Alter.Table("AlbumReleases").AddColumn("OldForeignReleaseIds").AsString().WithDefaultValue("[]"); diff --git a/src/NzbDrone.Core/Datastore/Migration/035_multi_disc_naming_format.cs b/src/NzbDrone.Core/Datastore/Migration/035_multi_disc_naming_format.cs index e1f9b915b..493b60013 100644 --- a/src/NzbDrone.Core/Datastore/Migration/035_multi_disc_naming_format.cs +++ b/src/NzbDrone.Core/Datastore/Migration/035_multi_disc_naming_format.cs @@ -1,7 +1,5 @@ using FluentMigrator; using NzbDrone.Core.Datastore.Migration.Framework; -using System.Data; -using System.IO; namespace NzbDrone.Core.Datastore.Migration { diff --git a/src/NzbDrone.Core/Datastore/Migration/036_add_download_client_priority.cs b/src/NzbDrone.Core/Datastore/Migration/036_add_download_client_priority.cs index be0508c3d..3c3e1192e 100644 --- a/src/NzbDrone.Core/Datastore/Migration/036_add_download_client_priority.cs +++ b/src/NzbDrone.Core/Datastore/Migration/036_add_download_client_priority.cs @@ -18,7 +18,6 @@ namespace NzbDrone.Core.Datastore.Migration { 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/Framework/MigrationController.cs b/src/NzbDrone.Core/Datastore/Migration/Framework/MigrationController.cs index b90d3de7c..e49b7b493 100644 --- a/src/NzbDrone.Core/Datastore/Migration/Framework/MigrationController.cs +++ b/src/NzbDrone.Core/Datastore/Migration/Framework/MigrationController.cs @@ -42,10 +42,11 @@ namespace NzbDrone.Core.Datastore.Migration.Framework .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/NzbDroneSQLiteProcessor.cs b/src/NzbDrone.Core/Datastore/Migration/Framework/NzbDroneSQLiteProcessor.cs index 290916aa3..25e39685f 100644 --- a/src/NzbDrone.Core/Datastore/Migration/Framework/NzbDroneSQLiteProcessor.cs +++ b/src/NzbDrone.Core/Datastore/Migration/Framework/NzbDroneSQLiteProcessor.cs @@ -79,6 +79,7 @@ namespace NzbDrone.Core.Datastore.Migration.Framework { throw new ApplicationException(string.Format("Column {0} does not exist on table {1}.", expression.OldName, expression.TableName)); } + if (columnDefinitions.Any(c => c.Name == expression.NewName)) { throw new ApplicationException(string.Format("Column {0} already exists on table {1}.", expression.NewName, expression.TableName)); @@ -106,7 +107,6 @@ namespace NzbDrone.Core.Datastore.Migration.Framework ProcessAlterTable(tableDefinition, oldColumnDefinitions); } - protected virtual TableDefinition GetTableSchema(string tableName) { var schemaDumper = new SqliteSchemaDumper(this); @@ -131,7 +131,6 @@ namespace NzbDrone.Core.Datastore.Migration.Framework var columnsToInsert = string.Join(", ", tableDefinition.Columns.Select(c => quoter.QuoteColumnName(c.Name))); var columnsToFetch = string.Join(", ", (oldColumnDefinitions ?? tableDefinition.Columns).Select(c => quoter.QuoteColumnName(c.Name))); - Process(new CreateTableExpression() { TableName = tempTableName, Columns = tableDefinition.Columns.ToList() }); Process(string.Format("INSERT INTO {0} ({1}) SELECT {2} FROM {3}", quoter.QuoteTableName(tempTableName), columnsToInsert, columnsToFetch, quoter.QuoteTableName(tableName))); diff --git a/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSchemaDumper.cs b/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSchemaDumper.cs index 6b8dc19ca..57b984c5a 100644 --- a/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSchemaDumper.cs +++ b/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSchemaDumper.cs @@ -38,7 +38,9 @@ namespace NzbDrone.Core.Datastore.Migration.Framework { 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") { @@ -87,7 +89,7 @@ namespace NzbDrone.Core.Datastore.Migration.Framework var column = new ColumnDefinition(); column.Name = ParseIdentifier(reader); - + reader.TrimBuffer(); reader.Read(); @@ -114,7 +116,10 @@ namespace NzbDrone.Core.Datastore.Migration.Framework 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") { @@ -131,7 +136,7 @@ namespace NzbDrone.Core.Datastore.Migration.Framework reader.Read(); // ON index.TableName = ParseIdentifier(reader); - + // Find Column List reader.SkipTillToken(SqliteSyntaxReader.TokenType.ListStart); @@ -175,22 +180,19 @@ namespace NzbDrone.Core.Datastore.Migration.Framework 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 @@ namespace NzbDrone.Core.Datastore.Migration.Framework tableDefinitionList.Add(table); } + return tableDefinitionList; } @@ -252,6 +255,7 @@ namespace NzbDrone.Core.Datastore.Migration.Framework 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 703aff012..4940eac93 100644 --- a/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSyntaxReader.cs +++ b/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSyntaxReader.cs @@ -5,7 +5,6 @@ using System.Text; namespace NzbDrone.Core.Datastore.Migration.Framework { - public class SqliteSyntaxReader { public string Buffer { get; private set; } @@ -48,18 +47,25 @@ namespace NzbDrone.Core.Datastore.Migration.Framework 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 @@ namespace NzbDrone.Core.Datastore.Migration.Framework { 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 @@ namespace NzbDrone.Core.Datastore.Migration.Framework { throw CreateSyntaxException("Unexpected sequence."); } + Type = TokenType.StringToken; Value = Buffer.Substring(start, end - start); return Type; @@ -191,6 +201,7 @@ namespace NzbDrone.Core.Datastore.Migration.Framework { throw CreateSyntaxException("Expected ListEnd first"); } + if (Type == TokenType.ListStart) { SkipTillToken(TokenType.ListEnd); @@ -215,7 +226,10 @@ namespace NzbDrone.Core.Datastore.Migration.Framework 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 @@ namespace NzbDrone.Core.Datastore.Migration.Framework 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 1a680f0d8..9917cfc47 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"); @@ -13,9 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// -#endregion - using System; using System.Collections.Generic; diff --git a/src/NzbDrone.Core/Datastore/ModelConflictException.cs b/src/NzbDrone.Core/Datastore/ModelConflictException.cs index 66c7f94ff..f313e3444 100644 --- a/src/NzbDrone.Core/Datastore/ModelConflictException.cs +++ b/src/NzbDrone.Core/Datastore/ModelConflictException.cs @@ -8,13 +8,11 @@ namespace NzbDrone.Core.Datastore 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) { - } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/ModelNotFoundException.cs b/src/NzbDrone.Core/Datastore/ModelNotFoundException.cs index 8241fd344..b9ad28da9 100644 --- a/src/NzbDrone.Core/Datastore/ModelNotFoundException.cs +++ b/src/NzbDrone.Core/Datastore/ModelNotFoundException.cs @@ -8,7 +8,6 @@ namespace NzbDrone.Core.Datastore public ModelNotFoundException(Type modelType, int modelId) : base("{0} with ID {1} does not exist", modelType.Name, modelId) { - } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/ResultSet.cs b/src/NzbDrone.Core/Datastore/ResultSet.cs index 2bb2b4169..7e67fff09 100644 --- a/src/NzbDrone.Core/Datastore/ResultSet.cs +++ b/src/NzbDrone.Core/Datastore/ResultSet.cs @@ -3,4 +3,4 @@ public class ResultSet { } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Datastore/TableMapping.cs b/src/NzbDrone.Core/Datastore/TableMapping.cs index 3e26f648d..7de8046fd 100644 --- a/src/NzbDrone.Core/Datastore/TableMapping.cs +++ b/src/NzbDrone.Core/Datastore/TableMapping.cs @@ -3,42 +3,42 @@ using System.Collections.Generic; using System.Linq; using Marr.Data; using Marr.Data.Mapping; +using Marr.Data.QGen; +using NzbDrone.Common.Disk; using NzbDrone.Common.Reflection; +using NzbDrone.Core.ArtistStats; +using NzbDrone.Core.Authentication; using NzbDrone.Core.Blacklisting; using NzbDrone.Core.Configuration; +using NzbDrone.Core.CustomFilters; 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.ImportLists; -using NzbDrone.Core.ImportLists.Exclusions; -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.Metadata; -using NzbDrone.Core.Profiles.Qualities; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.RootFolders; -using NzbDrone.Core.ArtistStats; -using NzbDrone.Core.Tags; -using NzbDrone.Core.ThingiProvider; -using NzbDrone.Common.Disk; -using NzbDrone.Core.Authentication; -using NzbDrone.Core.CustomFilters; +using NzbDrone.Core.Extras.Lyrics; using NzbDrone.Core.Extras.Metadata; using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.Extras.Others; -using NzbDrone.Core.Extras.Lyrics; +using NzbDrone.Core.ImportLists; +using NzbDrone.Core.ImportLists.Exclusions; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.Instrumentation; +using NzbDrone.Core.Jobs; +using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Music; -using Marr.Data.QGen; +using NzbDrone.Core.Notifications; +using NzbDrone.Core.Organizer; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Profiles.Delay; +using NzbDrone.Core.Profiles.Metadata; +using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Profiles.Releases; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.RootFolders; +using NzbDrone.Core.Tags; +using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Core.Datastore { @@ -79,7 +79,7 @@ namespace NzbDrone.Core.Datastore .Ignore(i => i.SupportsOnDownloadFailure) .Ignore(i => i.SupportsOnImportFailure) .Ignore(i => i.SupportsOnTrackRetag); - + Mapper.Entity().RegisterDefinition("Metadata") .Ignore(d => d.Tags); diff --git a/src/NzbDrone.Core/DecisionEngine/DownloadDecision.cs b/src/NzbDrone.Core/DecisionEngine/DownloadDecision.cs index c9d306ae8..021648540 100644 --- a/src/NzbDrone.Core/DecisionEngine/DownloadDecision.cs +++ b/src/NzbDrone.Core/DecisionEngine/DownloadDecision.cs @@ -43,4 +43,4 @@ namespace NzbDrone.Core.DecisionEngine return "[Rejected " + Rejections.Count() + "]" + RemoteAlbum; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionComparer.cs b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionComparer.cs index ca2178ffd..6b674f65f 100644 --- a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionComparer.cs +++ b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionComparer.cs @@ -91,7 +91,8 @@ namespace NzbDrone.Core.DecisionEngine private int CompareAlbumCount(DownloadDecision x, DownloadDecision y) { - var discographyCompare = CompareBy(x.RemoteAlbum, y.RemoteAlbum, + var discographyCompare = CompareBy(x.RemoteAlbum, + y.RemoteAlbum, remoteAlbum => remoteAlbum.ParsedAlbumInfo.Discography); if (discographyCompare != 0) @@ -162,7 +163,6 @@ namespace NzbDrone.Core.DecisionEngine private int CompareSize(DownloadDecision x, DownloadDecision y) { // TODO: Is smaller better? Smaller for usenet could mean no par2 files. - return CompareBy(x.RemoteAlbum, y.RemoteAlbum, remoteAlbum => remoteAlbum.Release.Size.Round(200.Megabytes())); } } diff --git a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionMaker.cs b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionMaker.cs index 693f0797a..897db56e4 100644 --- a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionMaker.cs +++ b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionMaker.cs @@ -73,7 +73,8 @@ namespace NzbDrone.Core.DecisionEngine if (parsedAlbumInfo == null && searchCriteria != null) { parsedAlbumInfo = Parser.Parser.ParseAlbumTitleWithSearchCriteria(report.Title, - searchCriteria.Artist, searchCriteria.Albums); + searchCriteria.Artist, + searchCriteria.Albums); } if (parsedAlbumInfo != null) @@ -92,7 +93,6 @@ namespace NzbDrone.Core.DecisionEngine //{ // parsedAlbumInfo.AlbumTitle = report.Album; //} - if (!parsedAlbumInfo.ArtistName.IsNullOrWhiteSpace()) { var remoteAlbum = _parsingService.Map(parsedAlbumInfo, searchCriteria); @@ -116,6 +116,7 @@ namespace NzbDrone.Core.DecisionEngine if (remoteAlbum.Artist == null) { decision = new DownloadDecision(remoteAlbum, new Rejection("Unknown Artist")); + // shove in the searched artist in case of forced download in interactive search if (searchCriteria != null) { @@ -156,7 +157,6 @@ namespace NzbDrone.Core.DecisionEngine { _logger.Debug("Release rejected for the following reasons: {0}", string.Join(", ", decision.Rejections)); } - else { _logger.Debug("Release accepted"); @@ -177,8 +177,12 @@ namespace NzbDrone.Core.DecisionEngine .Where(c => c != null) .ToArray(); - if (reasons.Any()) break; + if (reasons.Any()) + { + break; + } } + return new DownloadDecision(remoteAlbum, reasons.ToArray()); } diff --git a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionPriorizationService.cs b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionPriorizationService.cs index a8e683e77..f7b55535b 100644 --- a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionPriorizationService.cs +++ b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionPriorizationService.cs @@ -1,5 +1,5 @@ -using System.Linq; using System.Collections.Generic; +using System.Linq; using NzbDrone.Core.Configuration; using NzbDrone.Core.Profiles.Delay; diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/AcceptableSizeSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/AcceptableSizeSpecification.cs index 294ae477b..98e76ae7a 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/AcceptableSizeSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/AcceptableSizeSpecification.cs @@ -4,7 +4,6 @@ using NzbDrone.Common.Extensions; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; -using System.Collections.Generic; namespace NzbDrone.Core.DecisionEngine.Specifications { @@ -21,7 +20,7 @@ namespace NzbDrone.Core.DecisionEngine.Specifications public SpecificationPriority Priority => SpecificationPriority.Default; public RejectionType Type => RejectionType.Permanent; - + public Decision IsSatisfiedBy(RemoteAlbum subject, SearchCriteriaBase searchCriteria) { _logger.Debug("Beginning size check for: {0}", subject); @@ -53,6 +52,7 @@ namespace NzbDrone.Core.DecisionEngine.Specifications return Decision.Reject("{0} is smaller than minimum allowed {1}", subject.Release.Size.SizeSuffix(), minSize.SizeSuffix()); } } + if (!qualityDefinition.MaxSize.HasValue || qualityDefinition.MaxSize.Value == 0) { _logger.Debug("Max size is unlimited - skipping check."); @@ -61,7 +61,7 @@ namespace NzbDrone.Core.DecisionEngine.Specifications { var maxSize = qualityDefinition.MaxSize.Value.Kilobits(); var maxReleaseDuration = subject.Albums.Select(a => a.AlbumReleases.Value.Where(r => r.Monitored || a.AnyReleaseOk).Select(r => r.Duration).Max()).Sum() / 1000; - + //Multiply maxSize by Album.Duration maxSize = maxSize * maxReleaseDuration; diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/AlreadyImportedSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/AlreadyImportedSpecification.cs index 9e14277e2..027f599e6 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/AlreadyImportedSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/AlreadyImportedSpecification.cs @@ -77,7 +77,7 @@ namespace NzbDrone.Core.DecisionEngine.Specifications continue; } - var release = subject.Release; + var release = subject.Release; if (release.DownloadProtocol == DownloadProtocol.Torrent) { @@ -92,7 +92,6 @@ namespace NzbDrone.Core.DecisionEngine.Specifications // 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/CutoffSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/CutoffSpecification.cs index 0d04563c3..9dbd13506 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/CutoffSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/CutoffSpecification.cs @@ -1,13 +1,13 @@ using System; using System.Linq; using NLog; +using NzbDrone.Common.Cache; +using NzbDrone.Common.Extensions; using NzbDrone.Core.IndexerSearch.Definitions; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Music; -using NzbDrone.Common.Cache; +using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Releases; -using NzbDrone.Common.Extensions; namespace NzbDrone.Core.DecisionEngine.Specifications { @@ -19,7 +19,7 @@ namespace NzbDrone.Core.DecisionEngine.Specifications private readonly Logger _logger; private readonly ICached _missingFilesCache; private readonly IPreferredWordService _preferredWordServiceCalculator; - + public CutoffSpecification(UpgradableSpecification upgradableSpecification, Logger logger, ICacheManager cacheManager, @@ -44,8 +44,9 @@ namespace NzbDrone.Core.DecisionEngine.Specifications foreach (var album in subject.Albums) { - var tracksMissing = _missingFilesCache.Get(album.Id.ToString(), () => _trackService.TracksWithoutFiles(album.Id).Any(), - TimeSpan.FromSeconds(30)); + var tracksMissing = _missingFilesCache.Get(album.Id.ToString(), + () => _trackService.TracksWithoutFiles(album.Id).Any(), + TimeSpan.FromSeconds(30)); var trackFiles = _mediaFileService.GetFilesByAlbum(album.Id); if (!tracksMissing && trackFiles.Any()) @@ -68,7 +69,6 @@ namespace NzbDrone.Core.DecisionEngine.Specifications return Decision.Reject("Existing files meets cutoff: {0}", qualityCutoff); } - } } diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/DiscographySpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/DiscographySpecification.cs index e11ed8761..98ff0d304 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/DiscographySpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/DiscographySpecification.cs @@ -1,9 +1,9 @@ using System; +using System.Linq; using NLog; +using NzbDrone.Common.Extensions; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.Parser.Model; -using System.Linq; -using NzbDrone.Common.Extensions; namespace NzbDrone.Core.DecisionEngine.Specifications { diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/EarlyReleaseSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/EarlyReleaseSpecification.cs index 73fb277b2..4a3fbdef4 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/EarlyReleaseSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/EarlyReleaseSpecification.cs @@ -50,9 +50,12 @@ namespace NzbDrone.Core.DecisionEngine.Specifications var releaseDate = subject.Albums.First().ReleaseDate; - if (releaseDate == null) return Decision.Accept(); + if (releaseDate == null) + { + return Decision.Accept(); + } - var isEarly = (releaseDate.Value > subject.Release.PublishDate.AddDays(indexerSettings.EarlyReleaseLimit.Value)); + var isEarly = releaseDate.Value > subject.Release.PublishDate.AddDays(indexerSettings.EarlyReleaseLimit.Value); if (isEarly) { diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/MinimumAgeSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/MinimumAgeSpecification.cs index 3ec9b900e..3e322881d 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/MinimumAgeSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/MinimumAgeSpecification.cs @@ -38,7 +38,6 @@ namespace NzbDrone.Core.DecisionEngine.Specifications 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/NotSampleSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/NotSampleSpecification.cs index 825ca3c3d..6f7b454b4 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/NotSampleSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/NotSampleSpecification.cs @@ -1,4 +1,3 @@ -using System; using NLog; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.Parser.Model; @@ -19,14 +18,13 @@ namespace NzbDrone.Core.DecisionEngine.Specifications public Decision IsSatisfiedBy(RemoteAlbum subject, SearchCriteriaBase searchCriteria) { - if (subject.Release.Title.ToLower().Contains("sample") && subject.Release.Size < 20.Megabytes()) - { - _logger.Debug("Sample release, rejecting."); - return Decision.Reject("Sample"); - } + if (subject.Release.Title.ToLower().Contains("sample") && subject.Release.Size < 20.Megabytes()) + { + _logger.Debug("Sample release, rejecting."); + return Decision.Reject("Sample"); + } - return Decision.Accept(); + return Decision.Accept(); } - } } diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/QualityAllowedByProfileSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/QualityAllowedByProfileSpecification.cs index 73bb23fea..db5eebaec 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/QualityAllowedByProfileSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/QualityAllowedByProfileSpecification.cs @@ -1,4 +1,3 @@ -using System; using NLog; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.Parser.Model; diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/QueueSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/QueueSpecification.cs index 4ffda3d90..997e299a8 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/QueueSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/QueueSpecification.cs @@ -38,7 +38,6 @@ namespace NzbDrone.Core.DecisionEngine.Specifications q.RemoteAlbum.Albums.Select(e => e.Id).Intersect(subject.Albums.Select(e => e.Id)).Any()) .ToList(); - foreach (var queueItem in matchingAlbum) { var remoteAlbum = queueItem.RemoteAlbum; @@ -52,7 +51,6 @@ namespace NzbDrone.Core.DecisionEngine.Specifications queuedItemPreferredWordScore, subject.ParsedAlbumInfo.Quality, subject.PreferredWordScore)) - { return Decision.Reject("Release in queue already meets cutoff: {0}", remoteAlbum.ParsedAlbumInfo.Quality); } @@ -79,7 +77,6 @@ namespace NzbDrone.Core.DecisionEngine.Specifications } return Decision.Accept(); - } } } diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/RawDiskSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/RawDiskSpecification.cs index a6a6acd54..41a337336 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/RawDiskSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/RawDiskSpecification.cs @@ -27,11 +27,11 @@ namespace NzbDrone.Core.DecisionEngine.Specifications return Decision.Accept(); } - if (_cdContainerTypes.Contains(subject.Release.Container.ToLower())) - { - _logger.Debug("Release contains raw CD, rejecting."); - return Decision.Reject("Raw CD release"); - } + if (_cdContainerTypes.Contains(subject.Release.Container.ToLower())) + { + _logger.Debug("Release contains raw CD, rejecting."); + return Decision.Reject("Raw CD release"); + } return Decision.Accept(); } diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/RepackSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/RepackSpecification.cs index 3214c4c41..86198d776 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/RepackSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/RepackSpecification.cs @@ -58,7 +58,6 @@ namespace NzbDrone.Core.DecisionEngine.Specifications } } } - } return Decision.Accept(); diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/DelaySpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/DelaySpecification.cs index 5004f0d7b..623d66b97 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/DelaySpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/DelaySpecification.cs @@ -2,11 +2,11 @@ using System.Linq; using NLog; using NzbDrone.Core.Download.Pending; using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Delay; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Profiles.Releases; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.DecisionEngine.Specifications.RssSync { diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/DeletedTrackFileSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/DeletedTrackFileSpecification.cs index 45a25ce31..6543cf139 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/DeletedTrackFileSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/DeletedTrackFileSpecification.cs @@ -1,4 +1,3 @@ -using System.IO; using System.Linq; using NLog; using NzbDrone.Common.Disk; @@ -6,8 +5,8 @@ using NzbDrone.Common.Extensions; using NzbDrone.Core.Configuration; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Music; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.DecisionEngine.Specifications.RssSync { @@ -51,7 +50,6 @@ namespace NzbDrone.Core.DecisionEngine.Specifications.RssSync .Where(v => IsTrackFileMissing(subject.Artist, v)) .ToArray(); - if (missingTrackFiles.Any()) { foreach (var missingTrackFile in missingTrackFiles) diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/ProperSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/ProperSpecification.cs index b52615a51..03b63e3d2 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/ProperSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/ProperSpecification.cs @@ -1,10 +1,9 @@ using System; -using System.Linq; using NLog; using NzbDrone.Core.Configuration; using NzbDrone.Core.IndexerSearch.Definitions; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; namespace NzbDrone.Core.DecisionEngine.Specifications.RssSync diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/SameTracksSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/SameTracksSpecification.cs index dec6ac052..7cdbd5146 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/SameTracksSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/SameTracksSpecification.cs @@ -1,7 +1,5 @@ -using System; using System.Collections.Generic; using System.Linq; -using System.Text; using NzbDrone.Common.Extensions; using NzbDrone.Core.Music; diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/Search/AlbumRequestedSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/Search/AlbumRequestedSpecification.cs index 2be1a20b8..79c4a82b2 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/Search/AlbumRequestedSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/Search/AlbumRequestedSpecification.cs @@ -2,8 +2,6 @@ using System.Linq; using NLog; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Music; - namespace NzbDrone.Core.DecisionEngine.Specifications.Search { diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/Search/SingleAlbumSearchMatchSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/Search/SingleAlbumSearchMatchSpecification.cs index c2ea90be6..58543dcf1 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/Search/SingleAlbumSearchMatchSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/Search/SingleAlbumSearchMatchSpecification.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using NLog; using NzbDrone.Core.IndexerSearch.Definitions; @@ -30,7 +29,7 @@ namespace NzbDrone.Core.DecisionEngine.Specifications.Search { return Decision.Accept(); } - + if (Parser.Parser.CleanArtistName(singleAlbumSpec.AlbumTitle) != Parser.Parser.CleanArtistName(remoteAlbum.ParsedAlbumInfo.AlbumTitle)) { _logger.Debug("Album does not match searched album title, skipping."); diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/TorrentSeedingSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/TorrentSeedingSpecification.cs index 95b071a37..c98ae9f5a 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/TorrentSeedingSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/TorrentSeedingSpecification.cs @@ -20,7 +20,6 @@ namespace NzbDrone.Core.DecisionEngine.Specifications public SpecificationPriority Priority => SpecificationPriority.Default; public RejectionType Type => RejectionType.Permanent; - public Decision IsSatisfiedBy(RemoteAlbum remoteAlbum, SearchCriteriaBase searchCriteria) { var torrentInfo = remoteAlbum.Release as TorrentInfo; diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradableSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradableSpecification.cs index 1711b7ccf..a471d1028 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradableSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradableSpecification.cs @@ -1,9 +1,9 @@ +using System.Collections.Generic; +using System.Linq; using NLog; using NzbDrone.Core.Configuration; using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; -using System.Collections.Generic; -using System.Linq; namespace NzbDrone.Core.DecisionEngine.Specifications { @@ -47,7 +47,8 @@ namespace NzbDrone.Core.DecisionEngine.Specifications } // Not upgradable if new quality is equal to all current qualities - if (totalCompare == 0) { + if (totalCompare == 0) + { return ProfileComparisonResult.Equal; } @@ -71,7 +72,6 @@ namespace NzbDrone.Core.DecisionEngine.Specifications public bool IsUpgradable(QualityProfile qualityProfile, List currentQualities, int currentScore, QualityModel newQuality, int newScore) { - var qualityUpgrade = IsQualityUpgradable(qualityProfile, currentQualities, newQuality); if (qualityUpgrade == ProfileComparisonResult.Upgrade) @@ -154,7 +154,7 @@ namespace NzbDrone.Core.DecisionEngine.Specifications return CheckUpgradeAllowed(qualityProfile, isQualityUpgrade); } - private bool CheckUpgradeAllowed (QualityProfile qualityProfile, ProfileComparisonResult isQualityUpgrade) + private bool CheckUpgradeAllowed(QualityProfile qualityProfile, ProfileComparisonResult isQualityUpgrade) { if (isQualityUpgrade == ProfileComparisonResult.Upgrade && !qualityProfile.UpgradeAllowed) { diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeAllowedSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeAllowedSpecification.cs index 2ebc916c3..638ebcd30 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeAllowedSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeAllowedSpecification.cs @@ -1,13 +1,12 @@ using System; using System.Linq; using NLog; +using NzbDrone.Common.Cache; +using NzbDrone.Common.Extensions; using NzbDrone.Core.IndexerSearch.Definitions; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Music; -using NzbDrone.Common.Cache; -using NzbDrone.Core.Profiles.Releases; -using NzbDrone.Common.Extensions; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.DecisionEngine.Specifications { @@ -41,7 +40,8 @@ namespace NzbDrone.Core.DecisionEngine.Specifications foreach (var album in subject.Albums) { - var tracksMissing = _missingFilesCache.Get(album.Id.ToString(), () => _trackService.TracksWithoutFiles(album.Id).Any(), + var tracksMissing = _missingFilesCache.Get(album.Id.ToString(), + () => _trackService.TracksWithoutFiles(album.Id).Any(), TimeSpan.FromSeconds(30)); var trackFiles = _mediaFileService.GetFilesByAlbum(album.Id); @@ -61,7 +61,6 @@ namespace NzbDrone.Core.DecisionEngine.Specifications return Decision.Reject("Existing files and the Quality profile does not allow upgrades"); } - } } diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeDiskSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeDiskSpecification.cs index e1e75eb52..6f0d485b4 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeDiskSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeDiskSpecification.cs @@ -1,13 +1,13 @@ using System; using System.Linq; using NLog; +using NzbDrone.Common.Cache; +using NzbDrone.Common.Extensions; using NzbDrone.Core.IndexerSearch.Definitions; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Music; -using NzbDrone.Common.Cache; +using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Releases; -using NzbDrone.Common.Extensions; namespace NzbDrone.Core.DecisionEngine.Specifications { @@ -19,7 +19,7 @@ namespace NzbDrone.Core.DecisionEngine.Specifications private readonly IPreferredWordService _preferredWordServiceCalculator; private readonly Logger _logger; private readonly ICached _missingFilesCache; - + public UpgradeDiskSpecification(UpgradableSpecification qualityUpgradableSpecification, IMediaFileService mediaFileService, ITrackService trackService, @@ -40,10 +40,10 @@ namespace NzbDrone.Core.DecisionEngine.Specifications public virtual Decision IsSatisfiedBy(RemoteAlbum subject, SearchCriteriaBase searchCriteria) { - foreach (var album in subject.Albums) { - var tracksMissing = _missingFilesCache.Get(album.Id.ToString(), () => _trackService.TracksWithoutFiles(album.Id).Any(), + var tracksMissing = _missingFilesCache.Get(album.Id.ToString(), + () => _trackService.TracksWithoutFiles(album.Id).Any(), TimeSpan.FromSeconds(30)); var trackFiles = _mediaFileService.GetFilesByAlbum(album.Id); @@ -60,7 +60,6 @@ namespace NzbDrone.Core.DecisionEngine.Specifications return Decision.Reject("Existing files on disk is of equal or higher preference: {0}", currentQualities.ConcatToString()); } } - } return Decision.Accept(); diff --git a/src/NzbDrone.Core/DiskSpace/DiskSpaceService.cs b/src/NzbDrone.Core/DiskSpace/DiskSpaceService.cs index ff656d60c..d7106a8d7 100644 --- a/src/NzbDrone.Core/DiskSpace/DiskSpaceService.cs +++ b/src/NzbDrone.Core/DiskSpace/DiskSpaceService.cs @@ -73,11 +73,11 @@ namespace NzbDrone.Core.DiskSpace } 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/Aggregation/RemoteAlbumAggregationService.cs b/src/NzbDrone.Core/Download/Aggregation/RemoteAlbumAggregationService.cs index 61647a7a2..46352c300 100644 --- a/src/NzbDrone.Core/Download/Aggregation/RemoteAlbumAggregationService.cs +++ b/src/NzbDrone.Core/Download/Aggregation/RemoteAlbumAggregationService.cs @@ -37,7 +37,6 @@ namespace NzbDrone.Core.Download.Aggregation } } - return remoteAlbum; } } diff --git a/src/NzbDrone.Core/Download/AlbumGrabbedEvent.cs b/src/NzbDrone.Core/Download/AlbumGrabbedEvent.cs index 5b7972802..7876edec3 100644 --- a/src/NzbDrone.Core/Download/AlbumGrabbedEvent.cs +++ b/src/NzbDrone.Core/Download/AlbumGrabbedEvent.cs @@ -14,4 +14,4 @@ namespace NzbDrone.Core.Download Album = album; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Download/Clients/Blackhole/ScanWatchFolder.cs b/src/NzbDrone.Core/Download/Clients/Blackhole/ScanWatchFolder.cs index c19f37d35..9dec12b09 100644 --- a/src/NzbDrone.Core/Download/Clients/Blackhole/ScanWatchFolder.cs +++ b/src/NzbDrone.Core/Download/Clients/Blackhole/ScanWatchFolder.cs @@ -23,7 +23,7 @@ namespace NzbDrone.Core.Download.Clients.Blackhole private readonly Logger _logger; private readonly IDiskProvider _diskProvider; private readonly IDiskScanService _diskScanService; - private readonly ICached> _watchFolderItemCache; + private readonly ICached> _watchFolderItemCache; public ScanWatchFolder(ICacheManager cacheManager, IDiskScanService diskScanService, IDiskProvider diskProvider, Logger logger) { @@ -37,7 +37,7 @@ namespace NzbDrone.Core.Download.Clients.Blackhole { var newWatchItems = new Dictionary(); var lastWatchItems = _watchFolderItemCache.Get(watchFolder, () => newWatchItems); - + foreach (var newWatchItem in GetDownloadItems(watchFolder, lastWatchItems, waitPeriod)) { newWatchItems[newWatchItem.DownloadId] = newWatchItem; diff --git a/src/NzbDrone.Core/Download/Clients/Blackhole/TorrentBlackhole.cs b/src/NzbDrone.Core/Download/Clients/Blackhole/TorrentBlackhole.cs index 0558e4692..40bdb6152 100644 --- a/src/NzbDrone.Core/Download/Clients/Blackhole/TorrentBlackhole.cs +++ b/src/NzbDrone.Core/Download/Clients/Blackhole/TorrentBlackhole.cs @@ -12,7 +12,6 @@ using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.RemotePathMappings; -using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Core.Download.Clients.Blackhole { diff --git a/src/NzbDrone.Core/Download/Clients/Blackhole/UsenetBlackhole.cs b/src/NzbDrone.Core/Download/Clients/Blackhole/UsenetBlackhole.cs index bb9dddc85..323eeb789 100644 --- a/src/NzbDrone.Core/Download/Clients/Blackhole/UsenetBlackhole.cs +++ b/src/NzbDrone.Core/Download/Clients/Blackhole/UsenetBlackhole.cs @@ -70,7 +70,7 @@ namespace NzbDrone.Core.Download.Clients.Blackhole OutputPath = item.OutputPath, Status = item.Status, - + CanBeRemoved = true, CanMoveFiles = true }; diff --git a/src/NzbDrone.Core/Download/Clients/Blackhole/WatchFolderItem.cs b/src/NzbDrone.Core/Download/Clients/Blackhole/WatchFolderItem.cs index 554aa82b5..bba855d0d 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 27165ac11..31b394d86 100644 --- a/src/NzbDrone.Core/Download/Clients/Deluge/Deluge.cs +++ b/src/NzbDrone.Core/Download/Clients/Deluge/Deluge.cs @@ -1,17 +1,17 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; +using System.Net; +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 NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Configuration; -using NzbDrone.Core.Validation; -using NLog; -using FluentValidation.Results; -using System.Net; using NzbDrone.Core.RemotePathMappings; -using NzbDrone.Common.Extensions; +using NzbDrone.Core.Validation; namespace NzbDrone.Core.Download.Clients.Deluge { @@ -44,7 +44,8 @@ namespace NzbDrone.Core.Download.Clients.Deluge catch (DownloadClientUnavailableException) { _logger.Warn("Failed to set torrent post-import label \"{0}\" for {1} in Deluge. Does the label exist?", - Settings.MusicImportedCategory, downloadClientItem.Title); + Settings.MusicImportedCategory, + downloadClientItem.Title); } } } @@ -67,8 +68,8 @@ namespace NzbDrone.Core.Download.Clients.Deluge var isRecentAlbum = remoteAlbum.IsRecentAlbum(); - if (isRecentAlbum && Settings.RecentTvPriority == (int)DelugePriority.First || - !isRecentAlbum && Settings.OlderTvPriority == (int)DelugePriority.First) + if ((isRecentAlbum && Settings.RecentTvPriority == (int)DelugePriority.First) || + (!isRecentAlbum && Settings.OlderTvPriority == (int)DelugePriority.First)) { _proxy.MoveTorrentToTopInQueue(actualHash, Settings); } @@ -94,8 +95,8 @@ namespace NzbDrone.Core.Download.Clients.Deluge var isRecentAlbum = remoteAlbum.IsRecentAlbum(); - if (isRecentAlbum && Settings.RecentTvPriority == (int)DelugePriority.First || - !isRecentAlbum && Settings.OlderTvPriority == (int)DelugePriority.First) + if ((isRecentAlbum && Settings.RecentTvPriority == (int)DelugePriority.First) || + (!isRecentAlbum && Settings.OlderTvPriority == (int)DelugePriority.First)) { _proxy.MoveTorrentToTopInQueue(actualHash, Settings); } @@ -122,7 +123,10 @@ namespace NzbDrone.Core.Download.Clients.Deluge foreach (var torrent in torrents) { - if (torrent.Hash == null) continue; + if (torrent.Hash == null) + { + continue; + } var item = new DownloadClientItem(); item.DownloadId = torrent.Hash.ToUpper(); @@ -216,7 +220,11 @@ namespace NzbDrone.Core.Download.Clients.Deluge 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 764662547..45df09c8c 100644 --- a/src/NzbDrone.Core/Download/Clients/Deluge/DelugeException.cs +++ b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeException.cs @@ -5,7 +5,7 @@ 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/DelugePriority.cs b/src/NzbDrone.Core/Download/Clients/Deluge/DelugePriority.cs index e5cf2924c..741392e88 100644 --- a/src/NzbDrone.Core/Download/Clients/Deluge/DelugePriority.cs +++ b/src/NzbDrone.Core/Download/Clients/Deluge/DelugePriority.cs @@ -5,4 +5,4 @@ Last = 0, First = 1 } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Download/Clients/Deluge/DelugeProxy.cs b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeProxy.cs index 580096373..f7d151c71 100644 --- a/src/NzbDrone.Core/Download/Clients/Deluge/DelugeProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeProxy.cs @@ -31,7 +31,7 @@ namespace NzbDrone.Core.Download.Clients.Deluge 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 @@ namespace NzbDrone.Core.Download.Clients.Deluge // 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 @@ namespace NzbDrone.Core.Download.Clients.Deluge 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 @@ namespace NzbDrone.Core.Download.Clients.Deluge 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 @@ namespace NzbDrone.Core.Download.Clients.Deluge 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); return response; @@ -226,6 +226,7 @@ namespace NzbDrone.Core.Download.Clients.Deluge { return response.Result; } + error = response.Error.ToObject(); throw new DownloadClientAuthenticationException(error.Message); @@ -296,6 +297,7 @@ namespace NzbDrone.Core.Download.Clients.Deluge _logger.Debug("Deluge authentication failed."); throw new DownloadClientAuthenticationException("Failed to authenticate with Deluge."); } + _logger.Debug("Deluge authentication succeeded."); cookies = response.GetCookies(); @@ -328,7 +330,7 @@ namespace NzbDrone.Core.Download.Clients.Deluge 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) { @@ -339,7 +341,7 @@ namespace NzbDrone.Core.Download.Clients.Deluge } } - 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/DelugeTorrent.cs b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeTorrent.cs index d4b46ea42..680a163d9 100644 --- a/src/NzbDrone.Core/Download/Clients/Deluge/DelugeTorrent.cs +++ b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeTorrent.cs @@ -16,9 +16,9 @@ namespace NzbDrone.Core.Download.Clients.Deluge // Other paths: What is the difference between 'move_completed_path' and 'move_on_completed_path'? /* - [JsonProperty(PropertyName = "move_completed_path")] + [JsonProperty(PropertyName = "move_completed_path")] public String DownloadPathMoveCompleted { get; set; } - [JsonProperty(PropertyName = "move_on_completed_path")] + [JsonProperty(PropertyName = "move_on_completed_path")] public String DownloadPathMoveOnCompleted { get; set; } */ diff --git a/src/NzbDrone.Core/Download/Clients/DownloadClientAuthenticationException.cs b/src/NzbDrone.Core/Download/Clients/DownloadClientAuthenticationException.cs index 38c956479..6d27bb9bd 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadClientAuthenticationException.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadClientAuthenticationException.cs @@ -7,19 +7,16 @@ namespace NzbDrone.Core.Download.Clients 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 c2a6667ab..60f84c672 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/DiskStationApiInfo.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/DiskStationApiInfo.cs @@ -1,7 +1,7 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation { public class DiskStationApiInfo - { + { private string _path; public int MaxVersion { get; set; } @@ -16,7 +16,10 @@ 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 627589d73..77dd04bb1 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationSettings.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationSettings.cs @@ -53,8 +53,8 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation 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 6957f3e92..3c5de2fb9 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTask.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTask.cs @@ -29,13 +29,18 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation 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 45c9fd137..81e55569e 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/DownloadStationTaskFile.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTaskFile.cs index d49c5d7dd..2538e3e10 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTaskFile.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTaskFile.cs @@ -1,10 +1,5 @@ using Newtonsoft.Json; using Newtonsoft.Json.Converters; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using static NzbDrone.Core.Download.Clients.DownloadStation.DownloadStationTask; 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 9c18d5702..747781861 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DSMInfoProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DSMInfoProxy.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using NLog; +using NLog; using NzbDrone.Common.Cache; using NzbDrone.Common.Http; using NzbDrone.Core.Download.Clients.DownloadStation.Responses; @@ -14,8 +12,8 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Proxies 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 2162a3d57..4e84666ed 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DiskStationProxyBase.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DiskStationProxyBase.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Net; using NLog; using NzbDrone.Common.Cache; @@ -61,7 +60,8 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Proxies protected DiskStationResponse ProcessRequest(HttpRequestBuilder requestBuilder, string operation, - DownloadStationSettings settings) where T : new() + DownloadStationSettings settings) + where T : new() { return ProcessRequest(requestBuilder, operation, _apiType, settings); } @@ -69,7 +69,8 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Proxies 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 9b0cb00ed..6b9b24847 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 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Proxies 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/Proxies/FileStationProxy.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/FileStationProxy.cs index 29031e0eb..a07cc1b47 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/FileStationProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/FileStationProxy.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; +using System.Linq; using NLog; using NzbDrone.Common.Cache; using NzbDrone.Common.Http; @@ -22,7 +20,7 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Proxies : base(DiskStationApi.FileStationList, "SYNO.FileStation.List", httpClient, cacheManager, logger) { } - + public SharedFolderMapping GetSharedFolderMapping(string sharedFolder, DownloadStationSettings settings) { var info = GetInfoFileOrDirectory(sharedFolder, settings); diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationError.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationError.cs index ca56f127b..e69000659 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 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Responses 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 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Responses 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 54ac7dc8b..6c40ae75c 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 de7aadfc6..43c981669 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 1d974b913..ebd79f3d7 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 2f689a48b..f31d51a68 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 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Responses 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 ddf971384..88a419d22 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/SerialNumberProvider.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/SerialNumberProvider.cs @@ -15,8 +15,8 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation 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 d1db18db0..25ff176f6 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/SharedFolderResolver.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/SharedFolderResolver.cs @@ -14,8 +14,8 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation 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 d10d8541c..6bcb1fbfe 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/TorrentDownloadStation.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/TorrentDownloadStation.cs @@ -197,7 +197,11 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestOutputPath()); failures.AddIfNotNull(TestGetTorrents()); } @@ -209,10 +213,10 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation 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) + protected string GetMessage(DownloadStationTask torrent) { if (torrent.StatusExtra != null) { @@ -340,8 +344,9 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation return null; } - catch (DownloadClientAuthenticationException ex) // User could not have permission to access to downloadstation + catch (DownloadClientAuthenticationException ex) { + // User could not have permission to access to downloadstation _logger.Error(ex, "Unable to authenticate"); return new NzbDroneValidationFailure(string.Empty, ex.Message); } @@ -377,6 +382,7 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation 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 ac55aad0a..6edc96e84 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/UsenetDownloadStation.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/UsenetDownloadStation.cs @@ -34,8 +34,7 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation IDiskProvider diskProvider, IRemotePathMappingService remotePathMappingService, IValidateNzbs nzbValidationService, - Logger logger - ) + Logger logger) : base(httpClient, configService, diskProvider, remotePathMappingService, nzbValidationService, logger) { _dsInfoProxy = dsInfoProxy; @@ -192,7 +191,11 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestOutputPath()); failures.AddIfNotNull(TestGetNZB()); } @@ -239,8 +242,9 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation return null; } - catch (DownloadClientAuthenticationException ex) // User could not have permission to access to downloadstation + catch (DownloadClientAuthenticationException ex) { + // User could not have permission to access to downloadstation _logger.Error(ex, "Unable to authenticate"); return new NzbDroneValidationFailure(string.Empty, ex.Message); } @@ -276,6 +280,7 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation 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 c283840f9..b6b09a59c 100644 --- a/src/NzbDrone.Core/Download/Clients/Hadouken/Hadouken.cs +++ b/src/NzbDrone.Core/Download/Clients/Hadouken/Hadouken.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using FluentValidation.Results; using NLog; using NzbDrone.Common.Disk; @@ -89,7 +88,7 @@ namespace NzbDrone.Core.Download.Clients.Hadouken 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); } @@ -130,7 +129,11 @@ namespace NzbDrone.Core.Download.Clients.Hadouken protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestGetTorrents()); } @@ -177,7 +180,7 @@ namespace NzbDrone.Core.Download.Clients.Hadouken catch (Exception ex) { _logger.Error(ex, "Unable to validate"); - 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 fc684b375..75917c8d9 100644 --- a/src/NzbDrone.Core/Download/Clients/Hadouken/HadoukenProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/Hadouken/HadoukenProxy.cs @@ -38,7 +38,7 @@ namespace NzbDrone.Core.Download.Clients.Hadouken public HadoukenTorrent[] GetTorrents(HadoukenSettings settings) { var result = ProcessRequest(settings, "webui.list"); - + return GetTorrents(result.Torrents); } @@ -146,7 +146,7 @@ namespace NzbDrone.Core.Download.Clients.Hadouken 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 a80e1cbed..8b3ae01be 100644 --- a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortex.cs +++ b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortex.cs @@ -9,8 +9,8 @@ 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.Validation; namespace NzbDrone.Core.Download.Clients.NzbVortex { @@ -71,22 +71,25 @@ namespace NzbDrone.Core.Download.Clients.NzbVortex { 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); @@ -116,7 +119,6 @@ namespace NzbDrone.Core.Download.Clients.NzbVortex { _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 10178b9ce..6c8d3e34b 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 61bbb27d6..8735cb383 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/NzbVortexPriority.cs b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexPriority.cs index eb24f9afa..44e18b54e 100644 --- a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexPriority.cs +++ b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexPriority.cs @@ -6,4 +6,4 @@ Normal = 0, High = 1, } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexProxy.cs b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexProxy.cs index 9a248ae17..a400b58d1 100644 --- a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexProxy.cs @@ -42,12 +42,12 @@ namespace NzbDrone.Core.Download.Clients.NzbVortex var requestBuilder = BuildRequest(settings).Resource("nzb/add") .Post() .AddQueryParam("priority", priority.ToString()); - + if (settings.MusicCategory.IsNotNullOrWhiteSpace()) { requestBuilder.AddQueryParam("groupname", settings.MusicCategory); } - + requestBuilder.AddFormUpload("name", filename, nzbData, "application/x-nzb"); var response = ProcessRequest(requestBuilder, true, settings); @@ -91,7 +91,6 @@ namespace NzbDrone.Core.Download.Clients.NzbVortex public List GetQueue(int doneLimit, NzbVortexSettings settings) { var requestBuilder = BuildRequest(settings).Resource("nzb"); - if (settings.MusicCategory.IsNotNullOrWhiteSpace()) { @@ -113,7 +112,7 @@ namespace NzbDrone.Core.Download.Clients.NzbVortex return response.Files; } - + private HttpRequestBuilder BuildRequest(NzbVortexSettings settings) { var baseUrl = HttpRequestBuilder.BuildBaseUrl(true, settings.Host, settings.Port, settings.UrlBase); diff --git a/src/NzbDrone.Core/Download/Clients/Nzbget/Nzbget.cs b/src/NzbDrone.Core/Download/Clients/Nzbget/Nzbget.cs index 617574ef8..d7de962f4 100644 --- a/src/NzbDrone.Core/Download/Clients/Nzbget/Nzbget.cs +++ b/src/NzbDrone.Core/Download/Clients/Nzbget/Nzbget.cs @@ -20,7 +20,7 @@ namespace NzbDrone.Core.Download.Clients.Nzbget { 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, @@ -76,7 +76,7 @@ namespace NzbDrone.Core.Download.Clients.Nzbget 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; @@ -220,7 +220,10 @@ namespace NzbDrone.Core.Download.Clients.Nzbget { var name = config.GetValueOrDefault("Category" + i + ".Name"); - if (name == null) yield break; + if (name == null) + { + yield break; + } var destDir = config.GetValueOrDefault("Category" + i + ".DestDir"); @@ -270,6 +273,7 @@ namespace NzbDrone.Core.Download.Clients.Nzbget { return new ValidationFailure("Username", "Authentication failed"); } + _logger.Error(ex, "Unable to connect to NZBGet"); return new ValidationFailure("Host", "Unable to connect to NZBGet"); } @@ -327,7 +331,7 @@ namespace NzbDrone.Core.Download.Clients.Nzbget { long result = high; - result = (result << 32) | (long)low; + result = (result << 32) | low; return result; } diff --git a/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetProxy.cs b/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetProxy.cs index d79108532..6c7b5a53a 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 @@ namespace NzbDrone.Core.Download.Clients.Nzbget 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 @@ namespace NzbDrone.Core.Download.Clients.Nzbget 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 @@ namespace NzbDrone.Core.Download.Clients.Nzbget _logger.Warn("Failed to remove item from nzbget queue, {0} [{1}]", queueItem.NzbName, queueItem.NzbId); } } - else if (historyItem != null) { if (!EditQueue("HistoryDelete", 0, "", historyItem.Id, settings)) @@ -195,7 +194,6 @@ namespace NzbDrone.Core.Download.Clients.Nzbget _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 f1546593e..adec59ebc 100644 --- a/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetResponse.cs +++ b/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetResponse.cs @@ -5,6 +5,5 @@ public string Version { get; set; } public T Result { get; set; } - } } diff --git a/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetSettings.cs b/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetSettings.cs index 8b8607798..8b50b4b4b 100644 --- a/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetSettings.cs +++ b/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetSettings.cs @@ -65,7 +65,7 @@ namespace NzbDrone.Core.Download.Clients.Nzbget [FieldDefinition(9, Label = "Use SSL", Type = FieldType.Checkbox)] public bool UseSsl { get; set; } - + public NzbDroneValidationResult Validate() { return new NzbDroneValidationResult(Validator.Validate(this)); diff --git a/src/NzbDrone.Core/Download/Clients/Pneumatic/Pneumatic.cs b/src/NzbDrone.Core/Download/Clients/Pneumatic/Pneumatic.cs index f5ad06edf..f8eb62cc1 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.Extensions; 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 { @@ -54,7 +54,6 @@ namespace NzbDrone.Core.Download.Clients.Pneumatic var strmFile = WriteStrmFile(title, nzbFile); - return GetDownloadClientId(strmFile); } @@ -121,7 +120,6 @@ namespace NzbDrone.Core.Download.Clients.Pneumatic private string WriteStrmFile(string title, string nzbFile) { - if (Settings.StrmFolder.IsNullOrWhiteSpace()) { throw new DownloadClientException("Strm Folder needs to be set for Pneumatic Downloader"); diff --git a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrent.cs b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrent.cs index 93408c841..c20bbf0a7 100644 --- a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrent.cs +++ b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrent.cs @@ -1,9 +1,9 @@ using System; 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; @@ -12,7 +12,6 @@ using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.Validation; -using NzbDrone.Common.Cache; namespace NzbDrone.Core.Download.Clients.QBittorrent { @@ -57,7 +56,8 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent catch (DownloadClientException) { _logger.Warn("Failed to set post-import torrent label \"{0}\" for {1} in qBittorrent. Does the label exist?", - Settings.MusicImportedCategory, downloadClientItem.Title); + Settings.MusicImportedCategory, + downloadClientItem.Title); } } } @@ -73,8 +73,8 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent var isRecentAlbum = remoteAlbum.IsRecentAlbum(); - if (isRecentAlbum && Settings.RecentTvPriority == (int)QBittorrentPriority.First || - !isRecentAlbum && Settings.OlderTvPriority == (int)QBittorrentPriority.First) + if ((isRecentAlbum && Settings.RecentTvPriority == (int)QBittorrentPriority.First) || + (!isRecentAlbum && Settings.OlderTvPriority == (int)QBittorrentPriority.First)) { Proxy.MoveTorrentToTopInQueue(hash.ToLower(), Settings); } @@ -89,7 +89,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent return hash; } - protected override string AddFromTorrentFile(RemoteAlbum remoteAlbum, string hash, string filename, Byte[] fileContent) + protected override string AddFromTorrentFile(RemoteAlbum remoteAlbum, string hash, string filename, byte[] fileContent) { Proxy.AddTorrentFromFile(filename, fileContent, Settings); @@ -97,8 +97,8 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent { var isRecentAlbum = remoteAlbum.IsRecentAlbum(); - if (isRecentAlbum && Settings.RecentTvPriority == (int)QBittorrentPriority.First || - !isRecentAlbum && Settings.OlderTvPriority == (int)QBittorrentPriority.First) + if ((isRecentAlbum && Settings.RecentTvPriority == (int)QBittorrentPriority.First) || + (!isRecentAlbum && Settings.OlderTvPriority == (int)QBittorrentPriority.First)) { Proxy.MoveTorrentToTopInQueue(hash.ToLower(), Settings); } @@ -144,7 +144,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent // 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) { @@ -192,6 +192,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent 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 @@ -234,7 +235,11 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent 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()); @@ -278,7 +283,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent 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 = "Lidarr 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'." }; @@ -302,12 +307,13 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent 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; @@ -389,7 +395,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent 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; @@ -404,7 +410,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent 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; @@ -466,8 +472,10 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent } } - if (HasReachedSeedingTimeLimit(torrent, config)) return true; - + if (HasReachedSeedingTimeLimit(torrent, config)) + { + return true; + } return false; } diff --git a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentLabel.cs b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentLabel.cs index 153e8e009..224a079e9 100644 --- a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentLabel.cs +++ b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentLabel.cs @@ -1,6 +1,4 @@ -using Newtonsoft.Json; - -namespace NzbDrone.Core.Download.Clients.QBittorrent +namespace NzbDrone.Core.Download.Clients.QBittorrent { public class QBittorrentLabel { diff --git a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxySelector.cs b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxySelector.cs index 0b3c07e63..bbd308eea 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.Cache; using NzbDrone.Common.Http; - namespace NzbDrone.Core.Download.Clients.QBittorrent { public interface IQBittorrentProxy @@ -46,9 +45,9 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent private readonly IQBittorrentProxy _proxyV1; private readonly IQBittorrentProxy _proxyV2; - public QBittorrentProxySelector(QBittorrentProxyV1 proxyV1, + public QBittorrentProxySelector(QBittorrentProxyV1 proxyV1, QBittorrentProxyV2 proxyV2, - IHttpClient httpClient, + IHttpClient httpClient, ICacheManager cacheManager, Logger logger) { @@ -69,7 +68,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent _proxyCache.Remove(proxyKey); } - return _proxyCache.Get(proxyKey, () => FetchProxy(settings), TimeSpan.FromMinutes(10.0)); + return _proxyCache.Get(proxyKey, () => FetchProxy(settings), TimeSpan.FromMinutes(10.0)); } private IQBittorrentProxy FetchProxy(QBittorrentSettings settings) diff --git a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV1.cs b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV1.cs index a2ee7fde0..f095f32ee 100644 --- a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV1.cs +++ b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV1.cs @@ -1,16 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Net; using NLog; using NzbDrone.Common.Cache; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; -using System; -using System.Collections.Generic; -using System.Net; namespace NzbDrone.Core.Download.Clients.QBittorrent { // API https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-Documentation - public class QBittorrentProxyV1 : IQBittorrentProxy { private readonly IHttpClient _httpClient; @@ -230,7 +229,6 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent throw; } - } public void PauseTorrent(string hash, QBittorrentSettings settings) @@ -354,7 +352,8 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent 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 5326306fa..d20d15126 100644 --- a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV2.cs +++ b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV2.cs @@ -10,7 +10,6 @@ using NzbDrone.Common.Serializer; 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 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent { request.AddQueryParam("category", settings.MusicCategory); } + var response = ProcessRequest>(request, settings); return response; @@ -238,7 +238,6 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent throw; } - } public void PauseTorrent(string hash, QBittorrentSettings settings) @@ -329,6 +328,7 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent { throw new DownloadClientAuthenticationException("Failed to authenticate with qBittorrent."); } + return; } @@ -366,7 +366,8 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent 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/QBittorrentTorrent.cs b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentTorrent.cs index 93a07e749..4a5540e78 100644 --- a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentTorrent.cs +++ b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentTorrent.cs @@ -34,7 +34,6 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent [JsonProperty(PropertyName = "seeding_time_limit")] // Per torrent seeding time limit (-2 = use global, -1 = unlimited) public long SeedingTimeLimit { get; set; } = -2; - } public class QBittorrentTorrentProperties diff --git a/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdPriorityTypeConverter.cs b/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdPriorityTypeConverter.cs index 17557abcc..246b5b558 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 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd.JsonConverters 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 c5274efb1..10efa12b2 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 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd.JsonConverters 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 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd.JsonConverters 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 3cf61d8a5..719305dc9 100644 --- a/src/NzbDrone.Core/Download/Clients/Sabnzbd/Sabnzbd.cs +++ b/src/NzbDrone.Core/Download/Clients/Sabnzbd/Sabnzbd.cs @@ -10,8 +10,8 @@ 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.Validation; namespace NzbDrone.Core.Download.Clients.Sabnzbd { @@ -148,8 +148,9 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd { historyItem.Status = DownloadItemStatus.Completed; } - else // Verifying/Moving etc + else { + // Verifying/Moving etc historyItem.Status = DownloadItemStatus.Downloading; } @@ -166,6 +167,7 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd { historyItem.OutputPath = parent; } + parent = parent.Directory; } } @@ -182,7 +184,7 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd { foreach (var downloadClientItem in GetQueue().Concat(GetHistory())) { - if (downloadClientItem.Category == Settings.MusicCategory || downloadClientItem.Category == "*" && Settings.MusicCategory.IsNullOrWhiteSpace()) + if (downloadClientItem.Category == Settings.MusicCategory || (downloadClientItem.Category == "*" && Settings.MusicCategory.IsNullOrWhiteSpace())) { yield return downloadClientItem; } @@ -323,7 +325,6 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd minor = Convert.ToInt32(parsed.Groups["minor"].Value); patch = Convert.ToInt32(parsed.Groups["patch"].Value.Replace("x", "0")); } - else { if (!version.Equals("develop", StringComparison.InvariantCultureIgnoreCase)) @@ -391,10 +392,12 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd { return new ValidationFailure("APIKey", "API Key Incorrect"); } + if (ex.Message.ContainsIgnoreCase("API Key Required")) { return new ValidationFailure("APIKey", "API Key Required"); } + throw; } @@ -443,6 +446,7 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd }; } } + if (config.Misc.enable_tv_sorting && ContainsCategory(config.Misc.tv_categories, Settings.MusicCategory)) { return new NzbDroneValidationFailure("MusicCategory", "Disable TV Sorting") @@ -451,6 +455,7 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd DetailedDescription = "You must disable Sabnzbd TV Sorting for the category Lidarr uses to prevent import issues. Go to Sabnzbd to fix it." }; } + if (config.Misc.enable_movie_sorting && ContainsCategory(config.Misc.movie_categories, Settings.MusicCategory)) { return new NzbDroneValidationFailure("MusicCategory", "Disable Movie Sorting") @@ -459,6 +464,7 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd DetailedDescription = "You must disable Sabnzbd Movie Sorting for the category Lidarr uses to prevent import issues. Go to Sabnzbd to fix it." }; } + if (config.Misc.enable_date_sorting && ContainsCategory(config.Misc.date_categories, Settings.MusicCategory)) { return new NzbDroneValidationFailure("MusicCategory", "Disable Date Sorting") diff --git a/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdFullStatus.cs b/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdFullStatus.cs index d1d691fc6..f8b3298c1 100644 --- a/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdFullStatus.cs +++ b/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdFullStatus.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using Newtonsoft.Json; +using Newtonsoft.Json; namespace NzbDrone.Core.Download.Clients.Sabnzbd { diff --git a/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdPriority.cs b/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdPriority.cs index b769a78db..905aea6c0 100644 --- a/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdPriority.cs +++ b/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdPriority.cs @@ -9,4 +9,4 @@ High = 1, Force = 2 } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdProxy.cs b/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdProxy.cs index cd103cf1b..a775544d1 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 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd { 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 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd requestBuilder.AddSuffixQueryParam("ma_username", settings.Username); requestBuilder.AddSuffixQueryParam("ma_password", settings.Password); } + requestBuilder.AddSuffixQueryParam("output", "json"); return requestBuilder; @@ -211,7 +212,6 @@ namespace NzbDrone.Core.Download.Clients.Sabnzbd 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 058023d0c..369b9f961 100644 --- a/src/NzbDrone.Core/Download/Clients/Transmission/Transmission.cs +++ b/src/NzbDrone.Core/Download/Clients/Transmission/Transmission.cs @@ -1,10 +1,10 @@ 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; diff --git a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionBase.cs b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionBase.cs index 038ee3981..1f192a985 100644 --- a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionBase.cs +++ b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionBase.cs @@ -40,18 +40,27 @@ namespace NzbDrone.Core.Download.Clients.Transmission 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.TvDirectory.IsNotNullOrWhiteSpace()) { - if (!new OsPath(Settings.TvDirectory).Contains(outputPath)) continue; + if (!new OsPath(Settings.TvDirectory).Contains(outputPath)) + { + continue; + } } else if (Settings.MusicCategory.IsNotNullOrWhiteSpace()) { var directories = outputPath.FullPath.Split('\\', '/'); - if (!directories.Contains(Settings.MusicCategory)) continue; + if (!directories.Contains(Settings.MusicCategory)) + { + continue; + } } outputPath = _remotePathMappingService.RemapRemoteToLocal(Settings.Host, outputPath); @@ -112,7 +121,7 @@ namespace NzbDrone.Core.Download.Clients.Transmission { var isStopped = torrent.Status == TransmissionTorrentStatus.Stopped; var isSeeding = torrent.Status == TransmissionTorrentStatus.Seeding; - + if (torrent.SeedRatioMode == 1) { if (isStopped && ratio.HasValue && ratio >= torrent.SeedRatioLimit) @@ -177,8 +186,8 @@ namespace NzbDrone.Core.Download.Clients.Transmission var isRecentAlbum = remoteAlbum.IsRecentAlbum(); - if (isRecentAlbum && Settings.RecentTvPriority == (int)TransmissionPriority.First || - !isRecentAlbum && Settings.OlderTvPriority == (int)TransmissionPriority.First) + if ((isRecentAlbum && Settings.RecentTvPriority == (int)TransmissionPriority.First) || + (!isRecentAlbum && Settings.OlderTvPriority == (int)TransmissionPriority.First)) { _proxy.MoveTorrentToTopInQueue(hash, Settings); } @@ -193,8 +202,8 @@ namespace NzbDrone.Core.Download.Clients.Transmission var isRecentAlbum = remoteAlbum.IsRecentAlbum(); - if (isRecentAlbum && Settings.RecentTvPriority == (int)TransmissionPriority.First || - !isRecentAlbum && Settings.OlderTvPriority == (int)TransmissionPriority.First) + if ((isRecentAlbum && Settings.RecentTvPriority == (int)TransmissionPriority.First) || + (!isRecentAlbum && Settings.OlderTvPriority == (int)TransmissionPriority.First)) { _proxy.MoveTorrentToTopInQueue(hash, Settings); } @@ -205,7 +214,11 @@ namespace NzbDrone.Core.Download.Clients.Transmission protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestGetTorrents()); } diff --git a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionConfig.cs b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionConfig.cs index 194df1e5e..1b96ca6d3 100644 --- a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionConfig.cs +++ b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionConfig.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Newtonsoft.Json; +using Newtonsoft.Json; namespace NzbDrone.Core.Download.Clients.Transmission { diff --git a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionException.cs b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionException.cs index f89ee42da..3b91b4ce3 100644 --- a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionException.cs +++ b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionException.cs @@ -5,7 +5,6 @@ public TransmissionException(string message) : base(message) { - } } } diff --git a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionPriority.cs b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionPriority.cs index e5152bea6..1cf99c501 100644 --- a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionPriority.cs +++ b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionPriority.cs @@ -5,4 +5,4 @@ Last = 0, First = 1 } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionProxy.cs b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionProxy.cs index 4fb64f52f..945894c6c 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 @@ namespace NzbDrone.Core.Download.Clients.Transmission void MoveTorrentToTopInQueue(string hashString, TransmissionSettings settings); } - public class TransmissionProxy: ITransmissionProxy + public class TransmissionProxy : ITransmissionProxy { private readonly IHttpClient _httpClient; private readonly Logger _logger; @@ -37,7 +37,7 @@ namespace NzbDrone.Core.Download.Clients.Transmission _authSessionIDCache = cacheManager.GetCache(GetType(), "authSessionID"); } - + public List GetTorrents(TransmissionSettings settings) { var result = GetTorrentStatus(settings); @@ -77,7 +77,10 @@ namespace NzbDrone.Core.Download.Clients.Transmission 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 @@ namespace NzbDrone.Core.Download.Clients.Transmission 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 @@ namespace NzbDrone.Core.Download.Clients.Transmission 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", @@ -176,7 +179,7 @@ namespace NzbDrone.Core.Download.Clients.Transmission "seedIdleMode", "fileCount" }; - + var arguments = new Dictionary(); arguments.Add("fields", fields); @@ -244,7 +247,7 @@ namespace NzbDrone.Core.Download.Clients.Transmission requestBuilder.SetHeader("X-Transmission-Session-Id", sessionId); } - + public TransmissionResponse ProcessRequest(string action, object arguments, TransmissionSettings settings) { try @@ -296,6 +299,7 @@ namespace NzbDrone.Core.Download.Clients.Transmission { throw new TransmissionException(transmissionResponse.Result); } + return transmissionResponse; } catch (HttpException ex) diff --git a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionSettings.cs b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionSettings.cs index e456bbd30..8dc04f3e7 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 36e0818e3..1abbd5d09 100644 --- a/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrent.cs +++ b/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrent.cs @@ -1,20 +1,20 @@ 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.Parser.Model; using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.ThingiProvider; +using NzbDrone.Core.Validation; namespace NzbDrone.Core.Download.Clients.RTorrent { @@ -49,8 +49,10 @@ namespace NzbDrone.Core.Download.Clients.RTorrent } catch (Exception ex) { - _logger.Warn(ex, "Failed to set torrent post-import label \"{0}\" for {1} in rTorrent. Does the label exist?", - Settings.MusicImportedCategory, downloadClientItem.Title); + _logger.Warn(ex, + "Failed to set torrent post-import label \"{0}\" for {1} in rTorrent. Does the label exist?", + Settings.MusicImportedCategory, + downloadClientItem.Title); } } } @@ -107,7 +109,10 @@ namespace NzbDrone.Core.Download.Clients.RTorrent foreach (RTorrentTorrent torrent in torrents) { // Don't concern ourselves with categories other than specified - if (Settings.MusicCategory.IsNotNullOrWhiteSpace() && torrent.Category != Settings.MusicCategory) continue; + if (Settings.MusicCategory.IsNotNullOrWhiteSpace() && torrent.Category != Settings.MusicCategory) + { + continue; + } if (torrent.Path.StartsWith(".")) { @@ -169,7 +174,6 @@ namespace NzbDrone.Core.Download.Clients.RTorrent 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" @@ -181,7 +185,11 @@ namespace NzbDrone.Core.Download.Clients.RTorrent 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 b35063076..39f4d2cc2 100644 --- a/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrentProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrentProxy.cs @@ -1,12 +1,9 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Net; -using System.Net.Sockets; -using System.Runtime.InteropServices.ComTypes; +using CookComputing.XmlRpc; using NLog; using NzbDrone.Common.Extensions; -using CookComputing.XmlRpc; namespace NzbDrone.Core.Download.Clients.RTorrent { @@ -76,7 +73,9 @@ namespace NzbDrone.Core.Download.Clients.RTorrent _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 @@ -87,8 +86,7 @@ namespace NzbDrone.Core.Download.Clients.RTorrent "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/rTorrent/RTorrentSettings.cs b/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrentSettings.cs index 86a5d42d2..b5569e02a 100644 --- a/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrentSettings.cs +++ b/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrentSettings.cs @@ -13,7 +13,7 @@ namespace NzbDrone.Core.Download.Clients.RTorrent RuleFor(c => c.Port).InclusiveBetween(1, 65535); RuleFor(c => c.MusicCategory).NotEmpty() .WithMessage("A category is recommended") - .AsWarning(); + .AsWarning(); } } diff --git a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrent.cs b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrent.cs index 88116f725..8c72ac9c1 100644 --- a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrent.cs +++ b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrent.cs @@ -1,18 +1,18 @@ 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.Parser.Model; using NzbDrone.Core.RemotePathMappings; -using NzbDrone.Common.Cache; +using NzbDrone.Core.Validation; namespace NzbDrone.Core.Download.Clients.UTorrent { @@ -64,8 +64,8 @@ namespace NzbDrone.Core.Download.Clients.UTorrent var isRecentAlbum = remoteAlbum.IsRecentAlbum(); - if (isRecentAlbum && Settings.RecentTvPriority == (int)UTorrentPriority.First || - !isRecentAlbum && Settings.OlderTvPriority == (int)UTorrentPriority.First) + if ((isRecentAlbum && Settings.RecentTvPriority == (int)UTorrentPriority.First) || + (!isRecentAlbum && Settings.OlderTvPriority == (int)UTorrentPriority.First)) { _proxy.MoveTorrentToTopInQueue(hash, Settings); } @@ -87,8 +87,8 @@ namespace NzbDrone.Core.Download.Clients.UTorrent var isRecentAlbum = remoteAlbum.IsRecentAlbum(); - if (isRecentAlbum && Settings.RecentTvPriority == (int)UTorrentPriority.First || - !isRecentAlbum && Settings.OlderTvPriority == (int)UTorrentPriority.First) + if ((isRecentAlbum && Settings.RecentTvPriority == (int)UTorrentPriority.First) || + (!isRecentAlbum && Settings.OlderTvPriority == (int)UTorrentPriority.First)) { _proxy.MoveTorrentToTopInQueue(hash, Settings); } @@ -248,7 +248,11 @@ namespace NzbDrone.Core.Download.Clients.UTorrent protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestGetTorrents()); } @@ -281,6 +285,7 @@ namespace NzbDrone.Core.Download.Clients.UTorrent 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/UTorrentPriority.cs b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentPriority.cs index 7173a71e4..0079da670 100644 --- a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentPriority.cs +++ b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentPriority.cs @@ -5,4 +5,4 @@ Last = 0, First = 1 } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentProxy.cs b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentProxy.cs index 4415c2ec4..b50e9b121 100644 --- a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentProxy.cs @@ -186,7 +186,7 @@ namespace NzbDrone.Core.Download.Clients.UTorrent ProcessRequest(requestBuilder, settings); } - + private HttpRequestBuilder BuildRequest(UTorrentSettings settings) { var requestBuilder = new HttpRequestBuilder(false, settings.Host, settings.Port, settings.UrlBase) diff --git a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrent.cs b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrent.cs index 9a6a0188f..027b138e0 100644 --- a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrent.cs +++ b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrent.cs @@ -39,7 +39,7 @@ namespace NzbDrone.Core.Download.Clients.UTorrent public object Unknown28 { get; set; } } - class UTorrentTorrentJsonConverter : JsonConverter + internal class UTorrentTorrentJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) { @@ -78,11 +78,10 @@ namespace NzbDrone.Core.Download.Clients.UTorrent reader.Read(); // Builds before 25406 don't return the remaining items. - if (reader.TokenType != JsonToken.EndArray) { result.DownloadUrl = (string)reader.Value; - + reader.Read(); result.RssFeedUrl = reader.Value; reader.Read(); @@ -100,9 +99,11 @@ namespace NzbDrone.Core.Download.Clients.UTorrent result.Unknown27 = reader.Value; 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/Clients/uTorrent/UTorrentTorrentCache.cs b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrentCache.cs index 7f56675fe..4d9424f39 100644 --- a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrentCache.cs +++ b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrentCache.cs @@ -5,7 +5,7 @@ namespace NzbDrone.Core.Download.Clients.UTorrent public class UTorrentTorrentCache { public string CacheID { get; set; } - + public List Torrents { get; set; } } } diff --git a/src/NzbDrone.Core/Download/CompletedDownloadService.cs b/src/NzbDrone.Core/Download/CompletedDownloadService.cs index 64b594c7b..9195fc942 100644 --- a/src/NzbDrone.Core/Download/CompletedDownloadService.cs +++ b/src/NzbDrone.Core/Download/CompletedDownloadService.cs @@ -8,11 +8,11 @@ using NzbDrone.Core.Configuration; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.History; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Parser; -using NzbDrone.Core.Music; -using NzbDrone.Core.MediaFiles.TrackImport; using NzbDrone.Core.MediaFiles.Events; +using NzbDrone.Core.MediaFiles.TrackImport; +using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Music; +using NzbDrone.Core.Parser; namespace NzbDrone.Core.Download { diff --git a/src/NzbDrone.Core/Download/DownloadClientBase.cs b/src/NzbDrone.Core/Download/DownloadClientBase.cs index f6a58d2d2..e5895ffe1 100644 --- a/src/NzbDrone.Core/Download/DownloadClientBase.cs +++ b/src/NzbDrone.Core/Download/DownloadClientBase.cs @@ -1,6 +1,6 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentValidation.Results; using NLog; using NzbDrone.Common.Disk; @@ -32,12 +32,15 @@ namespace NzbDrone.Core.Download 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; - protected DownloadClientBase(IConfigService configService, - IDiskProvider diskProvider, + protected DownloadClientBase(IConfigService configService, + IDiskProvider diskProvider, IRemotePathMappingService remotePathMappingService, Logger logger) { @@ -150,7 +153,7 @@ namespace NzbDrone.Core.Download 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/DownloadClientFactory.cs b/src/NzbDrone.Core/Download/DownloadClientFactory.cs index 909b48ed6..c8a8c302e 100644 --- a/src/NzbDrone.Core/Download/DownloadClientFactory.cs +++ b/src/NzbDrone.Core/Download/DownloadClientFactory.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using FluentValidation.Results; diff --git a/src/NzbDrone.Core/Download/DownloadClientProvider.cs b/src/NzbDrone.Core/Download/DownloadClientProvider.cs index 09d7d712e..fb321d8b5 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.Linq; using NLog; +using NzbDrone.Common.Cache; +using NzbDrone.Core.Indexers; namespace NzbDrone.Core.Download { @@ -32,7 +32,10 @@ namespace NzbDrone.Core.Download { 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 9acebdeb0..704dababc 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 @@ -16,4 +15,4 @@ namespace NzbDrone.Core.Download { } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Download/DownloadClientStatus.cs b/src/NzbDrone.Core/Download/DownloadClientStatus.cs index f4d819424..a6d388125 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 ac6cfc0b9..8070ce5a6 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 11eecfe89..19f11d4b7 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/DownloadClientType.cs b/src/NzbDrone.Core/Download/DownloadClientType.cs index a1d67fe23..6989a34fb 100644 --- a/src/NzbDrone.Core/Download/DownloadClientType.cs +++ b/src/NzbDrone.Core/Download/DownloadClientType.cs @@ -7,4 +7,4 @@ namespace NzbDrone.Core.Download Pneumatic = 2, Nzbget = 3 } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Download/DownloadEventHub.cs b/src/NzbDrone.Core/Download/DownloadEventHub.cs index 7ecb9c190..2c2ef8181 100644 --- a/src/NzbDrone.Core/Download/DownloadEventHub.cs +++ b/src/NzbDrone.Core/Download/DownloadEventHub.cs @@ -45,7 +45,7 @@ namespace NzbDrone.Core.Download else { MarkItemAsImported(message.TrackedDownload); - } + } } public void Handle(DownloadFailedEvent message) @@ -60,7 +60,6 @@ namespace NzbDrone.Core.Download RemoveFromDownloadClient(trackedDownload); } - private void RemoveFromDownloadClient(TrackedDownload trackedDownload) { var downloadClient = _downloadClientProvider.Get(trackedDownload.DownloadClient); diff --git a/src/NzbDrone.Core/Download/DownloadService.cs b/src/NzbDrone.Core/Download/DownloadService.cs index ad3fadf2b..f1348cf2e 100644 --- a/src/NzbDrone.Core/Download/DownloadService.cs +++ b/src/NzbDrone.Core/Download/DownloadService.cs @@ -5,7 +5,6 @@ using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Common.Instrumentation.Extensions; using NzbDrone.Common.TPL; -using NzbDrone.Core.Configuration; using NzbDrone.Core.Download.Clients; using NzbDrone.Core.Exceptions; using NzbDrone.Core.Indexers; @@ -92,6 +91,7 @@ namespace NzbDrone.Core.Download { _indexerStatusService.RecordFailure(remoteAlbum.Release.IndexerId); } + throw; } diff --git a/src/NzbDrone.Core/Download/FailedDownloadService.cs b/src/NzbDrone.Core/Download/FailedDownloadService.cs index 741a7d337..a86374ae0 100644 --- a/src/NzbDrone.Core/Download/FailedDownloadService.cs +++ b/src/NzbDrone.Core/Download/FailedDownloadService.cs @@ -75,7 +75,7 @@ namespace NzbDrone.Core.Download trackedDownload.Warn("Download wasn't grabbed by Lidarr, skipping"); return; } - + trackedDownload.State = TrackedDownloadStage.DownloadFailed; PublishDownloadFailedEvent(grabbedItems, failure, trackedDownload); } diff --git a/src/NzbDrone.Core/Download/InvalidNzbException.cs b/src/NzbDrone.Core/Download/InvalidNzbException.cs index 5607590d9..5fde39c54 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 d8a9467ce..19a19ce3a 100644 --- a/src/NzbDrone.Core/Download/Pending/PendingReleaseService.cs +++ b/src/NzbDrone.Core/Download/Pending/PendingReleaseService.cs @@ -1,3 +1,6 @@ +using System; +using System.Collections.Generic; +using System.Linq; using NLog; using NzbDrone.Common.Crypto; using NzbDrone.Common.Extensions; @@ -6,16 +9,12 @@ using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Indexers; using NzbDrone.Core.Jobs; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Music; +using NzbDrone.Core.Music.Events; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Delay; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Music; -using NzbDrone.Core.Music.Events; -using System; -using System.Collections.Generic; -using System.Linq; -using Marr.Data; namespace NzbDrone.Core.Download.Pending { @@ -67,7 +66,6 @@ namespace NzbDrone.Core.Download.Pending _logger = logger; } - public void Add(DownloadDecision decision, PendingReleaseReason reason) { AddMany(new List> { Tuple.Create(decision, reason) }); @@ -288,7 +286,10 @@ namespace NzbDrone.Core.Download.Pending var artist = artistMap.GetValueOrDefault(release.ArtistId); // Just in case the artist was removed, but wasn't cleaned up yet (housekeeper will clean it up) - if (artist == null) return null; + if (artist == null) + { + return null; + } List albums; diff --git a/src/NzbDrone.Core/Download/ProcessDownloadDecisions.cs b/src/NzbDrone.Core/Download/ProcessDownloadDecisions.cs index 180907f94..f43bd75eb 100644 --- a/src/NzbDrone.Core/Download/ProcessDownloadDecisions.cs +++ b/src/NzbDrone.Core/Download/ProcessDownloadDecisions.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Net; using NLog; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download.Clients; @@ -40,6 +39,7 @@ namespace NzbDrone.Core.Download var prioritizedDecisions = _prioritizeDownloadDecision.PrioritizeDecisions(qualifiedReports); var grabbed = new List(); var pending = new List(); + //var failed = new List(); var rejected = decisions.Where(d => d.Rejected).ToList(); @@ -65,8 +65,8 @@ namespace NzbDrone.Core.Download 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; @@ -137,7 +137,6 @@ namespace NzbDrone.Core.Download // 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 (IsAlbumProcessed(grabbed, report) || IsAlbumProcessed(pending, report)) { diff --git a/src/NzbDrone.Core/Download/RedownloadFailedDownloadService.cs b/src/NzbDrone.Core/Download/RedownloadFailedDownloadService.cs index ea3ce10d6..7c3b4ae6b 100644 --- a/src/NzbDrone.Core/Download/RedownloadFailedDownloadService.cs +++ b/src/NzbDrone.Core/Download/RedownloadFailedDownloadService.cs @@ -1,4 +1,3 @@ -using System.Linq; using NLog; using NzbDrone.Core.Configuration; using NzbDrone.Core.IndexerSearch; diff --git a/src/NzbDrone.Core/Download/TorrentClientBase.cs b/src/NzbDrone.Core/Download/TorrentClientBase.cs index 500a570db..6aa5f892d 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 { @@ -33,7 +33,7 @@ namespace NzbDrone.Core.Download _httpClient = httpClient; _torrentFileInfoReader = torrentFileInfoReader; } - + public override DownloadProtocol Protocol => DownloadProtocol.Torrent; public virtual bool PreferTorrentFile => false; @@ -61,7 +61,7 @@ namespace NzbDrone.Core.Download { magnetUrl = torrentInfo.MagnetUrl; } - + if (PreferTorrentFile) { if (torrentUrl.IsNotNullOrWhiteSpace()) @@ -192,7 +192,8 @@ namespace NzbDrone.Core.Download { _logger.Debug( "{0} did not return the expected InfoHash for '{1}', Lidarr could potentially lose track of the download in progress.", - Definition.Implementation, remoteAlbum.Release.DownloadUrl); + Definition.Implementation, + remoteAlbum.Release.DownloadUrl); } return actualHash; @@ -223,7 +224,8 @@ namespace NzbDrone.Core.Download { _logger.Debug( "{0} did not return the expected InfoHash for '{1}', Lidarr could potentially lose track of the download in progress.", - Definition.Implementation, remoteAlbum.Release.DownloadUrl); + Definition.Implementation, + remoteAlbum.Release.DownloadUrl); } return actualHash; diff --git a/src/NzbDrone.Core/Download/TrackedDownloads/DownloadMonitoringService.cs b/src/NzbDrone.Core/Download/TrackedDownloads/DownloadMonitoringService.cs index 6ee24ed4c..e8bdce3f6 100644 --- a/src/NzbDrone.Core/Download/TrackedDownloads/DownloadMonitoringService.cs +++ b/src/NzbDrone.Core/Download/TrackedDownloads/DownloadMonitoringService.cs @@ -15,7 +15,6 @@ namespace NzbDrone.Core.Download.TrackedDownloads IHandle, IHandle, IHandle - { private readonly IDownloadClientStatusService _downloadClientStatusService; private readonly IDownloadClientFactory _downloadClientFactory; @@ -110,7 +109,6 @@ namespace NzbDrone.Core.Download.TrackedDownloads } return trackedDownloads; - } private void RemoveCompletedDownloads(List trackedDownloads) @@ -135,11 +133,9 @@ namespace NzbDrone.Core.Download.TrackedDownloads { _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 14d969942..73294e8e8 100644 --- a/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownload.cs +++ b/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownload.cs @@ -17,7 +17,7 @@ namespace NzbDrone.Core.Download.TrackedDownloads 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 7b0ae83df..745a1e8b2 100644 --- a/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadService.cs +++ b/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadService.cs @@ -4,12 +4,12 @@ using System.Linq; using NLog; using NzbDrone.Common.Cache; using NzbDrone.Common.Extensions; +using NzbDrone.Common.Serializer; using NzbDrone.Core.History; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Music; -using NzbDrone.Core.Parser; -using NzbDrone.Common.Serializer; using NzbDrone.Core.Music.Events; +using NzbDrone.Core.Parser; namespace NzbDrone.Core.Download.TrackedDownloads { @@ -51,7 +51,6 @@ namespace NzbDrone.Core.Download.TrackedDownloads public void UpdateAlbumCache(int albumId) { - var updateCacheItems = _cache.Values.Where(x => x.RemoteAlbum != null && x.RemoteAlbum.Albums.Any(a => a.Id == albumId)).ToList(); foreach (var item in updateCacheItems) @@ -135,7 +134,6 @@ namespace NzbDrone.Core.Download.TrackedDownloads var grabbedEvent = historyItems.FirstOrDefault(v => v.EventType == HistoryEventType.Grabbed); trackedDownload.Indexer = grabbedEvent?.Data["indexer"]; - if (parsedAlbumInfo == null || trackedDownload.RemoteAlbum == null || trackedDownload.RemoteAlbum.Artist == null || @@ -159,7 +157,8 @@ namespace NzbDrone.Core.Download.TrackedDownloads { parsedAlbumInfo = Parser.Parser.ParseAlbumTitleWithSearchCriteria(firstHistoryItem.SourceTitle, - historyArtist, historyAlbums); + historyArtist, + historyAlbums); if (parsedAlbumInfo != null) { @@ -214,16 +213,16 @@ namespace NzbDrone.Core.Download.TrackedDownloads existingItem.CanMoveFiles != downloadItem.CanMoveFiles) { _logger.Debug("Tracking '{0}:{1}': ClientState={2}{3} LidarrStage={4} Album='{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.RemoteAlbum?.ParsedAlbumInfo, downloadItem.OutputPath); } } - private static TrackedDownloadStage GetStateFromHistory(NzbDrone.Core.History.History history) { switch (history.EventType) @@ -251,4 +250,3 @@ namespace NzbDrone.Core.Download.TrackedDownloads } } } - diff --git a/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadStatusMessage.cs b/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadStatusMessage.cs index 3e8e5164d..5ce6532d4 100644 --- a/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadStatusMessage.cs +++ b/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadStatusMessage.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Core.Download.TrackedDownloads 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 3e74f2fbb..381f837b5 100644 --- a/src/NzbDrone.Core/Download/UsenetClientBase.cs +++ b/src/NzbDrone.Core/Download/UsenetClientBase.cs @@ -1,15 +1,15 @@ using System.Net; +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.Organizer; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Configuration; -using NLog; -using NzbDrone.Common.Extensions; using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Core.Download { @@ -30,7 +30,7 @@ namespace NzbDrone.Core.Download _httpClient = httpClient; _nzbValidationService = nzbValidationService; } - + public override DownloadProtocol Protocol => DownloadProtocol.Usenet; protected abstract string AddFromNzbFile(RemoteAlbum remoteAlbum, string filename, byte[] fileContent); @@ -38,7 +38,7 @@ namespace NzbDrone.Core.Download public override string Download(RemoteAlbum remoteAlbum) { var url = remoteAlbum.Release.DownloadUrl; - var filename = FileNameBuilder.CleanFileName(remoteAlbum.Release.Title) + ".nzb"; + var filename = FileNameBuilder.CleanFileName(remoteAlbum.Release.Title) + ".nzb"; byte[] nzbData; @@ -51,7 +51,7 @@ namespace NzbDrone.Core.Download { nzbDataRequest.Headers.Set("Authorization", "Basic " + remoteAlbum.Release.BasicAuthString); } - + nzbData = _httpClient.Get(nzbDataRequest).ResponseData; _logger.Debug("Downloaded nzb for release '{0}' finished ({1} bytes from {2})", remoteAlbum.Release.Title, nzbData.Length, url); diff --git a/src/NzbDrone.Core/Exceptions/AlbumNotFoundException.cs b/src/NzbDrone.Core/Exceptions/AlbumNotFoundException.cs index d9ac2729f..d07d6adb9 100644 --- a/src/NzbDrone.Core/Exceptions/AlbumNotFoundException.cs +++ b/src/NzbDrone.Core/Exceptions/AlbumNotFoundException.cs @@ -1,8 +1,4 @@ using NzbDrone.Common.Exceptions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace NzbDrone.Core.Exceptions { diff --git a/src/NzbDrone.Core/Exceptions/ArtistNotFoundException.cs b/src/NzbDrone.Core/Exceptions/ArtistNotFoundException.cs index 321777c79..fc1e69078 100644 --- a/src/NzbDrone.Core/Exceptions/ArtistNotFoundException.cs +++ b/src/NzbDrone.Core/Exceptions/ArtistNotFoundException.cs @@ -1,8 +1,4 @@ using NzbDrone.Common.Exceptions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace NzbDrone.Core.Exceptions { diff --git a/src/NzbDrone.Core/Exceptions/BadRequestException.cs b/src/NzbDrone.Core/Exceptions/BadRequestException.cs index adf8bf57f..b74559d05 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 0ce8f1a94..88bf850fa 100644 --- a/src/NzbDrone.Core/Exceptions/DownstreamException.cs +++ b/src/NzbDrone.Core/Exceptions/DownstreamException.cs @@ -7,7 +7,8 @@ namespace NzbDrone.Core.Exceptions { 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 d9225eb2c..ed44e447c 100644 --- a/src/NzbDrone.Core/Exceptions/NzbDroneClientException.cs +++ b/src/NzbDrone.Core/Exceptions/NzbDroneClientException.cs @@ -7,7 +7,8 @@ namespace NzbDrone.Core.Exceptions { 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 c9582ddde..b891b6d3b 100644 --- a/src/NzbDrone.Core/Exceptions/ReleaseDownloadException.cs +++ b/src/NzbDrone.Core/Exceptions/ReleaseDownloadException.cs @@ -8,7 +8,8 @@ namespace NzbDrone.Core.Exceptions { 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/Extras/ExtraService.cs b/src/NzbDrone.Core/Extras/ExtraService.cs index 17b2168f8..dd3c7ae90 100644 --- a/src/NzbDrone.Core/Extras/ExtraService.cs +++ b/src/NzbDrone.Core/Extras/ExtraService.cs @@ -11,8 +11,8 @@ using NzbDrone.Core.MediaCover; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Music; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.Extras { @@ -81,7 +81,6 @@ namespace NzbDrone.Core.Extras 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 360bbb13c..c618557d9 100644 --- a/src/NzbDrone.Core/Extras/Files/ExtraFileManager.cs +++ b/src/NzbDrone.Core/Extras/Files/ExtraFileManager.cs @@ -23,7 +23,6 @@ namespace NzbDrone.Core.Extras.Files public abstract class ExtraFileManager : IManageExtraFiles where TExtraFile : ExtraFile, new() - { private readonly IConfigService _configService; private readonly IDiskProvider _diskProvider; diff --git a/src/NzbDrone.Core/Extras/Files/ExtraFileRepository.cs b/src/NzbDrone.Core/Extras/Files/ExtraFileRepository.cs index 5e3a900a6..e124f390b 100644 --- a/src/NzbDrone.Core/Extras/Files/ExtraFileRepository.cs +++ b/src/NzbDrone.Core/Extras/Files/ExtraFileRepository.cs @@ -5,7 +5,8 @@ using NzbDrone.Core.Messaging.Events; namespace NzbDrone.Core.Extras.Files { - public interface IExtraFileRepository : IBasicRepository where TExtraFile : ExtraFile, new() + public interface IExtraFileRepository : IBasicRepository + where TExtraFile : ExtraFile, new() { void DeleteForArtist(int artistId); void DeleteForAlbum(int artistId, int albumId); diff --git a/src/NzbDrone.Core/Extras/Files/ExtraFileService.cs b/src/NzbDrone.Core/Extras/Files/ExtraFileService.cs index d5a61ee6e..f4a8dc8f2 100644 --- a/src/NzbDrone.Core/Extras/Files/ExtraFileService.cs +++ b/src/NzbDrone.Core/Extras/Files/ExtraFileService.cs @@ -109,7 +109,6 @@ namespace NzbDrone.Core.Extras.Files { _logger.Debug("Removing track file from DB as part of cleanup routine, not deleting extra files from disk."); } - else { var artist = trackFile.Artist.Value; diff --git a/src/NzbDrone.Core/Extras/Lyrics/ExistingLyricImporter.cs b/src/NzbDrone.Core/Extras/Lyrics/ExistingLyricImporter.cs index 86a55f1c3..fae0518b4 100644 --- a/src/NzbDrone.Core/Extras/Lyrics/ExistingLyricImporter.cs +++ b/src/NzbDrone.Core/Extras/Lyrics/ExistingLyricImporter.cs @@ -4,10 +4,9 @@ using System.Linq; using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Core.Extras.Files; -using NzbDrone.Core.Parser; +using NzbDrone.Core.MediaFiles.TrackImport.Aggregation; using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.MediaFiles.TrackImport.Aggregation; namespace NzbDrone.Core.Extras.Lyrics { @@ -20,7 +19,7 @@ namespace NzbDrone.Core.Extras.Lyrics public ExistingLyricImporter(IExtraFileService lyricFileService, IAugmentingService augmentingService, Logger logger) - : base (lyricFileService) + : base(lyricFileService) { _lyricFileService = lyricFileService; _augmentingService = augmentingService; @@ -72,13 +71,13 @@ namespace NzbDrone.Core.Extras.Lyrics } var subtitleFile = new LyricFile - { - ArtistId = artist.Id, - AlbumId = localTrack.Album.Id, - TrackFileId = localTrack.Tracks.First().TrackFileId, - RelativePath = artist.Path.GetRelativePath(possibleLyricFile), - Extension = extension - }; + { + ArtistId = artist.Id, + AlbumId = localTrack.Album.Id, + TrackFileId = localTrack.Tracks.First().TrackFileId, + RelativePath = artist.Path.GetRelativePath(possibleLyricFile), + Extension = extension + }; subtitleFiles.Add(subtitleFile); } @@ -89,7 +88,6 @@ namespace NzbDrone.Core.Extras.Lyrics // 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/Lyrics/LyricService.cs b/src/NzbDrone.Core/Extras/Lyrics/LyricService.cs index 7972cf20a..ae4a32e0d 100644 --- a/src/NzbDrone.Core/Extras/Lyrics/LyricService.cs +++ b/src/NzbDrone.Core/Extras/Lyrics/LyricService.cs @@ -8,7 +8,6 @@ using NzbDrone.Common.Extensions; using NzbDrone.Core.Configuration; using NzbDrone.Core.Extras.Files; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Parser; using NzbDrone.Core.Music; namespace NzbDrone.Core.Extras.Lyrics diff --git a/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadata.cs b/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadata.cs index 11618a6af..fb64e6d6b 100644 --- a/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadata.cs +++ b/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadata.cs @@ -52,15 +52,19 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Roksbox { var filename = Path.GetFileName(path); - if (filename == null) return null; + if (filename == null) + { + return null; + } + var parentdir = Directory.GetParent(path); var metadata = new MetadataFile - { - ArtistId = artist.Id, - Consumer = GetType().Name, - RelativePath = artist.Path.GetRelativePath(path) - }; + { + ArtistId = artist.Id, + Consumer = GetType().Name, + RelativePath = artist.Path.GetRelativePath(path) + }; //Series and season images are both named folder.jpg, only season ones sit in season folders if (Path.GetFileNameWithoutExtension(filename).Equals(parentdir.Name, StringComparison.InvariantCultureIgnoreCase)) @@ -75,7 +79,6 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Roksbox { metadata.AlbumId = 0; } - else { metadata.AlbumId = Convert.ToInt32(seasonMatch.Groups["season"].Value); @@ -98,7 +101,7 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Roksbox { metadata.Type = MetadataType.TrackMetadata; return metadata; - } + } } return null; @@ -121,7 +124,7 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Roksbox { return null; } - + _logger.Debug("Generating Track Metadata for: {0}", trackFile.Path); var xmlResult = string.Empty; @@ -162,13 +165,13 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Roksbox if (image == null) { _logger.Trace("Failed to find suitable Artist image for artist {0}.", artist.Name); - return new List(); ; + return new List(); } var source = _mediaCoverService.GetCoverPath(artist.Id, MediaCoverEntity.Artist, image.CoverType, image.Extension); var destination = Path.GetFileName(artist.Path) + Path.GetExtension(source); - return new List{ new ImageFileResult(destination, source) }; + return new List { new ImageFileResult(destination, source) }; } public override List AlbumImages(Artist artist, Album album, string albumFolder) diff --git a/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadataSettings.cs b/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadataSettings.cs index f9cb73281..d0213c72a 100644 --- a/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadataSettings.cs +++ b/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadataSettings.cs @@ -28,7 +28,7 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Roksbox [FieldDefinition(2, Label = "Album Images", Type = FieldType.Checkbox, Section = MetadataSectionType.Image, HelpText = "Album Title.jpg")] public bool AlbumImages { get; set; } - + public bool IsValid => true; public NzbDroneValidationResult Validate() diff --git a/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadata.cs b/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadata.cs index 7ce21dbda..609f8b6dd 100644 --- a/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadata.cs +++ b/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadata.cs @@ -1,9 +1,7 @@ using System; using System.Collections.Generic; using System.IO; -using System.Linq; using System.Text; -using System.Text.RegularExpressions; using System.Xml; using System.Xml.Linq; using NLog; @@ -44,21 +42,23 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Wdtv _logger.Debug("Unknown track file metadata: {0}", metadataFile.RelativePath); return Path.Combine(artist.Path, metadataFile.RelativePath); - } public override MetadataFile FindMetadataFile(Artist artist, string path) { var filename = Path.GetFileName(path); - if (filename == null) return null; + if (filename == null) + { + return null; + } var metadata = new MetadataFile - { - ArtistId = artist.Id, - Consumer = GetType().Name, - RelativePath = artist.Path.GetRelativePath(path) - }; + { + ArtistId = artist.Id, + Consumer = GetType().Name, + RelativePath = artist.Path.GetRelativePath(path) + }; var parseResult = Parser.Parser.ParseMusicTitle(filename); @@ -70,7 +70,6 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Wdtv metadata.Type = MetadataType.TrackMetadata; return metadata; } - } return null; @@ -141,7 +140,6 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Wdtv public override List TrackImages(Artist artist, TrackFile trackFile) { - return new List(); } diff --git a/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadataSettings.cs b/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadataSettings.cs index 3f67bc746..4045486f5 100644 --- a/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadataSettings.cs +++ b/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadataSettings.cs @@ -20,7 +20,7 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Wdtv [FieldDefinition(0, Label = "Track Metadata", Type = FieldType.Checkbox, Section = MetadataSectionType.Metadata)] public bool TrackMetadata { get; set; } - + public bool IsValid => true; public NzbDroneValidationResult Validate() diff --git a/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcMetadata.cs b/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcMetadata.cs index e5e0a9992..d48f6a141 100644 --- a/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcMetadata.cs +++ b/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcMetadata.cs @@ -52,7 +52,10 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Xbmc { var filename = Path.GetFileName(path); - if (filename == null) return null; + if (filename == null) + { + return null; + } var metadata = new MetadataFile { @@ -163,7 +166,7 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Xbmc doc.Save(xw); _logger.Debug("Saving album.nfo for {0}", album.Title); - + var fileName = Path.Combine(albumPath, "album.nfo"); return new MetadataFileResult(fileName, doc.ToString()); @@ -197,7 +200,6 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Xbmc public override List TrackImages(Artist artist, TrackFile trackFile) { - return new List(); } @@ -224,7 +226,7 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Xbmc // var source = _mediaCoverService.GetCoverPath(album.ArtistId, image.CoverType, null, album.Id); string filename; - switch(image.CoverType) + switch (image.CoverType) { case MediaCoverTypes.Cover: filename = "folder"; @@ -246,6 +248,5 @@ namespace NzbDrone.Core.Extras.Metadata.Consumers.Xbmc { return Path.ChangeExtension(trackFilePath, "nfo"); } - } } diff --git a/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcNfoDetector.cs b/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcNfoDetector.cs index 234d27f22..4132602ec 100644 --- a/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcNfoDetector.cs +++ b/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcNfoDetector.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Text.RegularExpressions; using NzbDrone.Common.Disk; diff --git a/src/NzbDrone.Core/Extras/Metadata/ExistingMetadataImporter.cs b/src/NzbDrone.Core/Extras/Metadata/ExistingMetadataImporter.cs index 03fbe8a91..61519dd46 100644 --- a/src/NzbDrone.Core/Extras/Metadata/ExistingMetadataImporter.cs +++ b/src/NzbDrone.Core/Extras/Metadata/ExistingMetadataImporter.cs @@ -4,11 +4,11 @@ using System.Linq; using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Core.Extras.Files; -using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.Extras.Lyrics; -using NzbDrone.Core.Parser; -using NzbDrone.Core.Music; +using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.MediaFiles.TrackImport.Aggregation; +using NzbDrone.Core.Music; +using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.Extras.Metadata @@ -47,7 +47,6 @@ namespace NzbDrone.Core.Extras.Metadata foreach (var possibleMetadataFile in filterResult.FilesOnDisk) { // Don't process files that have known Subtitle file extensions (saves a bit of unecessary processing) - if (LyricFileExtensions.Extensions.Contains(Path.GetExtension(possibleMetadataFile))) { continue; @@ -83,7 +82,7 @@ namespace NzbDrone.Core.Extras.Metadata Artist = artist, Path = possibleMetadataFile }; - + try { _augmentingService.Augment(localTrack, false); @@ -105,7 +104,7 @@ namespace NzbDrone.Core.Extras.Metadata _logger.Debug("Extra file: {0} does not match existing files.", possibleMetadataFile); continue; } - + metadata.TrackFileId = localTrack.Tracks.First().TrackFileId; } @@ -120,7 +119,6 @@ namespace NzbDrone.Core.Extras.Metadata // 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/Files/MetadataFileRepository.cs b/src/NzbDrone.Core/Extras/Metadata/Files/MetadataFileRepository.cs index d1f29ea75..1a8b0aae8 100644 --- a/src/NzbDrone.Core/Extras/Metadata/Files/MetadataFileRepository.cs +++ b/src/NzbDrone.Core/Extras/Metadata/Files/MetadataFileRepository.cs @@ -15,4 +15,4 @@ namespace NzbDrone.Core.Extras.Metadata.Files { } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Extras/Metadata/IMetadata.cs b/src/NzbDrone.Core/Extras/Metadata/IMetadata.cs index 7abee9e8b..032de483d 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.Music; +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 7650402a5..55c0189cb 100644 --- a/src/NzbDrone.Core/Extras/Metadata/MetadataBase.cs +++ b/src/NzbDrone.Core/Extras/Metadata/MetadataBase.cs @@ -4,12 +4,13 @@ using System.IO; using FluentValidation.Results; using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Music; +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; } @@ -52,7 +53,10 @@ namespace NzbDrone.Core.Extras.Metadata public abstract List AlbumImages(Artist artist, Album album, string albumPath); public abstract List TrackImages(Artist artist, TrackFile trackFile); - 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/MetadataFactory.cs b/src/NzbDrone.Core/Extras/Metadata/MetadataFactory.cs index 5fe8db3f5..b52d8a18c 100644 --- a/src/NzbDrone.Core/Extras/Metadata/MetadataFactory.cs +++ b/src/NzbDrone.Core/Extras/Metadata/MetadataFactory.cs @@ -53,4 +53,4 @@ namespace NzbDrone.Core.Extras.Metadata return GetAvailableProviders().Where(n => ((MetadataDefinition)n.Definition).Enable).ToList(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Extras/Metadata/MetadataRepository.cs b/src/NzbDrone.Core/Extras/Metadata/MetadataRepository.cs index 349da708e..942a5172b 100644 --- a/src/NzbDrone.Core/Extras/Metadata/MetadataRepository.cs +++ b/src/NzbDrone.Core/Extras/Metadata/MetadataRepository.cs @@ -15,4 +15,4 @@ namespace NzbDrone.Core.Extras.Metadata { } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Extras/Metadata/MetadataService.cs b/src/NzbDrone.Core/Extras/Metadata/MetadataService.cs index ef1b2884d..7432fc35b 100644 --- a/src/NzbDrone.Core/Extras/Metadata/MetadataService.cs +++ b/src/NzbDrone.Core/Extras/Metadata/MetadataService.cs @@ -13,7 +13,6 @@ using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.Extras.Others; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Music; -using NzbDrone.Core.Organizer; namespace NzbDrone.Core.Extras.Metadata { @@ -79,7 +78,7 @@ namespace NzbDrone.Core.Extras.Metadata files.AddIfNotNull(ProcessArtistMetadata(consumer, artist, consumerFiles)); files.AddRange(ProcessArtistImages(consumer, artist, consumerFiles)); - + var albumGroups = trackFiles.GroupBy(s => Path.GetDirectoryName(s.Path)).ToList(); foreach (var group in albumGroups) @@ -150,7 +149,6 @@ namespace NzbDrone.Core.Extras.Metadata // TODO: Move EpisodeImage and EpisodeMetadata metadata files, instead of relying on consumers to do it // (Xbmc's EpisodeImage is more than just the extension) - foreach (var consumer in _metadataFactory.GetAvailableProviders()) { foreach (var filePath in distinctTrackFilePaths) @@ -181,7 +179,6 @@ namespace NzbDrone.Core.Extras.Metadata } } - foreach (var trackFile in trackFiles) { var metadataFilesForConsumer = GetMetadataFilesForConsumer(consumer, metadataFiles).Where(m => m.TrackFileId == trackFile.Id).ToList(); @@ -436,7 +433,6 @@ namespace NzbDrone.Core.Extras.Metadata result.Add(metadata); } - return result; } @@ -454,6 +450,7 @@ namespace NzbDrone.Core.Extras.Metadata { _diskProvider.CopyFile(image.Url, fullPath); } + _mediaFileAttributeService.SetFilePermissions(fullPath); } catch (WebException ex) @@ -492,7 +489,7 @@ namespace NzbDrone.Core.Extras.Metadata _recycleBinProvider.DeleteFile(path, subfolder); _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 e63baf28a..35d83e570 100644 --- a/src/NzbDrone.Core/Extras/Others/ExistingOtherExtraImporter.cs +++ b/src/NzbDrone.Core/Extras/Others/ExistingOtherExtraImporter.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -6,7 +5,6 @@ using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Core.Extras.Files; using NzbDrone.Core.MediaFiles.TrackImport.Aggregation; -using NzbDrone.Core.Parser; using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; @@ -53,7 +51,7 @@ namespace NzbDrone.Core.Extras.Others Artist = artist, Path = possibleExtraFile }; - + try { _augmentingService.Augment(localTrack, false); @@ -93,7 +91,6 @@ namespace NzbDrone.Core.Extras.Others // 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/Others/OtherExtraFileRenamer.cs b/src/NzbDrone.Core/Extras/Others/OtherExtraFileRenamer.cs index 8231f9563..b5f321e61 100644 --- a/src/NzbDrone.Core/Extras/Others/OtherExtraFileRenamer.cs +++ b/src/NzbDrone.Core/Extras/Others/OtherExtraFileRenamer.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; diff --git a/src/NzbDrone.Core/Extras/Others/OtherExtraFileRepository.cs b/src/NzbDrone.Core/Extras/Others/OtherExtraFileRepository.cs index 3f33a3eb8..91fbdb056 100644 --- a/src/NzbDrone.Core/Extras/Others/OtherExtraFileRepository.cs +++ b/src/NzbDrone.Core/Extras/Others/OtherExtraFileRepository.cs @@ -15,4 +15,4 @@ namespace NzbDrone.Core.Extras.Others { } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Extras/Others/OtherExtraService.cs b/src/NzbDrone.Core/Extras/Others/OtherExtraService.cs index 2c4dbaa20..10c5a8a73 100644 --- a/src/NzbDrone.Core/Extras/Others/OtherExtraService.cs +++ b/src/NzbDrone.Core/Extras/Others/OtherExtraService.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.IO; using System.Linq; using NLog; using NzbDrone.Common.Disk; diff --git a/src/NzbDrone.Core/Fluent.cs b/src/NzbDrone.Core/Fluent.cs index 98e38a1d3..41f031816 100644 --- a/src/NzbDrone.Core/Fluent.cs +++ b/src/NzbDrone.Core/Fluent.cs @@ -50,7 +50,6 @@ namespace NzbDrone.Core 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); @@ -59,16 +58,24 @@ namespace NzbDrone.Core 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(); } @@ -76,12 +83,16 @@ namespace NzbDrone.Core public static int MaxOrDefault(this IEnumerable ints) { if (ints == null) + { return 0; + } var intList = ints.ToList(); if (!intList.Any()) + { return 0; + } return intList.Max(); } @@ -89,7 +100,10 @@ namespace NzbDrone.Core 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; @@ -97,7 +111,10 @@ namespace NzbDrone.Core { 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) { @@ -105,20 +122,27 @@ namespace NzbDrone.Core 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/Checks/AppDataLocationCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/AppDataLocationCheck.cs index d4f9a7cc7..56b7fd35a 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/AppDataLocationCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/AppDataLocationCheck.cs @@ -1,6 +1,5 @@ using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Common.Extensions; -using NzbDrone.Core.Configuration.Events; namespace NzbDrone.Core.HealthCheck.Checks { @@ -12,7 +11,7 @@ namespace NzbDrone.Core.HealthCheck.Checks { _appFolderInfo = appFolderInfo; } - + public override HealthCheck Check() { if (_appFolderInfo.StartUpFolder.IsParentPath(_appFolderInfo.AppDataFolder) || @@ -23,6 +22,5 @@ namespace NzbDrone.Core.HealthCheck.Checks return new HealthCheck(GetType()); } - } } diff --git a/src/NzbDrone.Core/HealthCheck/Checks/DotnetVersionCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/DotnetVersionCheck.cs index 4736e670b..99e8355e2 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/DotnetVersionCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/DotnetVersionCheck.cs @@ -45,12 +45,14 @@ namespace NzbDrone.Core.HealthCheck.Checks 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/DownloadClientStatusCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/DownloadClientStatusCheck.cs index 91b9b122d..b813dbdfd 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/DownloadClientStatusCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/DownloadClientStatusCheck.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using NzbDrone.Common.Extensions; using NzbDrone.Core.Download; diff --git a/src/NzbDrone.Core/HealthCheck/Checks/FpcalcCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/FpcalcCheck.cs index 156a4946f..c46e240ab 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/FpcalcCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/FpcalcCheck.cs @@ -10,14 +10,14 @@ namespace NzbDrone.Core.HealthCheck.Checks { private readonly IFingerprintingService _fingerprintingService; private readonly IConfigService _configService; - + public FpcalcCheck(IFingerprintingService fingerprintingService, IConfigService configService) { _fingerprintingService = fingerprintingService; _configService = configService; } - + public override HealthCheck Check() { // always pass if fingerprinting is disabled @@ -25,7 +25,7 @@ namespace NzbDrone.Core.HealthCheck.Checks { return new HealthCheck(GetType()); } - + if (!_fingerprintingService.IsSetup()) { return new HealthCheck(GetType(), HealthCheckResult.Warning, $"fpcalc could not be found. Audio fingerprinting disabled.", "#fpcalc-missing"); diff --git a/src/NzbDrone.Core/HealthCheck/Checks/ImportListStatusCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/ImportListStatusCheck.cs index 4a3855146..e815ce334 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/ImportListStatusCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/ImportListStatusCheck.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using NzbDrone.Common.Extensions; using NzbDrone.Core.ImportLists; diff --git a/src/NzbDrone.Core/HealthCheck/Checks/ImportMechanismCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/ImportMechanismCheck.cs index c6b6fedd6..b201cf7c4 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/ImportMechanismCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/ImportMechanismCheck.cs @@ -12,7 +12,6 @@ namespace NzbDrone.Core.HealthCheck.Checks { private readonly IConfigService _configService; - public ImportMechanismCheck(IConfigService configService) { _configService = configService; diff --git a/src/NzbDrone.Core/HealthCheck/Checks/IndexerRssCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/IndexerRssCheck.cs index 6c4f1f60d..d24a34054 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/IndexerRssCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/IndexerRssCheck.cs @@ -1,4 +1,3 @@ -using System.Linq; using NzbDrone.Common.Extensions; using NzbDrone.Core.Indexers; using NzbDrone.Core.ThingiProvider.Events; @@ -31,7 +30,7 @@ namespace NzbDrone.Core.HealthCheck.Checks 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/IndexerSearchCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/IndexerSearchCheck.cs index b15980ee3..597c6b3aa 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/IndexerSearchCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/IndexerSearchCheck.cs @@ -1,4 +1,3 @@ -using System.Linq; using NzbDrone.Common.Extensions; using NzbDrone.Core.Indexers; using NzbDrone.Core.ThingiProvider.Events; diff --git a/src/NzbDrone.Core/HealthCheck/Checks/IndexerStatusCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/IndexerStatusCheck.cs index d608686a2..b7065f45f 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/IndexerStatusCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/IndexerStatusCheck.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using NzbDrone.Common.Extensions; using NzbDrone.Core.Indexers; diff --git a/src/NzbDrone.Core/HealthCheck/Checks/MonoTlsCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/MonoTlsCheck.cs index 01e690ac9..c1f9ecc8b 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/MonoTlsCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/MonoTlsCheck.cs @@ -1,6 +1,4 @@ using System; -using System.Linq; -using System.Reflection; using NLog; using NLog.Fluent; using NzbDrone.Common.EnvironmentInfo; diff --git a/src/NzbDrone.Core/HealthCheck/Checks/MonoVersionCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/MonoVersionCheck.cs index 3afeb6ae0..70d3dd68a 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/MonoVersionCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/MonoVersionCheck.cs @@ -28,7 +28,8 @@ namespace NzbDrone.Core.HealthCheck.Checks 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 @@ namespace NzbDrone.Core.HealthCheck.Checks 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,17 +59,18 @@ namespace NzbDrone.Core.HealthCheck.Checks if (monoVersion >= supportedVersion) { _logger.Debug("Mono version is {0} or better: {1}", supportedVersion, monoVersion); - return new HealthCheck(GetType(), HealthCheckResult.Warning, - $"Currently installed Mono version {monoVersion} is supported but has some known issues. Please upgrade Mono to version {bestVersion}.", + 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, - $"Currently installed Mono version {monoVersion} is old and unsupported. Please upgrade Mono to version {bestVersion}.", + 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"); } public override bool CheckOnSchedule => false; - } } diff --git a/src/NzbDrone.Core/HealthCheck/Checks/ProxyCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/ProxyCheck.cs index 71ededd18..d75e29ed3 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.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/RemotePathMappingCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/RemotePathMappingCheck.cs index ba9ae6eaa..07a4423c2 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/RemotePathMappingCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/RemotePathMappingCheck.cs @@ -95,6 +95,7 @@ namespace NzbDrone.Core.HealthCheck.Checks _logger.Error(ex, "Unknown error occured in RemotePathMapping HealthCheck"); } } + return new HealthCheck(GetType()); } @@ -102,7 +103,7 @@ namespace NzbDrone.Core.HealthCheck.Checks { if (typeof(TrackImportFailedEvent).IsAssignableFrom(message.GetType())) { - var failureMessage = (TrackImportFailedEvent) message; + var failureMessage = (TrackImportFailedEvent)message; // if we can see the file exists but the import failed then likely a permissions issue if (failureMessage.TrackInfo != null) @@ -155,7 +156,7 @@ namespace NzbDrone.Core.HealthCheck.Checks { return new HealthCheck(GetType(), HealthCheckResult.Error, $"Lidarr can see but not access download directory {dlpath}. Likely permissions error.", "#permissions-error"); } - + // if it's a remote client/docker, likely missing path mappings if (_osInfo.IsDocker) { diff --git a/src/NzbDrone.Core/HealthCheck/Checks/UpdateCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/UpdateCheck.cs index d474b503c..6b6d92d1f 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/UpdateCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/UpdateCheck.cs @@ -38,21 +38,24 @@ namespace NzbDrone.Core.HealthCheck.Checks { 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 f31fa7efd..49492c368 100644 --- a/src/NzbDrone.Core/HealthCheck/HealthCheckService.cs +++ b/src/NzbDrone.Core/HealthCheck/HealthCheckService.cs @@ -6,13 +6,9 @@ using NzbDrone.Common.Cache; using NzbDrone.Common.Extensions; using NzbDrone.Common.Messaging; using NzbDrone.Common.Reflection; -using NzbDrone.Core.Configuration.Events; -using NzbDrone.Core.Download; -using NzbDrone.Core.Indexers; using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.ThingiProvider.Events; namespace NzbDrone.Core.HealthCheck { @@ -88,7 +84,6 @@ namespace NzbDrone.Core.HealthCheck { _healthCheckResults.Remove(result.Source.Name); } - else { if (_healthCheckResults.Find(result.Source.Name) == null) @@ -97,7 +92,6 @@ namespace NzbDrone.Core.HealthCheck } _healthCheckResults.Set(result.Source.Name, result); - } } diff --git a/src/NzbDrone.Core/History/History.cs b/src/NzbDrone.Core/History/History.cs index 24aad2670..2949aae28 100644 --- a/src/NzbDrone.Core/History/History.cs +++ b/src/NzbDrone.Core/History/History.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using NzbDrone.Core.Datastore; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Music; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.History { @@ -28,7 +28,6 @@ namespace NzbDrone.Core.History public Dictionary Data { get; set; } public string DownloadId { get; set; } - } public enum HistoryEventType diff --git a/src/NzbDrone.Core/History/HistoryRepository.cs b/src/NzbDrone.Core/History/HistoryRepository.cs index e21efec4f..4126a8071 100644 --- a/src/NzbDrone.Core/History/HistoryRepository.cs +++ b/src/NzbDrone.Core/History/HistoryRepository.cs @@ -4,8 +4,8 @@ using System.Linq; using Marr.Data.QGen; using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Music; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.History { @@ -19,18 +19,15 @@ namespace NzbDrone.Core.History List FindDownloadHistory(int idArtistId, QualityModel quality); void DeleteForArtist(int artistId); List Since(DateTime date, HistoryEventType? eventType); - } public class HistoryRepository : BasicRepository, IHistoryRepository { - public HistoryRepository(IMainDatabase database, IEventAggregator eventAggregator) : base(database, eventAggregator) { } - public History MostRecentForAlbum(int albumId) { return Query.Where(h => h.AlbumId == albumId) @@ -88,8 +85,8 @@ namespace NzbDrone.Core.History h.Quality == quality && (h.EventType == HistoryEventType.Grabbed || h.EventType == HistoryEventType.DownloadFailed || - h.EventType == HistoryEventType.TrackFileImported) - ).ToList(); + h.EventType == HistoryEventType.TrackFileImported)) + .ToList(); } public void DeleteForArtist(int artistId) diff --git a/src/NzbDrone.Core/History/HistoryService.cs b/src/NzbDrone.Core/History/HistoryService.cs index 7decd0d49..4ca7ff955 100644 --- a/src/NzbDrone.Core/History/HistoryService.cs +++ b/src/NzbDrone.Core/History/HistoryService.cs @@ -4,15 +4,15 @@ using System.IO; using System.Linq; using NLog; using NzbDrone.Common.Extensions; +using NzbDrone.Common.Serializer; using NzbDrone.Core.Datastore; using NzbDrone.Core.Download; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Music.Events; +using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; -using NzbDrone.Common.Serializer; namespace NzbDrone.Core.History { @@ -98,7 +98,6 @@ namespace NzbDrone.Core.History var allHistory = _historyRepository.FindDownloadHistory(trackedDownload.TrackInfo.Artist.Id, trackedDownload.ImportedTrack.Quality); - //Find download related items for these episdoes var albumsHistory = allHistory.Where(h => albumIds.Contains(h.AlbumId)).ToList(); @@ -217,15 +216,15 @@ namespace NzbDrone.Core.History foreach (var track in message.TrackInfo.Tracks) { var history = new History - { - EventType = HistoryEventType.TrackFileImported, - Date = DateTime.UtcNow, - Quality = message.TrackInfo.Quality, - SourceTitle = message.ImportedTrack.SceneName ?? Path.GetFileNameWithoutExtension(message.TrackInfo.Path), - ArtistId = message.TrackInfo.Artist.Id, - AlbumId = message.TrackInfo.Album.Id, - TrackId = track.Id, - DownloadId = downloadId + { + EventType = HistoryEventType.TrackFileImported, + Date = DateTime.UtcNow, + Quality = message.TrackInfo.Quality, + SourceTitle = message.ImportedTrack.SceneName ?? Path.GetFileNameWithoutExtension(message.TrackInfo.Path), + ArtistId = message.TrackInfo.Artist.Id, + AlbumId = message.TrackInfo.Album.Id, + TrackId = track.Id, + DownloadId = downloadId }; //Won't have a value since we publish this event before saving to DB. @@ -292,7 +291,6 @@ namespace NzbDrone.Core.History return; } - foreach (var track in message.TrackFile.Tracks.Value) { var history = new History @@ -355,13 +353,14 @@ namespace NzbDrone.Core.History AlbumId = message.TrackFile.AlbumId, TrackId = track.Id, }; - + history.Data.Add("TagsScrubbed", message.Scrubbed.ToString()); - history.Data.Add("Diff", message.Diff.Select(x => new { - Field = x.Key, - OldValue = x.Value.Item1, - NewValue = x.Value.Item2 - }).ToJson()); + history.Data.Add("Diff", message.Diff.Select(x => new + { + Field = x.Key, + OldValue = x.Value.Item1, + NewValue = x.Value.Item2 + }).ToJson()); _historyRepository.Insert(history); } diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/DeleteBadMediaCovers.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/DeleteBadMediaCovers.cs index df2fd5389..becadec0e 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/DeleteBadMediaCovers.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/DeleteBadMediaCovers.cs @@ -33,7 +33,10 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers public void Clean() { - if (!_configService.CleanupMetadataImages) return; + if (!_configService.CleanupMetadataImages) + { + return; + } var artists = _artistService.GetAllArtists(); var imageExtensions = new List { ".jpg", ".png", ".gif" }; @@ -61,7 +64,6 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers } } - _configService.CleanupMetadataImages = false; } @@ -77,7 +79,11 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers 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 80bf5c8b9..55a4c6b3d 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/FixFutureProviderStatusTimes.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/FixFutureProviderStatusTimes.cs @@ -5,7 +5,8 @@ using NzbDrone.Core.ThingiProvider.Status; 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/Housekeepers/UpdateCleanTitleForArtist.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/UpdateCleanTitleForArtist.cs index a1c5a3227..f8649e5d6 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/UpdateCleanTitleForArtist.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/UpdateCleanTitleForArtist.cs @@ -1,6 +1,6 @@ using System.Linq; -using NzbDrone.Core.Parser; using NzbDrone.Core.Music; +using NzbDrone.Core.Parser; namespace NzbDrone.Core.Housekeeping.Housekeepers { diff --git a/src/NzbDrone.Core/Housekeeping/HousekeepingService.cs b/src/NzbDrone.Core/Housekeeping/HousekeepingService.cs index eb8cedd9e..277065511 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 @@ namespace NzbDrone.Core.Housekeeping _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/Housekeeping/IHousekeepingTask.cs b/src/NzbDrone.Core/Housekeeping/IHousekeepingTask.cs index 2a69cfdc5..f2e955782 100644 --- a/src/NzbDrone.Core/Housekeeping/IHousekeepingTask.cs +++ b/src/NzbDrone.Core/Housekeeping/IHousekeepingTask.cs @@ -4,4 +4,4 @@ namespace NzbDrone.Core.Housekeeping { void Clean(); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Http/CloudFlare/CloudFlareHttpInterceptor.cs b/src/NzbDrone.Core/Http/CloudFlare/CloudFlareHttpInterceptor.cs index e5590c63c..c5addc2c3 100644 --- a/src/NzbDrone.Core/Http/CloudFlare/CloudFlareHttpInterceptor.cs +++ b/src/NzbDrone.Core/Http/CloudFlare/CloudFlareHttpInterceptor.cs @@ -7,10 +7,9 @@ namespace NzbDrone.Core.Http.CloudFlare { public class CloudFlareHttpInterceptor : IHttpRequestInterceptor { - private readonly Logger _logger; - private const string _cloudFlareChallengeScript = "cdn-cgi/scripts/cf.challenge.js"; private static readonly Regex _cloudFlareRegex = new Regex(@"data-ray=""(?[\w-_]+)"".*?data-sitekey=""(?[\w-_]+)"".*?data-stoken=""(?[\w-_]+)""", RegexOptions.Compiled); + private readonly Logger _logger; public CloudFlareHttpInterceptor(Logger logger) { diff --git a/src/NzbDrone.Core/Http/HttpProxySettingsProvider.cs b/src/NzbDrone.Core/Http/HttpProxySettingsProvider.cs index 6e5a23e07..26c7d9341 100644 --- a/src/NzbDrone.Core/Http/HttpProxySettingsProvider.cs +++ b/src/NzbDrone.Core/Http/HttpProxySettingsProvider.cs @@ -21,7 +21,7 @@ namespace NzbDrone.Core.Http { return null; } - + var proxySettings = new HttpProxySettings(_configService.ProxyType, _configService.ProxyHostname, _configService.ProxyPort, diff --git a/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionExistsValidator.cs b/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionExistsValidator.cs index db2179493..7911eb713 100644 --- a/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionExistsValidator.cs +++ b/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionExistsValidator.cs @@ -14,9 +14,12 @@ namespace NzbDrone.Core.ImportLists.Exclusions protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } - return (!_importListExclusionService.All().Exists(s => s.ForeignId == context.PropertyValue.ToString())); + return !_importListExclusionService.All().Exists(s => s.ForeignId == context.PropertyValue.ToString()); } } } diff --git a/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionRepository.cs b/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionRepository.cs index d980b776f..1ec78cfaa 100644 --- a/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionRepository.cs +++ b/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionRepository.cs @@ -1,7 +1,7 @@ -using NzbDrone.Core.Datastore; -using NzbDrone.Core.Messaging.Events; using System.Collections.Generic; using System.Linq; +using NzbDrone.Core.Datastore; +using NzbDrone.Core.Messaging.Events; namespace NzbDrone.Core.ImportLists.Exclusions { diff --git a/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionService.cs b/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionService.cs index a91c837d8..f4b3de7e6 100644 --- a/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionService.cs +++ b/src/NzbDrone.Core/ImportLists/Exclusions/ImportListExclusionService.cs @@ -1,7 +1,7 @@ -using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Music.Events; using System.Collections.Generic; using System.Linq; +using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Music.Events; namespace NzbDrone.Core.ImportLists.Exclusions { diff --git a/src/NzbDrone.Core/ImportLists/FetchAndParseImportListService.cs b/src/NzbDrone.Core/ImportLists/FetchAndParseImportListService.cs index 98eec4ee2..9a7678313 100644 --- a/src/NzbDrone.Core/ImportLists/FetchAndParseImportListService.cs +++ b/src/NzbDrone.Core/ImportLists/FetchAndParseImportListService.cs @@ -1,11 +1,11 @@ +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.Common.Extensions; +using NzbDrone.Common.TPL; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.ImportLists { @@ -71,7 +71,7 @@ namespace NzbDrone.Core.ImportLists Task.WaitAll(taskList.ToArray()); - result = result.DistinctBy(r => new {r.Artist, r.Album}).ToList(); + result = result.DistinctBy(r => new { r.Artist, r.Album }).ToList(); _logger.Debug("Found {0} reports", result.Count); @@ -116,7 +116,6 @@ namespace NzbDrone.Core.ImportLists taskList.Add(task); - Task.WaitAll(taskList.ToArray()); result = result.DistinctBy(r => new { r.Artist, r.Album }).ToList(); diff --git a/src/NzbDrone.Core/ImportLists/HeadphonesImport/HeadphonesImport.cs b/src/NzbDrone.Core/ImportLists/HeadphonesImport/HeadphonesImport.cs index 6912858af..f587649b4 100644 --- a/src/NzbDrone.Core/ImportLists/HeadphonesImport/HeadphonesImport.cs +++ b/src/NzbDrone.Core/ImportLists/HeadphonesImport/HeadphonesImport.cs @@ -20,13 +20,12 @@ namespace NzbDrone.Core.ImportLists.HeadphonesImport public override IImportListRequestGenerator GetRequestGenerator() { - return new HeadphonesImportRequestGenerator { Settings = Settings}; + return new HeadphonesImportRequestGenerator { Settings = Settings }; } public override IParseImportListResponse GetParser() { return new HeadphonesImportParser(); } - } } diff --git a/src/NzbDrone.Core/ImportLists/HeadphonesImport/HeadphonesImportApi.cs b/src/NzbDrone.Core/ImportLists/HeadphonesImport/HeadphonesImportApi.cs index ce9d5341f..4436bad2d 100644 --- a/src/NzbDrone.Core/ImportLists/HeadphonesImport/HeadphonesImportApi.cs +++ b/src/NzbDrone.Core/ImportLists/HeadphonesImport/HeadphonesImportApi.cs @@ -1,4 +1,3 @@ - namespace NzbDrone.Core.ImportLists.HeadphonesImport { public class HeadphonesImportArtist diff --git a/src/NzbDrone.Core/ImportLists/HeadphonesImport/HeadphonesImportParser.cs b/src/NzbDrone.Core/ImportLists/HeadphonesImport/HeadphonesImportParser.cs index b490a6cbd..1fbe46530 100644 --- a/src/NzbDrone.Core/ImportLists/HeadphonesImport/HeadphonesImportParser.cs +++ b/src/NzbDrone.Core/ImportLists/HeadphonesImport/HeadphonesImportParser.cs @@ -1,10 +1,9 @@ -using Newtonsoft.Json; -using NzbDrone.Core.ImportLists.Exceptions; -using NzbDrone.Core.Parser.Model; using System.Collections.Generic; using System.Net; -using NLog; +using Newtonsoft.Json; using NzbDrone.Common.Extensions; +using NzbDrone.Core.ImportLists.Exceptions; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.ImportLists.HeadphonesImport { @@ -58,6 +57,5 @@ namespace NzbDrone.Core.ImportLists.HeadphonesImport return true; } - } } diff --git a/src/NzbDrone.Core/ImportLists/HeadphonesImport/HeadphonesImportRequestGenerator.cs b/src/NzbDrone.Core/ImportLists/HeadphonesImport/HeadphonesImportRequestGenerator.cs index 664c32273..6f851332f 100644 --- a/src/NzbDrone.Core/ImportLists/HeadphonesImport/HeadphonesImportRequestGenerator.cs +++ b/src/NzbDrone.Core/ImportLists/HeadphonesImport/HeadphonesImportRequestGenerator.cs @@ -29,6 +29,5 @@ namespace NzbDrone.Core.ImportLists.HeadphonesImport { yield return new ImportListRequest(string.Format("{0}/api?cmd=getIndex&apikey={1}", Settings.BaseUrl.TrimEnd('/'), Settings.ApiKey), HttpAccept.Json); } - } } diff --git a/src/NzbDrone.Core/ImportLists/HttpImportListBase.cs b/src/NzbDrone.Core/ImportLists/HttpImportListBase.cs index 98942d450..8907726e2 100644 --- a/src/NzbDrone.Core/ImportLists/HttpImportListBase.cs +++ b/src/NzbDrone.Core/ImportLists/HttpImportListBase.cs @@ -12,7 +12,6 @@ using NzbDrone.Core.ImportLists.Exceptions; using NzbDrone.Core.Indexers.Exceptions; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Core.ImportLists { @@ -22,7 +21,7 @@ namespace NzbDrone.Core.ImportLists protected const int MaxNumResultsPerQuery = 1000; protected readonly IHttpClient _httpClient; - + public bool SupportsPaging => PageSize > 0; public virtual int PageSize => 0; @@ -124,6 +123,7 @@ namespace NzbDrone.Core.ImportLists { _importListStatusService.RecordFailure(Definition.Id, TimeSpan.FromHours(1)); } + _logger.Warn("API Request Limit reached for {0}", this); } catch (HttpException ex) @@ -242,5 +242,4 @@ namespace NzbDrone.Core.ImportLists return null; } } - } diff --git a/src/NzbDrone.Core/ImportLists/IImportList.cs b/src/NzbDrone.Core/ImportLists/IImportList.cs index 5aad5bb9d..f9fde642b 100644 --- a/src/NzbDrone.Core/ImportLists/IImportList.cs +++ b/src/NzbDrone.Core/ImportLists/IImportList.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Core.ImportLists { diff --git a/src/NzbDrone.Core/ImportLists/ImportListBase.cs b/src/NzbDrone.Core/ImportLists/ImportListBase.cs index 36ae9a184..d92a6d66e 100644 --- a/src/NzbDrone.Core/ImportLists/ImportListBase.cs +++ b/src/NzbDrone.Core/ImportLists/ImportListBase.cs @@ -21,7 +21,7 @@ namespace NzbDrone.Core.ImportLists public abstract string Name { get; } - public abstract ImportListType ListType {get; } + public abstract ImportListType ListType { get; } public ImportListBase(IImportListStatusService importListStatusService, IConfigService configService, IParsingService parsingService, Logger logger) { @@ -53,7 +53,10 @@ namespace NzbDrone.Core.ImportLists 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; @@ -61,7 +64,7 @@ namespace NzbDrone.Core.ImportLists protected virtual IList CleanupListItems(IEnumerable releases) { - var result = releases.DistinctBy(r => new {r.Artist, r.Album}).ToList(); + var result = releases.DistinctBy(r => new { r.Artist, r.Album }).ToList(); result.ForEach(c => { diff --git a/src/NzbDrone.Core/ImportLists/ImportListStatus.cs b/src/NzbDrone.Core/ImportLists/ImportListStatus.cs index e58976744..139d2b97b 100644 --- a/src/NzbDrone.Core/ImportLists/ImportListStatus.cs +++ b/src/NzbDrone.Core/ImportLists/ImportListStatus.cs @@ -5,6 +5,6 @@ namespace NzbDrone.Core.ImportLists { public class ImportListStatus : ProviderStatusBase { - public ImportListItemInfo LastSyncListInfo { get; set; } + public ImportListItemInfo LastSyncListInfo { get; set; } } } diff --git a/src/NzbDrone.Core/ImportLists/ImportListStatusRepository.cs b/src/NzbDrone.Core/ImportLists/ImportListStatusRepository.cs index 8bf500a7a..24d052dcc 100644 --- a/src/NzbDrone.Core/ImportLists/ImportListStatusRepository.cs +++ b/src/NzbDrone.Core/ImportLists/ImportListStatusRepository.cs @@ -9,7 +9,6 @@ namespace NzbDrone.Core.ImportLists } public class ImportListStatusRepository : ProviderStatusRepository, IImportListStatusRepository - { public ImportListStatusRepository(IMainDatabase database, IEventAggregator eventAggregator) : base(database, eventAggregator) diff --git a/src/NzbDrone.Core/ImportLists/ImportListStatusService.cs b/src/NzbDrone.Core/ImportLists/ImportListStatusService.cs index 9898a3f78..362359dca 100644 --- a/src/NzbDrone.Core/ImportLists/ImportListStatusService.cs +++ b/src/NzbDrone.Core/ImportLists/ImportListStatusService.cs @@ -25,7 +25,6 @@ namespace NzbDrone.Core.ImportLists return GetProviderStatus(importListId).LastSyncListInfo; } - public void UpdateListSyncStatus(int importListId, ImportListItemInfo listItemInfo) { lock (_syncRoot) diff --git a/src/NzbDrone.Core/ImportLists/ImportListSyncService.cs b/src/NzbDrone.Core/ImportLists/ImportListSyncService.cs index 03acd940e..2c018ae97 100644 --- a/src/NzbDrone.Core/ImportLists/ImportListSyncService.cs +++ b/src/NzbDrone.Core/ImportLists/ImportListSyncService.cs @@ -51,7 +51,6 @@ namespace NzbDrone.Core.ImportLists _logger = logger; } - private List SyncAll() { _logger.ProgressInfo("Starting Import List Sync"); @@ -61,7 +60,6 @@ namespace NzbDrone.Core.ImportLists var reports = rssReleases.ToList(); return ProcessReports(reports); - } private List SyncList(ImportListDefinition definition) @@ -73,7 +71,6 @@ namespace NzbDrone.Core.ImportLists var reports = rssReleases.ToList(); return ProcessReports(reports); - } private List ProcessReports(List reports) @@ -184,26 +181,25 @@ namespace NzbDrone.Core.ImportLists var monitored = importList.ShouldMonitor != ImportListMonitorType.None; albumsToAdd.Add(new Album + { + ForeignAlbumId = report.AlbumMusicBrainzId, + Monitored = monitored, + Artist = new Artist { - ForeignAlbumId = report.AlbumMusicBrainzId, Monitored = monitored, - Artist = new Artist + RootFolderPath = importList.RootFolderPath, + QualityProfileId = importList.ProfileId, + MetadataProfileId = importList.MetadataProfileId, + Tags = importList.Tags, + AlbumFolder = true, + AddOptions = new AddArtistOptions { + SearchForMissingAlbums = monitored, Monitored = monitored, - RootFolderPath = importList.RootFolderPath, - QualityProfileId = importList.ProfileId, - MetadataProfileId = importList.MetadataProfileId, - Tags = importList.Tags, - AlbumFolder = true, - AddOptions = new AddArtistOptions - { - SearchForMissingAlbums = monitored, - Monitored = monitored, - Monitor = monitored ? MonitorTypes.All : MonitorTypes.None - } - }, - - }); + Monitor = monitored ? MonitorTypes.All : MonitorTypes.None + } + }, + }); } } @@ -246,25 +242,25 @@ namespace NzbDrone.Core.ImportLists var monitored = importList.ShouldMonitor != ImportListMonitorType.None; artistsToAdd.Add(new Artist + { + Metadata = new ArtistMetadata { - Metadata = new ArtistMetadata - { - ForeignArtistId = report.ArtistMusicBrainzId, - Name = report.Artist - }, + ForeignArtistId = report.ArtistMusicBrainzId, + Name = report.Artist + }, + Monitored = monitored, + RootFolderPath = importList.RootFolderPath, + QualityProfileId = importList.ProfileId, + MetadataProfileId = importList.MetadataProfileId, + Tags = importList.Tags, + AlbumFolder = true, + AddOptions = new AddArtistOptions + { + SearchForMissingAlbums = monitored, Monitored = monitored, - RootFolderPath = importList.RootFolderPath, - QualityProfileId = importList.ProfileId, - MetadataProfileId = importList.MetadataProfileId, - Tags = importList.Tags, - AlbumFolder = true, - AddOptions = new AddArtistOptions - { - SearchForMissingAlbums = monitored, - Monitored = monitored, - Monitor = monitored ? MonitorTypes.All : MonitorTypes.None - } - }); + Monitor = monitored ? MonitorTypes.All : MonitorTypes.None + } + }); } } diff --git a/src/NzbDrone.Core/ImportLists/ImportListType.cs b/src/NzbDrone.Core/ImportLists/ImportListType.cs index 556255095..36aa04376 100644 --- a/src/NzbDrone.Core/ImportLists/ImportListType.cs +++ b/src/NzbDrone.Core/ImportLists/ImportListType.cs @@ -1,9 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - namespace NzbDrone.Core.ImportLists { public enum ImportListType diff --git a/src/NzbDrone.Core/ImportLists/LastFm/LastFmParser.cs b/src/NzbDrone.Core/ImportLists/LastFm/LastFmParser.cs index 333dd71c8..fa60b0fae 100644 --- a/src/NzbDrone.Core/ImportLists/LastFm/LastFmParser.cs +++ b/src/NzbDrone.Core/ImportLists/LastFm/LastFmParser.cs @@ -1,10 +1,9 @@ -using NzbDrone.Core.ImportLists.Exceptions; -using NzbDrone.Core.Parser.Model; using System.Collections.Generic; using System.Net; -using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Common.Serializer; +using NzbDrone.Core.ImportLists.Exceptions; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.ImportLists.LastFm { @@ -57,6 +56,5 @@ namespace NzbDrone.Core.ImportLists.LastFm return true; } - } } diff --git a/src/NzbDrone.Core/ImportLists/LastFm/LastFmTag.cs b/src/NzbDrone.Core/ImportLists/LastFm/LastFmTag.cs index 0d2da6c61..727c3d1dc 100644 --- a/src/NzbDrone.Core/ImportLists/LastFm/LastFmTag.cs +++ b/src/NzbDrone.Core/ImportLists/LastFm/LastFmTag.cs @@ -20,13 +20,12 @@ namespace NzbDrone.Core.ImportLists.LastFm public override IImportListRequestGenerator GetRequestGenerator() { - return new LastFmTagRequestGenerator { Settings = Settings}; + return new LastFmTagRequestGenerator { Settings = Settings }; } public override IParseImportListResponse GetParser() { return new LastFmParser(); } - } } diff --git a/src/NzbDrone.Core/ImportLists/LastFm/LastFmTagRequestGenerator.cs b/src/NzbDrone.Core/ImportLists/LastFm/LastFmTagRequestGenerator.cs index 9c7d03ee9..bfd662984 100644 --- a/src/NzbDrone.Core/ImportLists/LastFm/LastFmTagRequestGenerator.cs +++ b/src/NzbDrone.Core/ImportLists/LastFm/LastFmTagRequestGenerator.cs @@ -29,6 +29,5 @@ namespace NzbDrone.Core.ImportLists.LastFm { yield return new ImportListRequest(string.Format("{0}&tag={1}&limit={2}&api_key={3}&format=json", Settings.BaseUrl.TrimEnd('/'), Settings.TagId, Settings.Count, Settings.ApiKey), HttpAccept.Json); } - } } diff --git a/src/NzbDrone.Core/ImportLists/LastFm/LastFmUser.cs b/src/NzbDrone.Core/ImportLists/LastFm/LastFmUser.cs index 2e944c142..884062aa7 100644 --- a/src/NzbDrone.Core/ImportLists/LastFm/LastFmUser.cs +++ b/src/NzbDrone.Core/ImportLists/LastFm/LastFmUser.cs @@ -20,13 +20,12 @@ namespace NzbDrone.Core.ImportLists.LastFm public override IImportListRequestGenerator GetRequestGenerator() { - return new LastFmUserRequestGenerator { Settings = Settings}; + return new LastFmUserRequestGenerator { Settings = Settings }; } public override IParseImportListResponse GetParser() { return new LastFmParser(); } - } } diff --git a/src/NzbDrone.Core/ImportLists/LastFm/LastFmUserRequestGenerator.cs b/src/NzbDrone.Core/ImportLists/LastFm/LastFmUserRequestGenerator.cs index 97d541a22..5bdfb7a07 100644 --- a/src/NzbDrone.Core/ImportLists/LastFm/LastFmUserRequestGenerator.cs +++ b/src/NzbDrone.Core/ImportLists/LastFm/LastFmUserRequestGenerator.cs @@ -29,6 +29,5 @@ namespace NzbDrone.Core.ImportLists.LastFm { yield return new ImportListRequest(string.Format("{0}&user={1}&limit={2}&api_key={3}&format=json", Settings.BaseUrl.TrimEnd('/'), Settings.UserId, Settings.Count, Settings.ApiKey), HttpAccept.Json); } - } } diff --git a/src/NzbDrone.Core/ImportLists/LidarrLists/LidarrLists.cs b/src/NzbDrone.Core/ImportLists/LidarrLists/LidarrLists.cs index fb14fb1a2..052c39fec 100644 --- a/src/NzbDrone.Core/ImportLists/LidarrLists/LidarrLists.cs +++ b/src/NzbDrone.Core/ImportLists/LidarrLists/LidarrLists.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; 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.ImportLists.LidarrLists { @@ -65,6 +65,5 @@ namespace NzbDrone.Core.ImportLists.LidarrLists { return new LidarrListsParser(Settings); } - } } diff --git a/src/NzbDrone.Core/ImportLists/LidarrLists/LidarrListsParser.cs b/src/NzbDrone.Core/ImportLists/LidarrLists/LidarrListsParser.cs index 42a1b48ae..f2fbc3e3e 100644 --- a/src/NzbDrone.Core/ImportLists/LidarrLists/LidarrListsParser.cs +++ b/src/NzbDrone.Core/ImportLists/LidarrLists/LidarrListsParser.cs @@ -1,10 +1,9 @@ -using Newtonsoft.Json; -using NzbDrone.Core.ImportLists.Exceptions; -using NzbDrone.Core.Parser.Model; using System.Collections.Generic; using System.Net; -using NLog; +using Newtonsoft.Json; using NzbDrone.Common.Extensions; +using NzbDrone.Core.ImportLists.Exceptions; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.ImportLists.LidarrLists { @@ -67,6 +66,5 @@ namespace NzbDrone.Core.ImportLists.LidarrLists return true; } - } } diff --git a/src/NzbDrone.Core/ImportLists/Spotify/SpotifyException.cs b/src/NzbDrone.Core/ImportLists/Spotify/SpotifyException.cs index 9f2125a36..a9aae6894 100644 --- a/src/NzbDrone.Core/ImportLists/Spotify/SpotifyException.cs +++ b/src/NzbDrone.Core/ImportLists/Spotify/SpotifyException.cs @@ -5,22 +5,26 @@ namespace NzbDrone.Core.ImportLists.Spotify { public class SpotifyException : NzbDroneException { - public SpotifyException(string message) : base(message) + public SpotifyException(string message) + : base(message) { } - public SpotifyException(string message, params object[] args) : base(message, args) + public SpotifyException(string message, params object[] args) + : base(message, args) { } - public SpotifyException(string message, Exception innerException) : base(message, innerException) + public SpotifyException(string message, Exception innerException) + : base(message, innerException) { } } public class SpotifyAuthorizationException : SpotifyException { - public SpotifyAuthorizationException(string message) : base(message) + public SpotifyAuthorizationException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/ImportLists/Spotify/SpotifyFollowedArtists.cs b/src/NzbDrone.Core/ImportLists/Spotify/SpotifyFollowedArtists.cs index 5c75640ae..414c05d67 100644 --- a/src/NzbDrone.Core/ImportLists/Spotify/SpotifyFollowedArtists.cs +++ b/src/NzbDrone.Core/ImportLists/Spotify/SpotifyFollowedArtists.cs @@ -5,7 +5,6 @@ using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.MetadataSource; using NzbDrone.Core.Parser; -using NzbDrone.Core.Parser.Model; using SpotifyAPI.Web; using SpotifyAPI.Web.Models; diff --git a/src/NzbDrone.Core/ImportLists/Spotify/SpotifyImportListBase.cs b/src/NzbDrone.Core/ImportLists/Spotify/SpotifyImportListBase.cs index 8390179a6..f852acb1d 100644 --- a/src/NzbDrone.Core/ImportLists/Spotify/SpotifyImportListBase.cs +++ b/src/NzbDrone.Core/ImportLists/Spotify/SpotifyImportListBase.cs @@ -79,9 +79,8 @@ namespace NzbDrone.Core.ImportLists.Spotify { _logger.Warn($"Error refreshing spotify access token"); } - } - + public SpotifyWebAPI GetApi() { Settings.Validate().Filter("AccessToken", "RefreshToken").ThrowOnError(); @@ -122,10 +121,11 @@ namespace NzbDrone.Core.ImportLists.Spotify { return default(DateTime); } - + string format; - - switch (precision) { + + switch (precision) + { case "year": format = "yyyy"; break; @@ -333,13 +333,15 @@ namespace NzbDrone.Core.ImportLists.Spotify .AddQueryParam("show_dialog", true) .Build(); - return new { + return new + { OauthUrl = request.Url.ToString() }; } else if (action == "getOAuthToken") { - return new { + return new + { accessToken = query["access_token"], expires = DateTime.UtcNow.AddSeconds(int.Parse(query["expires_in"])), refreshToken = query["refresh_token"], diff --git a/src/NzbDrone.Core/ImportLists/Spotify/SpotifyPlaylist.cs b/src/NzbDrone.Core/ImportLists/Spotify/SpotifyPlaylist.cs index 3c1b80761..54bc232f0 100644 --- a/src/NzbDrone.Core/ImportLists/Spotify/SpotifyPlaylist.cs +++ b/src/NzbDrone.Core/ImportLists/Spotify/SpotifyPlaylist.cs @@ -53,7 +53,7 @@ namespace NzbDrone.Core.ImportLists.Spotify { result.AddIfNotNull(ParsePlaylistTrack(playlistTrack)); } - + if (!playlistTracks.HasNextPage()) { break; @@ -97,9 +97,9 @@ namespace NzbDrone.Core.ImportLists.Spotify if (Settings.AccessToken.IsNullOrWhiteSpace()) { return new - { - playlists = new List() - }; + { + playlists = new List() + }; } Settings.Validate().Filter("AccessToken").ThrowOnError(); @@ -131,17 +131,18 @@ namespace NzbDrone.Core.ImportLists.Spotify } return new + { + options = new { - options = new { - user = profile.DisplayName, - playlists = playlists.OrderBy(p => p.Name) + user = profile.DisplayName, + playlists = playlists.OrderBy(p => p.Name) .Select(p => new - { - id = p.Id, - name = p.Name - }) - } - }; + { + id = p.Id, + name = p.Name + }) + } + }; } catch (Exception ex) { diff --git a/src/NzbDrone.Core/ImportLists/Spotify/SpotifySavedAlbums.cs b/src/NzbDrone.Core/ImportLists/Spotify/SpotifySavedAlbums.cs index 91bb3e869..2d9004328 100644 --- a/src/NzbDrone.Core/ImportLists/Spotify/SpotifySavedAlbums.cs +++ b/src/NzbDrone.Core/ImportLists/Spotify/SpotifySavedAlbums.cs @@ -6,7 +6,6 @@ using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.MetadataSource; using NzbDrone.Core.Parser; -using NzbDrone.Core.Parser.Model; using SpotifyAPI.Web; using SpotifyAPI.Web.Models; diff --git a/src/NzbDrone.Core/IndexerSearch/AlbumSearchService.cs b/src/NzbDrone.Core/IndexerSearch/AlbumSearchService.cs index 345c9f1d3..34ee40e29 100644 --- a/src/NzbDrone.Core/IndexerSearch/AlbumSearchService.cs +++ b/src/NzbDrone.Core/IndexerSearch/AlbumSearchService.cs @@ -3,18 +3,17 @@ using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using NLog; -using NzbDrone.Common.Extensions; 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.Queue; using NzbDrone.Core.Music; +using NzbDrone.Core.Queue; namespace NzbDrone.Core.IndexerSearch { - class AlbumSearchService : IExecute, + internal class AlbumSearchService : IExecute, IExecute, IExecute { @@ -57,7 +56,6 @@ namespace NzbDrone.Core.IndexerSearch _logger.ProgressInfo("Completed missing search for {0} albums. {1} reports downloaded.", albums.Count, downloadedCount); } - public void Execute(AlbumSearchCommand message) { foreach (var albumId in message.AlbumIds) @@ -89,9 +87,7 @@ namespace NzbDrone.Core.IndexerSearch pagingSpec.FilterExpressions.Add(v => v.Monitored == true && v.Artist.Value.Monitored == true); albums = _albumService.AlbumsWithoutFiles(pagingSpec).Records.Where(e => e.ArtistId.Equals(artistId)).ToList(); - } - else { var pagingSpec = new PagingSpec @@ -105,7 +101,6 @@ namespace NzbDrone.Core.IndexerSearch pagingSpec.FilterExpressions.Add(v => v.Monitored == true && v.Artist.Value.Monitored == true); albums = _albumService.AlbumsWithoutFiles(pagingSpec).Records.ToList(); - } var queue = _queueService.GetQueue().Where(q => q.Album != null).Select(q => q.Album.Id); diff --git a/src/NzbDrone.Core/IndexerSearch/Definitions/ArtistSearchCriteria.cs b/src/NzbDrone.Core/IndexerSearch/Definitions/ArtistSearchCriteria.cs index 6de6dd3b1..4fa786200 100644 --- a/src/NzbDrone.Core/IndexerSearch/Definitions/ArtistSearchCriteria.cs +++ b/src/NzbDrone.Core/IndexerSearch/Definitions/ArtistSearchCriteria.cs @@ -1,6 +1,4 @@ -using System; - -namespace NzbDrone.Core.IndexerSearch.Definitions +namespace NzbDrone.Core.IndexerSearch.Definitions { public class ArtistSearchCriteria : SearchCriteriaBase { diff --git a/src/NzbDrone.Core/IndexerSearch/Definitions/SearchCriteriaBase.cs b/src/NzbDrone.Core/IndexerSearch/Definitions/SearchCriteriaBase.cs index 57b939fd1..6373d3314 100644 --- a/src/NzbDrone.Core/IndexerSearch/Definitions/SearchCriteriaBase.cs +++ b/src/NzbDrone.Core/IndexerSearch/Definitions/SearchCriteriaBase.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; -using System.Linq; using System.Text.RegularExpressions; using NzbDrone.Common.EnsureThat; using NzbDrone.Common.Extensions; @@ -25,7 +24,7 @@ namespace NzbDrone.Core.IndexerSearch.Definitions 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/NzbSearchService.cs b/src/NzbDrone.Core/IndexerSearch/NzbSearchService.cs index c1ce05294..21005ad36 100644 --- a/src/NzbDrone.Core/IndexerSearch/NzbSearchService.cs +++ b/src/NzbDrone.Core/IndexerSearch/NzbSearchService.cs @@ -1,17 +1,16 @@ using System; using System.Collections.Generic; -using System.Globalization; +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 System.Linq; using NzbDrone.Common.Extensions; +using NzbDrone.Common.Instrumentation.Extensions; using NzbDrone.Common.TPL; +using NzbDrone.Core.DecisionEngine; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.Music; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.IndexerSearch { @@ -62,7 +61,7 @@ namespace NzbDrone.Core.IndexerSearch albums = albums.Where(a => a.Monitored).ToList(); searchSpec.Albums = albums; - + return Dispatch(indexer => indexer.Fetch(searchSpec), searchSpec); } @@ -86,7 +85,8 @@ namespace NzbDrone.Core.IndexerSearch return Dispatch(indexer => indexer.Fetch(searchSpec), searchSpec); } - private TSpec Get(Artist artist, List albums, bool userInvokedSearch, bool interactiveSearch) where TSpec : SearchCriteriaBase, new() + private TSpec Get(Artist artist, List albums, bool userInvokedSearch, bool interactiveSearch) + where TSpec : SearchCriteriaBase, new() { var spec = new TSpec(); @@ -98,7 +98,8 @@ namespace NzbDrone.Core.IndexerSearch return spec; } - private static TSpec Get(Artist artist, bool userInvokedSearch, bool interactiveSearch) where TSpec : SearchCriteriaBase, new() + private static TSpec Get(Artist artist, bool userInvokedSearch, bool interactiveSearch) + where TSpec : SearchCriteriaBase, new() { var spec = new TSpec(); spec.Artist = artist; diff --git a/src/NzbDrone.Core/Indexers/Exceptions/ApiKeyException.cs b/src/NzbDrone.Core/Indexers/Exceptions/ApiKeyException.cs index 41d0d4d5e..eb4e26654 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 6fe085dd4..08e5d72f4 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 6e23f1917..460f63e13 100644 --- a/src/NzbDrone.Core/Indexers/FetchAndParseRssService.cs +++ b/src/NzbDrone.Core/Indexers/FetchAndParseRssService.cs @@ -1,10 +1,10 @@ +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/Gazelle/Gazelle.cs b/src/NzbDrone.Core/Indexers/Gazelle/Gazelle.cs index fa1d0c7a5..1bcd5a000 100644 --- a/src/NzbDrone.Core/Indexers/Gazelle/Gazelle.cs +++ b/src/NzbDrone.Core/Indexers/Gazelle/Gazelle.cs @@ -1,13 +1,11 @@ +using System.Collections.Generic; +using FluentValidation.Results; using NLog; using NzbDrone.Common.Cache; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.Parser; using NzbDrone.Core.ThingiProvider; -using System.Collections.Generic; -using System.Linq; -using FluentValidation.Results; -using NzbDrone.Common.Extensions; namespace NzbDrone.Core.Indexers.Gazelle { @@ -21,8 +19,12 @@ namespace NzbDrone.Core.Indexers.Gazelle private readonly ICached> _authCookieCache; - public Gazelle(IHttpClient httpClient, ICacheManager cacheManager, IIndexerStatusService indexerStatusService, - IConfigService configService, IParsingService parsingService, Logger logger) + public Gazelle(IHttpClient httpClient, + ICacheManager cacheManager, + IIndexerStatusService indexerStatusService, + IConfigService configService, + IParsingService parsingService, + Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { _authCookieCache = cacheManager.GetCache>(GetType(), "authCookies"); @@ -51,7 +53,6 @@ namespace NzbDrone.Core.Indexers.Gazelle yield return GetDefinition("Orpheus Network", GetSettings("https://orpheus.network")); yield return GetDefinition("REDacted", GetSettings("https://redacted.ch")); yield return GetDefinition("Not What CD", GetSettings("https://notwhat.cd")); - } } diff --git a/src/NzbDrone.Core/Indexers/Gazelle/GazelleApi.cs b/src/NzbDrone.Core/Indexers/Gazelle/GazelleApi.cs index a12532907..a9bc5386a 100644 --- a/src/NzbDrone.Core/Indexers/Gazelle/GazelleApi.cs +++ b/src/NzbDrone.Core/Indexers/Gazelle/GazelleApi.cs @@ -72,7 +72,6 @@ namespace NzbDrone.Core.Indexers.Gazelle { public string Status { get; set; } public GazelleIndexResponse Response { get; set; } - } public class GazelleIndexResponse @@ -81,7 +80,5 @@ namespace NzbDrone.Core.Indexers.Gazelle public string Id { get; set; } public string Authkey { get; set; } public string Passkey { get; set; } - } - } diff --git a/src/NzbDrone.Core/Indexers/Gazelle/GazelleInfo.cs b/src/NzbDrone.Core/Indexers/Gazelle/GazelleInfo.cs index 84915f605..2f694c47f 100644 --- a/src/NzbDrone.Core/Indexers/Gazelle/GazelleInfo.cs +++ b/src/NzbDrone.Core/Indexers/Gazelle/GazelleInfo.cs @@ -1,8 +1,4 @@ using NzbDrone.Core.Parser.Model; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace NzbDrone.Core.Indexers.Gazelle { diff --git a/src/NzbDrone.Core/Indexers/Gazelle/GazelleParser.cs b/src/NzbDrone.Core/Indexers/Gazelle/GazelleParser.cs index 62f0b3e2a..df3cdbf9d 100644 --- a/src/NzbDrone.Core/Indexers/Gazelle/GazelleParser.cs +++ b/src/NzbDrone.Core/Indexers/Gazelle/GazelleParser.cs @@ -1,11 +1,11 @@ using System.Collections.Generic; +using System.Linq; using System.Net; +using NzbDrone.Common.Cache; +using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Indexers.Exceptions; using NzbDrone.Core.Parser.Model; -using System.Linq; -using NzbDrone.Common.Cache; -using NzbDrone.Common.Extensions; namespace NzbDrone.Core.Indexers.Gazelle { @@ -47,7 +47,6 @@ namespace NzbDrone.Core.Indexers.Gazelle return torrentInfos; } - foreach (var result in jsonResponse.Resource.Response.Results) { if (result.Torrents != null) @@ -62,8 +61,9 @@ namespace NzbDrone.Core.Indexers.Gazelle { Guid = string.Format("Gazelle-{0}", id), Artist = artist, + // Splice Title from info to avoid calling API again for every torrent. - Title = WebUtility.HtmlDecode(result.Artist + " - " + result.GroupName + " (" + result.GroupYear +") [" + torrent.Format + " " + torrent.Encoding + "]"), + Title = WebUtility.HtmlDecode(result.Artist + " - " + result.GroupName + " (" + result.GroupYear + ") [" + torrent.Format + " " + torrent.Encoding + "]"), Album = album, Container = torrent.Encoding, Codec = torrent.Format, @@ -80,12 +80,12 @@ namespace NzbDrone.Core.Indexers.Gazelle } var torr = torrentInfos; + // order by date return torrentInfos .OrderByDescending(o => o.PublishDate) .ToArray(); - } private string GetDownloadUrl(int torrentId, string authKey, string passKey) diff --git a/src/NzbDrone.Core/Indexers/Gazelle/GazelleRequestGenerator.cs b/src/NzbDrone.Core/Indexers/Gazelle/GazelleRequestGenerator.cs index 3e226dc54..0f15e1484 100644 --- a/src/NzbDrone.Core/Indexers/Gazelle/GazelleRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/Gazelle/GazelleRequestGenerator.cs @@ -1,17 +1,16 @@ using System; using System.Collections.Generic; -using NzbDrone.Common.Http; -using NzbDrone.Core.IndexerSearch.Definitions; -using NzbDrone.Common.Cache; using NLog; +using NzbDrone.Common.Cache; using NzbDrone.Common.Extensions; +using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; +using NzbDrone.Core.IndexerSearch.Definitions; namespace NzbDrone.Core.Indexers.Gazelle { public class GazelleRequestGenerator : IIndexerRequestGenerator { - public GazelleSettings Settings { get; set; } public ICached> AuthCookieCache { get; set; } @@ -37,7 +36,7 @@ namespace NzbDrone.Core.Indexers.Gazelle public IndexerPageableRequestChain GetSearchRequests(ArtistSearchCriteria searchCriteria) { var pageableRequests = new IndexerPageableRequestChain(); - pageableRequests.Add(GetRequest(string.Format("&artistname={0}",searchCriteria.ArtistQuery))); + pageableRequests.Add(GetRequest(string.Format("&artistname={0}", searchCriteria.ArtistQuery))); return pageableRequests; } @@ -48,7 +47,6 @@ namespace NzbDrone.Core.Indexers.Gazelle var filter = ""; if (searchParameters == null) { - } var request = @@ -65,7 +63,7 @@ namespace NzbDrone.Core.Indexers.Gazelle yield return request; } - private GazelleAuthResponse GetIndex(Dictionary cookies) + private GazelleAuthResponse GetIndex(Dictionary cookies) { var indexRequestBuilder = new HttpRequestBuilder($"{Settings.BaseUrl.Trim().TrimEnd('/')}") { @@ -89,7 +87,6 @@ namespace NzbDrone.Core.Indexers.Gazelle private void Authenticate() { - var requestBuilder = new HttpRequestBuilder($"{Settings.BaseUrl.Trim().TrimEnd('/')}") { LogResponseContent = true @@ -133,7 +130,6 @@ namespace NzbDrone.Core.Indexers.Gazelle Settings.AuthKey = index.Response.Authkey; Settings.PassKey = index.Response.Passkey; - - } + } } } diff --git a/src/NzbDrone.Core/Indexers/Headphones/Headphones.cs b/src/NzbDrone.Core/Indexers/Headphones/Headphones.cs index 14b5abab8..eb2c1fc63 100644 --- a/src/NzbDrone.Core/Indexers/Headphones/Headphones.cs +++ b/src/NzbDrone.Core/Indexers/Headphones/Headphones.cs @@ -7,7 +7,6 @@ using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.Parser; -using NzbDrone.Core.Indexers.Newznab; namespace NzbDrone.Core.Indexers.Headphones { @@ -48,7 +47,11 @@ namespace NzbDrone.Core.Indexers.Headphones { base.Test(failures); - if (failures.Any()) return; + if (failures.Any()) + { + return; + } + failures.AddIfNotNull(TestCapabilities()); } diff --git a/src/NzbDrone.Core/Indexers/Headphones/HeadphonesCapabilitiesProvider.cs b/src/NzbDrone.Core/Indexers/Headphones/HeadphonesCapabilitiesProvider.cs index 9ac5b8941..95155a710 100644 --- a/src/NzbDrone.Core/Indexers/Headphones/HeadphonesCapabilitiesProvider.cs +++ b/src/NzbDrone.Core/Indexers/Headphones/HeadphonesCapabilitiesProvider.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Net; using System.Xml; using System.Xml.Linq; using NLog; @@ -142,7 +141,6 @@ namespace NzbDrone.Core.Indexers.Headphones 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/Headphones/HeadphonesRequestGenerator.cs b/src/NzbDrone.Core/Indexers/Headphones/HeadphonesRequestGenerator.cs index 7e7a124c6..348c29243 100644 --- a/src/NzbDrone.Core/Indexers/Headphones/HeadphonesRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/Headphones/HeadphonesRequestGenerator.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using NzbDrone.Common.Extensions; @@ -35,10 +34,12 @@ namespace NzbDrone.Core.Indexers.Headphones { var pageableRequests = new IndexerPageableRequestChain(); - pageableRequests.AddTier(); + pageableRequests.AddTier(); - pageableRequests.Add(GetPagedRequests(MaxPages, Settings.Categories, "search", - NewsnabifyTitle($"&q={searchCriteria.ArtistQuery}+{searchCriteria.AlbumQuery}"))); + pageableRequests.Add(GetPagedRequests(MaxPages, + Settings.Categories, + "search", + NewsnabifyTitle($"&q={searchCriteria.ArtistQuery}+{searchCriteria.AlbumQuery}"))); return pageableRequests; } @@ -49,7 +50,9 @@ namespace NzbDrone.Core.Indexers.Headphones pageableRequests.AddTier(); - pageableRequests.Add(GetPagedRequests(MaxPages, Settings.Categories, "search", + pageableRequests.Add(GetPagedRequests(MaxPages, + Settings.Categories, + "search", NewsnabifyTitle($"&q={searchCriteria.ArtistQuery}"))); return pageableRequests; diff --git a/src/NzbDrone.Core/Indexers/Headphones/HeadphonesRssParser.cs b/src/NzbDrone.Core/Indexers/Headphones/HeadphonesRssParser.cs index abdc9961b..9ee7cff5d 100644 --- a/src/NzbDrone.Core/Indexers/Headphones/HeadphonesRssParser.cs +++ b/src/NzbDrone.Core/Indexers/Headphones/HeadphonesRssParser.cs @@ -16,7 +16,7 @@ namespace NzbDrone.Core.Indexers.Headphones protected override string GetBasicAuth() { - return Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes($"{Settings.Username}:{Settings.Password}")); ; + return Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes($"{Settings.Username}:{Settings.Password}")); } } } diff --git a/src/NzbDrone.Core/Indexers/Headphones/HeadphonesSettings.cs b/src/NzbDrone.Core/Indexers/Headphones/HeadphonesSettings.cs index be9fae97b..5296f6ec7 100644 --- a/src/NzbDrone.Core/Indexers/Headphones/HeadphonesSettings.cs +++ b/src/NzbDrone.Core/Indexers/Headphones/HeadphonesSettings.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using FluentValidation; -using FluentValidation.Results; using NzbDrone.Common.Extensions; using NzbDrone.Core.Annotations; using NzbDrone.Core.Validation; diff --git a/src/NzbDrone.Core/Indexers/HttpIndexerBase.cs b/src/NzbDrone.Core/Indexers/HttpIndexerBase.cs index 3bd8163f3..d7d04acbb 100644 --- a/src/NzbDrone.Core/Indexers/HttpIndexerBase.cs +++ b/src/NzbDrone.Core/Indexers/HttpIndexerBase.cs @@ -12,7 +12,6 @@ using NzbDrone.Core.Indexers.Exceptions; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Core.Indexers { @@ -81,7 +80,6 @@ namespace NzbDrone.Core.Indexers var pageableRequestChain = pageableRequestChainSelector(generator); - var fullyUpdated = false; ReleaseInfo lastReleaseInfo = null; if (isRecent) @@ -112,6 +110,7 @@ namespace NzbDrone.Core.Indexers fullyUpdated = true; break; } + var oldestReleaseDate = page.Select(v => v.PublishDate).Min(); if (oldestReleaseDate < lastReleaseInfo.PublishDate || page.Any(v => v.DownloadUrl == lastReleaseInfo.DownloadUrl)) { @@ -156,6 +155,7 @@ namespace NzbDrone.Core.Indexers var gapEnd = ordered.Last().PublishDate; _logger.Warn("Indexer {0} rss sync didn't cover the period between {1} and {2} UTC. Search may be required.", Definition.Name, gapStart, gapEnd); } + lastReleaseInfo = ordered.First(); _indexerStatusService.UpdateRssSyncStatus(Definition.Id, lastReleaseInfo); } @@ -194,6 +194,7 @@ namespace NzbDrone.Core.Indexers { _indexerStatusService.RecordFailure(Definition.Id, TimeSpan.FromHours(1)); } + _logger.Warn("API Request Limit reached for {0}", this); } catch (HttpException ex) @@ -343,5 +344,4 @@ namespace NzbDrone.Core.Indexers return null; } } - } diff --git a/src/NzbDrone.Core/Indexers/IIndexer.cs b/src/NzbDrone.Core/Indexers/IIndexer.cs index 1a1e034f1..8e6847b8e 100644 --- a/src/NzbDrone.Core/Indexers/IIndexer.cs +++ b/src/NzbDrone.Core/Indexers/IIndexer.cs @@ -10,7 +10,7 @@ namespace NzbDrone.Core.Indexers bool SupportsRss { get; } bool SupportsSearch { get; } DownloadProtocol Protocol { get; } - + IList FetchRecent(); IList Fetch(AlbumSearchCriteria searchCriteria); IList Fetch(ArtistSearchCriteria searchCriteria); diff --git a/src/NzbDrone.Core/Indexers/IPTorrents/IPTorrents.cs b/src/NzbDrone.Core/Indexers/IPTorrents/IPTorrents.cs index a62926c10..6b74949ba 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 @@ namespace NzbDrone.Core.Indexers.IPTorrents public IPTorrents(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { - } public override IIndexerRequestGenerator GetRequestGenerator() @@ -29,4 +28,4 @@ namespace NzbDrone.Core.Indexers.IPTorrents return new TorrentRssParser() { ParseSizeInDescription = true }; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Indexers/IPTorrents/IPTorrentsRequestGenerator.cs b/src/NzbDrone.Core/Indexers/IPTorrents/IPTorrentsRequestGenerator.cs index b5d95dfb7..e18b46808 100644 --- a/src/NzbDrone.Core/Indexers/IPTorrents/IPTorrentsRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/IPTorrents/IPTorrentsRequestGenerator.cs @@ -7,7 +7,7 @@ namespace NzbDrone.Core.Indexers.IPTorrents public class IPTorrentsRequestGenerator : IIndexerRequestGenerator { public IPTorrentsSettings Settings { get; set; } - + public virtual IndexerPageableRequestChain GetRecentRequests() { var pageableRequests = new IndexerPageableRequestChain(); diff --git a/src/NzbDrone.Core/Indexers/IndexerBase.cs b/src/NzbDrone.Core/Indexers/IndexerBase.cs index 63726ccf1..feb5f5c27 100644 --- a/src/NzbDrone.Core/Indexers/IndexerBase.cs +++ b/src/NzbDrone.Core/Indexers/IndexerBase.cs @@ -58,7 +58,10 @@ namespace NzbDrone.Core.Indexers 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 b44cfaf76..1671ff1c1 100644 --- a/src/NzbDrone.Core/Indexers/IndexerPageableRequestChain.cs +++ b/src/NzbDrone.Core/Indexers/IndexerPageableRequestChain.cs @@ -27,7 +27,10 @@ namespace NzbDrone.Core.Indexers public void Add(IEnumerable request) { - if (request == null) return; + if (request == null) + { + return; + } _chains.Last().Add(new IndexerPageableRequest(request)); } @@ -40,9 +43,12 @@ namespace NzbDrone.Core.Indexers public void AddTier() { - if (_chains.Last().Count == 0) return; + if (_chains.Last().Count == 0) + { + return; + } _chains.Add(new List()); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Indexers/IndexerRepository.cs b/src/NzbDrone.Core/Indexers/IndexerRepository.cs index 50d07d66d..c4858f415 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/IndexerSettingUpdatedEvent.cs b/src/NzbDrone.Core/Indexers/IndexerSettingUpdatedEvent.cs index 783948b2e..299cef651 100644 --- a/src/NzbDrone.Core/Indexers/IndexerSettingUpdatedEvent.cs +++ b/src/NzbDrone.Core/Indexers/IndexerSettingUpdatedEvent.cs @@ -14,4 +14,4 @@ namespace NzbDrone.Core.Indexers IndexerSetting = indexerSetting; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Indexers/IndexerStatusRepository.cs b/src/NzbDrone.Core/Indexers/IndexerStatusRepository.cs index 02a656125..5df1f1523 100644 --- a/src/NzbDrone.Core/Indexers/IndexerStatusRepository.cs +++ b/src/NzbDrone.Core/Indexers/IndexerStatusRepository.cs @@ -2,7 +2,6 @@ using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.ThingiProvider.Status; - namespace NzbDrone.Core.Indexers { public interface IIndexerStatusRepository : IProviderStatusRepository @@ -10,7 +9,6 @@ namespace NzbDrone.Core.Indexers } public class IndexerStatusRepository : ProviderStatusRepository, IIndexerStatusRepository - { public IndexerStatusRepository(IMainDatabase database, IEventAggregator eventAggregator) : base(database, eventAggregator) diff --git a/src/NzbDrone.Core/Indexers/IndexerStatusService.cs b/src/NzbDrone.Core/Indexers/IndexerStatusService.cs index a681622f9..4e6de3d68 100644 --- a/src/NzbDrone.Core/Indexers/IndexerStatusService.cs +++ b/src/NzbDrone.Core/Indexers/IndexerStatusService.cs @@ -25,7 +25,6 @@ namespace NzbDrone.Core.Indexers return GetProviderStatus(indexerId).LastRssSyncReleaseInfo; } - public void UpdateRssSyncStatus(int indexerId, ReleaseInfo releaseInfo) { lock (_syncRoot) diff --git a/src/NzbDrone.Core/Indexers/Newznab/Newznab.cs b/src/NzbDrone.Core/Indexers/Newznab/Newznab.cs index 1cae12b92..c24c01782 100644 --- a/src/NzbDrone.Core/Indexers/Newznab/Newznab.cs +++ b/src/NzbDrone.Core/Indexers/Newznab/Newznab.cs @@ -64,17 +64,17 @@ namespace NzbDrone.Core.Indexers.Newznab 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, params int[] categories) @@ -92,7 +92,11 @@ namespace NzbDrone.Core.Indexers.Newznab protected override void Test(List failures) { base.Test(failures); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestCapabilities()); } diff --git a/src/NzbDrone.Core/Indexers/Newznab/NewznabCapabilitiesProvider.cs b/src/NzbDrone.Core/Indexers/Newznab/NewznabCapabilitiesProvider.cs index a9c8fd9c0..596ae4130 100644 --- a/src/NzbDrone.Core/Indexers/Newznab/NewznabCapabilitiesProvider.cs +++ b/src/NzbDrone.Core/Indexers/Newznab/NewznabCapabilitiesProvider.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Net; using System.Xml; using System.Xml.Linq; using NLog; @@ -160,7 +159,6 @@ namespace NzbDrone.Core.Indexers.Newznab 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 21f31e46f..f7f167b34 100644 --- a/src/NzbDrone.Core/Indexers/Newznab/NewznabRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/Newznab/NewznabRequestGenerator.cs @@ -69,7 +69,8 @@ namespace NzbDrone.Core.Indexers.Newznab if (SupportsAudioSearch) { - AddAudioPageableRequests(pageableRequests, searchCriteria, + AddAudioPageableRequests(pageableRequests, + searchCriteria, NewsnabifyTitle($"&artist={searchCriteria.ArtistQuery}&album={searchCriteria.AlbumQuery}")); } @@ -77,7 +78,9 @@ namespace NzbDrone.Core.Indexers.Newznab { pageableRequests.AddTier(); - pageableRequests.Add(GetPagedRequests(MaxPages, Settings.Categories, "search", + pageableRequests.Add(GetPagedRequests(MaxPages, + Settings.Categories, + "search", NewsnabifyTitle($"&q={searchCriteria.ArtistQuery}+{searchCriteria.AlbumQuery}"))); } @@ -90,7 +93,8 @@ namespace NzbDrone.Core.Indexers.Newznab if (SupportsAudioSearch) { - AddAudioPageableRequests(pageableRequests, searchCriteria, + AddAudioPageableRequests(pageableRequests, + searchCriteria, NewsnabifyTitle($"&artist={searchCriteria.ArtistQuery}")); } @@ -98,7 +102,9 @@ namespace NzbDrone.Core.Indexers.Newznab { pageableRequests.AddTier(); - pageableRequests.Add(GetPagedRequests(MaxPages, Settings.Categories, "search", + pageableRequests.Add(GetPagedRequests(MaxPages, + Settings.Categories, + "search", NewsnabifyTitle($"&q={searchCriteria.ArtistQuery}"))); } diff --git a/src/NzbDrone.Core/Indexers/Newznab/NewznabRssParser.cs b/src/NzbDrone.Core/Indexers/Newznab/NewznabRssParser.cs index b9f1efa54..0a1f15f65 100644 --- a/src/NzbDrone.Core/Indexers/Newznab/NewznabRssParser.cs +++ b/src/NzbDrone.Core/Indexers/Newznab/NewznabRssParser.cs @@ -23,7 +23,10 @@ namespace NzbDrone.Core.Indexers.Newznab 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; @@ -68,10 +71,10 @@ namespace NzbDrone.Core.Indexers.Newznab protected override ReleaseInfo ProcessItem(XElement item, ReleaseInfo releaseInfo) { releaseInfo = base.ProcessItem(item, releaseInfo); - + releaseInfo.Artist = GetArtist(item); releaseInfo.Album = GetAlbum(item); - + return releaseInfo; } @@ -122,7 +125,7 @@ namespace NzbDrone.Core.Indexers.Newznab return ""; } - + protected virtual string GetAlbum(XElement item) { var albumString = TryGetNewznabAttribute(item, "album"); diff --git a/src/NzbDrone.Core/Indexers/Newznab/NewznabSettings.cs b/src/NzbDrone.Core/Indexers/Newznab/NewznabSettings.cs index ee6149801..f9361cc5e 100644 --- a/src/NzbDrone.Core/Indexers/Newznab/NewznabSettings.cs +++ b/src/NzbDrone.Core/Indexers/Newznab/NewznabSettings.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using FluentValidation; -using FluentValidation.Results; using NzbDrone.Common.Extensions; using NzbDrone.Core.Annotations; using NzbDrone.Core.Validation; @@ -82,7 +81,6 @@ namespace NzbDrone.Core.Indexers.Newznab // Field 6 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 82d1a1c3d..d2d63cbf0 100644 --- a/src/NzbDrone.Core/Indexers/Nyaa/Nyaa.cs +++ b/src/NzbDrone.Core/Indexers/Nyaa/Nyaa.cs @@ -15,7 +15,6 @@ namespace NzbDrone.Core.Indexers.Nyaa public Nyaa(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { - } public override IIndexerRequestGenerator GetRequestGenerator() @@ -28,4 +27,4 @@ namespace NzbDrone.Core.Indexers.Nyaa return new TorrentRssParser() { UseGuidInfoUrl = true, ParseSizeInDescription = true, ParseSeedersInDescription = true }; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Indexers/Nyaa/NyaaSettings.cs b/src/NzbDrone.Core/Indexers/Nyaa/NyaaSettings.cs index 3bb640d4a..448f0fdab 100644 --- a/src/NzbDrone.Core/Indexers/Nyaa/NyaaSettings.cs +++ b/src/NzbDrone.Core/Indexers/Nyaa/NyaaSettings.cs @@ -1,7 +1,7 @@ +using System.Text.RegularExpressions; using FluentValidation; using NzbDrone.Core.Annotations; using NzbDrone.Core.Validation; -using System.Text.RegularExpressions; namespace NzbDrone.Core.Indexers.Nyaa { public class NyaaSettingsValidator : AbstractValidator diff --git a/src/NzbDrone.Core/Indexers/Omgwtfnzbs/Omgwtfnzbs.cs b/src/NzbDrone.Core/Indexers/Omgwtfnzbs/Omgwtfnzbs.cs index d957b5cbd..e4f1bb56b 100644 --- a/src/NzbDrone.Core/Indexers/Omgwtfnzbs/Omgwtfnzbs.cs +++ b/src/NzbDrone.Core/Indexers/Omgwtfnzbs/Omgwtfnzbs.cs @@ -14,7 +14,6 @@ namespace NzbDrone.Core.Indexers.Omgwtfnzbs 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/OmgwtfnzbsRequestGenerator.cs b/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsRequestGenerator.cs index 45a2a7414..80e73e276 100644 --- a/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsRequestGenerator.cs @@ -29,12 +29,10 @@ namespace NzbDrone.Core.Indexers.Omgwtfnzbs { var pageableRequests = new IndexerPageableRequestChain(); - pageableRequests.Add(GetPagedRequests(string.Format("{0}+{1}", searchCriteria.ArtistQuery, searchCriteria.AlbumQuery))); - return pageableRequests; } @@ -42,11 +40,9 @@ namespace NzbDrone.Core.Indexers.Omgwtfnzbs { var pageableRequests = new IndexerPageableRequestChain(); - pageableRequests.Add(GetPagedRequests(string.Format("{0}", searchCriteria.ArtistQuery))); - return pageableRequests; } diff --git a/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsRssParser.cs b/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsRssParser.cs index a5946e5ff..5ff9174e3 100644 --- a/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsRssParser.cs +++ b/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsRssParser.cs @@ -19,9 +19,15 @@ namespace NzbDrone.Core.Indexers.Omgwtfnzbs 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 @@ namespace NzbDrone.Core.Indexers.Omgwtfnzbs 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\.+)(?:\""\starget)", - RegexOptions.IgnoreCase | RegexOptions.Compiled); + var match = Regex.Match(item.Description(), + @"(?:\View NZB\:\<\/b\>\s\.+)(?:\""\starget)", + RegexOptions.IgnoreCase | RegexOptions.Compiled); if (match.Success) { @@ -40,4 +47,4 @@ namespace NzbDrone.Core.Indexers.Omgwtfnzbs return string.Empty; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsSettings.cs b/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsSettings.cs index f3ecaf102..58ab71791 100644 --- a/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsSettings.cs +++ b/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsSettings.cs @@ -1,6 +1,5 @@ using FluentValidation; using NzbDrone.Core.Annotations; -using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; namespace NzbDrone.Core.Indexers.Omgwtfnzbs diff --git a/src/NzbDrone.Core/Indexers/Rarbg/Rarbg.cs b/src/NzbDrone.Core/Indexers/Rarbg/Rarbg.cs index acf427eee..d9f423ae8 100644 --- a/src/NzbDrone.Core/Indexers/Rarbg/Rarbg.cs +++ b/src/NzbDrone.Core/Indexers/Rarbg/Rarbg.cs @@ -63,7 +63,7 @@ namespace NzbDrone.Core.Indexers.Rarbg siteKey = ex.CaptchaRequest.SiteKey, secretToken = ex.CaptchaRequest.SecretToken, responseUrl = ex.CaptchaRequest.ResponseUrl.FullUri, - } + } }; } @@ -110,4 +110,4 @@ namespace NzbDrone.Core.Indexers.Rarbg return new { }; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Indexers/Rarbg/RarbgParser.cs b/src/NzbDrone.Core/Indexers/Rarbg/RarbgParser.cs index 0ead72ac3..482d0c706 100644 --- a/src/NzbDrone.Core/Indexers/Rarbg/RarbgParser.cs +++ b/src/NzbDrone.Core/Indexers/Rarbg/RarbgParser.cs @@ -22,6 +22,7 @@ namespace NzbDrone.Core.Indexers.Rarbg { throw new IndexerException(indexerResponse, "Indexer API call returned an unexpected StatusCode [{0}]", indexerResponse.HttpResponse.StatusCode); } + break; } @@ -75,6 +76,5 @@ namespace NzbDrone.Core.Indexers.Rarbg return string.Format("rarbg-{0}", torrent.download); } } - } } diff --git a/src/NzbDrone.Core/Indexers/Rarbg/RarbgSettings.cs b/src/NzbDrone.Core/Indexers/Rarbg/RarbgSettings.cs index 003f1e79c..34fd23241 100644 --- a/src/NzbDrone.Core/Indexers/Rarbg/RarbgSettings.cs +++ b/src/NzbDrone.Core/Indexers/Rarbg/RarbgSettings.cs @@ -30,7 +30,7 @@ namespace NzbDrone.Core.Indexers.Rarbg [FieldDefinition(1, Type = FieldType.Checkbox, Label = "Ranked Only", HelpText = "Only include ranked results.")] public bool RankedOnly { get; set; } - + [FieldDefinition(2, Type = FieldType.Captcha, Label = "CAPTCHA Token", HelpText = "CAPTCHA Clearance token used to handle CloudFlare Anti-DDOS measures on shared-ip VPNs.")] public string CaptchaToken { get; set; } diff --git a/src/NzbDrone.Core/Indexers/Rarbg/RarbgTokenProvider.cs b/src/NzbDrone.Core/Indexers/Rarbg/RarbgTokenProvider.cs index 15a7a7bdb..c014e9c68 100644 --- a/src/NzbDrone.Core/Indexers/Rarbg/RarbgTokenProvider.cs +++ b/src/NzbDrone.Core/Indexers/Rarbg/RarbgTokenProvider.cs @@ -27,7 +27,8 @@ namespace NzbDrone.Core.Indexers.Rarbg 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 @@ namespace NzbDrone.Core.Indexers.Rarbg 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/RssEnclosure.cs b/src/NzbDrone.Core/Indexers/RssEnclosure.cs index 6c0a59c37..9e61253ad 100644 --- a/src/NzbDrone.Core/Indexers/RssEnclosure.cs +++ b/src/NzbDrone.Core/Indexers/RssEnclosure.cs @@ -1,8 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - namespace NzbDrone.Core.Indexers { public class RssEnclosure diff --git a/src/NzbDrone.Core/Indexers/RssIndexerRequestGenerator.cs b/src/NzbDrone.Core/Indexers/RssIndexerRequestGenerator.cs index 0fa1a03f1..9c8608875 100644 --- a/src/NzbDrone.Core/Indexers/RssIndexerRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/RssIndexerRequestGenerator.cs @@ -12,7 +12,6 @@ namespace NzbDrone.Core.Indexers _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 c8af9f437..096045a7b 100644 --- a/src/NzbDrone.Core/Indexers/RssParser.cs +++ b/src/NzbDrone.Core/Indexers/RssParser.cs @@ -236,6 +236,7 @@ namespace NzbDrone.Core.Indexers { return GetEnclosureLength(item); } + if (ParseSizeInDescription && item.Element("description") != null) { return ParseSize(item.Element("description").Value, true); @@ -292,7 +293,6 @@ namespace NzbDrone.Core.Indexers protected virtual RssEnclosure GetEnclosure(RssEnclosure[] enclosures, bool enforceMimeType = true) { - if (enclosures.Length == 0) { return null; @@ -399,6 +399,7 @@ namespace NzbDrone.Core.Indexers return (long)value; } } + return 0; } diff --git a/src/NzbDrone.Core/Indexers/RssSyncCommand.cs b/src/NzbDrone.Core/Indexers/RssSyncCommand.cs index 308a9de2e..47b9cca67 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; } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Indexers/RssSyncService.cs b/src/NzbDrone.Core/Indexers/RssSyncService.cs index 27c0256e4..8f4a07a04 100644 --- a/src/NzbDrone.Core/Indexers/RssSyncService.cs +++ b/src/NzbDrone.Core/Indexers/RssSyncService.cs @@ -39,7 +39,6 @@ namespace NzbDrone.Core.Indexers _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 f1e250ce9..f41d65ea6 100644 --- a/src/NzbDrone.Core/Indexers/SeedConfigProvider.cs +++ b/src/NzbDrone.Core/Indexers/SeedConfigProvider.cs @@ -1,9 +1,6 @@ using System; -using System.Linq; -using NzbDrone.Common.Extensions; using NzbDrone.Core.Datastore; using NzbDrone.Core.Download.Clients; -using NzbDrone.Core.Indexers; using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.Indexers diff --git a/src/NzbDrone.Core/Indexers/SeedCriteriaSettings.cs b/src/NzbDrone.Core/Indexers/SeedCriteriaSettings.cs index 08b9f00b5..d9b5410c1 100644 --- a/src/NzbDrone.Core/Indexers/SeedCriteriaSettings.cs +++ b/src/NzbDrone.Core/Indexers/SeedCriteriaSettings.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using FluentValidation; using NzbDrone.Core.Annotations; using NzbDrone.Core.Validation; @@ -39,7 +35,7 @@ namespace NzbDrone.Core.Indexers .AsWarning() .WithMessage($"Under {seedTimeMinimum} leads to H&R"); } - + if (discographySeedTimeMinimum != 0) { RuleFor(c => c.DiscographySeedTime).GreaterThanOrEqualTo(discographySeedTimeMinimum) diff --git a/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssIndexerRequestGenerator.cs b/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssIndexerRequestGenerator.cs index 582a817e9..956f60a25 100644 --- a/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssIndexerRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssIndexerRequestGenerator.cs @@ -8,7 +8,7 @@ namespace NzbDrone.Core.Indexers.TorrentRss public class TorrentRssIndexerRequestGenerator : IIndexerRequestGenerator { public TorrentRssIndexerSettings Settings { get; set; } - + public virtual IndexerPageableRequestChain GetRecentRequests() { var pageableRequests = new IndexerPageableRequestChain(); diff --git a/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssIndexerSettings.cs b/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssIndexerSettings.cs index b9a1b514e..e0fd4f1ca 100644 --- a/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssIndexerSettings.cs +++ b/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssIndexerSettings.cs @@ -16,7 +16,7 @@ namespace NzbDrone.Core.Indexers.TorrentRss public class TorrentRssIndexerSettings : ITorrentIndexerSettings { - private static readonly TorrentRssIndexerSettingsValidator validator = new TorrentRssIndexerSettingsValidator(); + private static readonly TorrentRssIndexerSettingsValidator Validator = new TorrentRssIndexerSettingsValidator(); public TorrentRssIndexerSettings() { @@ -31,7 +31,7 @@ namespace NzbDrone.Core.Indexers.TorrentRss [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.Textbox, Label = "Minimum Seeders", HelpText = "Minimum number of seeders required.", Advanced = true)] @@ -45,7 +45,7 @@ namespace NzbDrone.Core.Indexers.TorrentRss public NzbDroneValidationResult Validate() { - return new NzbDroneValidationResult(validator.Validate(this)); + return new NzbDroneValidationResult(Validator.Validate(this)); } } } diff --git a/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssParserFactory.cs b/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssParserFactory.cs index a60e3cd9c..d7b58cda7 100644 --- a/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssParserFactory.cs +++ b/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssParserFactory.cs @@ -14,7 +14,7 @@ namespace NzbDrone.Core.Indexers.TorrentRss public class TorrentRssParserFactory : ITorrentRssParserFactory { protected readonly Logger _logger; - + private readonly ICached _settingsCache; private readonly ITorrentRssSettingsDetector _torrentRssSettingsDetector; diff --git a/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssSettingsDetector.cs b/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssSettingsDetector.cs index 8142ac892..d9bc95c22 100644 --- a/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssSettingsDetector.cs +++ b/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssSettingsDetector.cs @@ -1,7 +1,6 @@ using System; -using System.Linq; using System.IO; -using System.Text.RegularExpressions; +using System.Linq; using System.Xml; using System.Xml.Linq; using NLog; @@ -19,12 +18,12 @@ namespace NzbDrone.Core.Indexers.TorrentRss 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; @@ -148,7 +147,7 @@ namespace NzbDrone.Core.Indexers.TorrentRss _logger.Trace("Feed doesn't have Seeders in Description, disabling option."); parser.ParseSeedersInDescription = settings.ParseSeedersInDescription = false; } - + if (!releases.Any(r => r.Size < ValidSizeThreshold)) { _logger.Trace("Feed has valid size in enclosure."); @@ -183,6 +182,7 @@ namespace NzbDrone.Core.Indexers.TorrentRss { _logger.Debug("Feed {0} contains very small releases.", response.Request.Url); } + _logger.Trace("Feed has valid size in description."); return settings; } @@ -244,7 +244,6 @@ namespace NzbDrone.Core.Indexers.TorrentRss { var releases = parser.ParseResponse(response).Cast().ToArray(); return releases; - } catch (Exception ex) { @@ -279,7 +278,6 @@ namespace NzbDrone.Core.Indexers.TorrentRss 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/Torrentleech/Torrentleech.cs b/src/NzbDrone.Core/Indexers/Torrentleech/Torrentleech.cs index 5c7620a1a..fc3a46bc2 100644 --- a/src/NzbDrone.Core/Indexers/Torrentleech/Torrentleech.cs +++ b/src/NzbDrone.Core/Indexers/Torrentleech/Torrentleech.cs @@ -1,7 +1,7 @@ -using NzbDrone.Common.Http; +using NLog; +using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.Parser; -using NLog; namespace NzbDrone.Core.Indexers.Torrentleech { @@ -16,7 +16,6 @@ namespace NzbDrone.Core.Indexers.Torrentleech public Torrentleech(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/Torrentleech/TorrentleechRequestGenerator.cs b/src/NzbDrone.Core/Indexers/Torrentleech/TorrentleechRequestGenerator.cs index 829b485f8..a110a9cdf 100644 --- a/src/NzbDrone.Core/Indexers/Torrentleech/TorrentleechRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/Torrentleech/TorrentleechRequestGenerator.cs @@ -7,7 +7,7 @@ namespace NzbDrone.Core.Indexers.Torrentleech public class TorrentleechRequestGenerator : IIndexerRequestGenerator { public TorrentleechSettings Settings { get; set; } - + public virtual IndexerPageableRequestChain GetRecentRequests() { var pageableRequests = new IndexerPageableRequestChain(); diff --git a/src/NzbDrone.Core/Indexers/Torznab/Torznab.cs b/src/NzbDrone.Core/Indexers/Torznab/Torznab.cs index 1847aca49..27132cd85 100644 --- a/src/NzbDrone.Core/Indexers/Torznab/Torznab.cs +++ b/src/NzbDrone.Core/Indexers/Torznab/Torznab.cs @@ -8,7 +8,6 @@ using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.Indexers.Newznab; using NzbDrone.Core.Parser; -using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; namespace NzbDrone.Core.Indexers.Torznab @@ -45,17 +44,17 @@ namespace NzbDrone.Core.Indexers.Torznab 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, params int[] categories) @@ -73,7 +72,11 @@ namespace NzbDrone.Core.Indexers.Torznab protected override void Test(List failures) { base.Test(failures); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestCapabilities()); } diff --git a/src/NzbDrone.Core/Indexers/Torznab/TorznabException.cs b/src/NzbDrone.Core/Indexers/Torznab/TorznabException.cs index 258a12492..4c8836a88 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 46bd46533..26ddd8110 100644 --- a/src/NzbDrone.Core/Indexers/Torznab/TorznabRssParser.cs +++ b/src/NzbDrone.Core/Indexers/Torznab/TorznabRssParser.cs @@ -22,12 +22,18 @@ namespace NzbDrone.Core.Indexers.Torznab 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") { @@ -60,7 +66,6 @@ namespace NzbDrone.Core.Indexers.Torznab return true; } - protected override string GetInfoUrl(XElement item) { return ParseUrl(item.TryGetValue("comments").TrimEnd("#comments")); diff --git a/src/NzbDrone.Core/Indexers/Torznab/TorznabSettings.cs b/src/NzbDrone.Core/Indexers/Torznab/TorznabSettings.cs index 4051bdb5b..fe2ec3a95 100644 --- a/src/NzbDrone.Core/Indexers/Torznab/TorznabSettings.cs +++ b/src/NzbDrone.Core/Indexers/Torznab/TorznabSettings.cs @@ -1,7 +1,6 @@ using System.Linq; using System.Text.RegularExpressions; using FluentValidation; -using FluentValidation.Results; using NzbDrone.Common.Extensions; using NzbDrone.Core.Annotations; using NzbDrone.Core.Indexers.Newznab; diff --git a/src/NzbDrone.Core/Indexers/Waffles/Waffles.cs b/src/NzbDrone.Core/Indexers/Waffles/Waffles.cs index f337ca6d5..9f2377fb2 100644 --- a/src/NzbDrone.Core/Indexers/Waffles/Waffles.cs +++ b/src/NzbDrone.Core/Indexers/Waffles/Waffles.cs @@ -1,6 +1,6 @@ -using NzbDrone.Common.Http; +using NLog; +using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; -using NLog; using NzbDrone.Core.Parser; namespace NzbDrone.Core.Indexers.Waffles @@ -15,7 +15,6 @@ namespace NzbDrone.Core.Indexers.Waffles public Waffles(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { - } public override IIndexerRequestGenerator GetRequestGenerator() @@ -28,4 +27,4 @@ namespace NzbDrone.Core.Indexers.Waffles return new WafflesRssParser() { ParseSizeInDescription = true, ParseSeedersInDescription = true }; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Indexers/Waffles/WafflesRequestGenerator.cs b/src/NzbDrone.Core/Indexers/Waffles/WafflesRequestGenerator.cs index 50d4589b5..fa39d562b 100644 --- a/src/NzbDrone.Core/Indexers/Waffles/WafflesRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/Waffles/WafflesRequestGenerator.cs @@ -1,8 +1,7 @@ using System.Collections.Generic; +using System.Text; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; -using System.Text; -using System; using NzbDrone.Core.IndexerSearch.Definitions; namespace NzbDrone.Core.Indexers.Waffles @@ -30,7 +29,7 @@ namespace NzbDrone.Core.Indexers.Waffles { var pageableRequests = new IndexerPageableRequestChain(); - pageableRequests.Add(GetPagedRequests(MaxPages, string.Format("&q=artist:{0} album:{1}",searchCriteria.ArtistQuery,searchCriteria.AlbumQuery))); + pageableRequests.Add(GetPagedRequests(MaxPages, string.Format("&q=artist:{0} album:{1}", searchCriteria.ArtistQuery, searchCriteria.AlbumQuery))); return pageableRequests; } @@ -45,10 +44,9 @@ namespace NzbDrone.Core.Indexers.Waffles } private IEnumerable GetPagedRequests(int maxPages, string query) - { - + { var url = new StringBuilder(); - + url.AppendFormat("{0}/browse.php?rss=1&c0=1&uid={1}&passkey={2}", Settings.BaseUrl.Trim().TrimEnd('/'), Settings.UserId, Settings.RssPasskey); if (query.IsNotNullOrWhiteSpace()) diff --git a/src/NzbDrone.Core/Indexers/Waffles/WafflesRssParser.cs b/src/NzbDrone.Core/Indexers/Waffles/WafflesRssParser.cs index 4cc8e6be6..a5744d141 100644 --- a/src/NzbDrone.Core/Indexers/Waffles/WafflesRssParser.cs +++ b/src/NzbDrone.Core/Indexers/Waffles/WafflesRssParser.cs @@ -1,16 +1,15 @@ using System; using System.Globalization; using System.Linq; -using System.Xml.Linq; using System.Text.RegularExpressions; +using System.Xml.Linq; using NzbDrone.Common.Extensions; using NzbDrone.Core.Indexers.Exceptions; using NzbDrone.Core.Parser.Model; - namespace NzbDrone.Core.Indexers.Waffles { - public class WafflesRssParser : TorrentRssParser + public class WafflesRssParser : TorrentRssParser { public const string ns = "{http://purl.org/rss/1.0/}"; public const string dc = "{http://purl.org/dc/elements/1.1/}"; @@ -20,12 +19,18 @@ namespace NzbDrone.Core.Indexers.Waffles 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 Pass key"); + if (code >= 100 && code <= 199) + { + throw new ApiKeyException("Invalid Pass key"); + } if (!indexerResponse.Request.Url.FullUri.Contains("passkey=") && errorMessage == "Missing parameter") { @@ -57,8 +62,8 @@ namespace NzbDrone.Core.Indexers.Waffles return ParseUrl(item.TryGetValue("comments")); } - private static readonly Regex ParseSizeRegex = new Regex(@"(?:Size: )(?\d+)<", - RegexOptions.IgnoreCase | RegexOptions.Compiled); + private static readonly Regex ParseSizeRegex = new Regex(@"(?:Size: )(?\d+)<", + RegexOptions.IgnoreCase | RegexOptions.Compiled); protected override long GetSize(XElement item) { diff --git a/src/NzbDrone.Core/Indexers/Waffles/WafflesSettings.cs b/src/NzbDrone.Core/Indexers/Waffles/WafflesSettings.cs index 28d10c59f..ef681924e 100644 --- a/src/NzbDrone.Core/Indexers/Waffles/WafflesSettings.cs +++ b/src/NzbDrone.Core/Indexers/Waffles/WafflesSettings.cs @@ -1,4 +1,3 @@ -using System.Text.RegularExpressions; using FluentValidation; using NzbDrone.Core.Annotations; using NzbDrone.Core.Validation; @@ -43,7 +42,6 @@ namespace NzbDrone.Core.Indexers.Waffles [FieldDefinition(5, Type = FieldType.Number, Label = "Early Download Limit", Unit = "days", HelpText = "Time before release date Lidarr will download from this indexer, empty is no limit", Advanced = true)] public int? EarlyReleaseLimit { get; set; } - public NzbDroneValidationResult Validate() { return new NzbDroneValidationResult(Validator.Validate(this)); diff --git a/src/NzbDrone.Core/Indexers/XElementExtensions.cs b/src/NzbDrone.Core/Indexers/XElementExtensions.cs index ef2b8b064..a90dbed85 100644 --- a/src/NzbDrone.Core/Indexers/XElementExtensions.cs +++ b/src/NzbDrone.Core/Indexers/XElementExtensions.cs @@ -27,8 +27,7 @@ namespace NzbDrone.Core.Indexers root.Name.LocalName, root.HasElements ? root.Elements().Select(StripNameSpace) : - (object)root.Value - ); + (object)root.Value); res.ReplaceAttributes( root.Attributes().Where(attr => (!attr.IsNamespaceDeclaration))); @@ -46,6 +45,7 @@ namespace NzbDrone.Core.Indexers dateString = RemoveTimeZoneRegex.Replace(dateString, ""); result = DateTime.Parse(dateString, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal); } + return result.ToUniversalTime(); } catch (FormatException e) @@ -109,7 +109,6 @@ namespace NzbDrone.Core.Indexers { 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 91d0ea3b1..9d1f95654 100644 --- a/src/NzbDrone.Core/Indexers/XmlCleaner.cs +++ b/src/NzbDrone.Core/Indexers/XmlCleaner.cs @@ -1,12 +1,10 @@ -using System.Globalization; -using System.Net; +using System.Net; using System.Text.RegularExpressions; 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/Commands/ClearLogCommand.cs b/src/NzbDrone.Core/Instrumentation/Commands/ClearLogCommand.cs index f8eb71ee7..80463075c 100644 --- a/src/NzbDrone.Core/Instrumentation/Commands/ClearLogCommand.cs +++ b/src/NzbDrone.Core/Instrumentation/Commands/ClearLogCommand.cs @@ -6,4 +6,4 @@ namespace NzbDrone.Core.Instrumentation.Commands { public override bool SendUpdatesToClient => true; } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Instrumentation/Commands/DeleteLogFilesCommand.cs b/src/NzbDrone.Core/Instrumentation/Commands/DeleteLogFilesCommand.cs index 7676baa52..1cc1712d2 100644 --- a/src/NzbDrone.Core/Instrumentation/Commands/DeleteLogFilesCommand.cs +++ b/src/NzbDrone.Core/Instrumentation/Commands/DeleteLogFilesCommand.cs @@ -6,4 +6,4 @@ namespace NzbDrone.Core.Instrumentation.Commands { public override bool SendUpdatesToClient => true; } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Instrumentation/Commands/DeleteUpdateLogFilesCommand.cs b/src/NzbDrone.Core/Instrumentation/Commands/DeleteUpdateLogFilesCommand.cs index 5a909bdf6..97fa8d456 100644 --- a/src/NzbDrone.Core/Instrumentation/Commands/DeleteUpdateLogFilesCommand.cs +++ b/src/NzbDrone.Core/Instrumentation/Commands/DeleteUpdateLogFilesCommand.cs @@ -6,4 +6,4 @@ namespace NzbDrone.Core.Instrumentation.Commands { public override bool SendUpdatesToClient => true; } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Instrumentation/DatabaseTarget.cs b/src/NzbDrone.Core/Instrumentation/DatabaseTarget.cs index 1c36b91a8..2a74549b9 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 SQLiteConnection _connection; - - 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 SQLiteConnection _connection; + public DatabaseTarget(IConnectionStringFactory connectionStringFactory) { _connection = new SQLiteConnection(connectionStringFactory.LogDbConnectionString); @@ -110,4 +110,4 @@ namespace NzbDrone.Core.Instrumentation } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Instrumentation/Log.cs b/src/NzbDrone.Core/Instrumentation/Log.cs index 6410ab6e9..91e4710b0 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; } @@ -19,4 +17,4 @@ namespace NzbDrone.Core.Instrumentation public string Level { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Instrumentation/LogRepository.cs b/src/NzbDrone.Core/Instrumentation/LogRepository.cs index 97bfe9f79..69bcbe474 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 @@ -24,4 +23,4 @@ namespace NzbDrone.Core.Instrumentation Vacuum(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Instrumentation/LogService.cs b/src/NzbDrone.Core/Instrumentation/LogService.cs index f0727e859..c12a65694 100644 --- a/src/NzbDrone.Core/Instrumentation/LogService.cs +++ b/src/NzbDrone.Core/Instrumentation/LogService.cs @@ -28,4 +28,4 @@ namespace NzbDrone.Core.Instrumentation _logRepository.Purge(vacuum: true); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Instrumentation/ReconfigureLogging.cs b/src/NzbDrone.Core/Instrumentation/ReconfigureLogging.cs index 2de9edfe1..47e27a4e4 100644 --- a/src/NzbDrone.Core/Instrumentation/ReconfigureLogging.cs +++ b/src/NzbDrone.Core/Instrumentation/ReconfigureLogging.cs @@ -26,11 +26,17 @@ namespace NzbDrone.Core.Instrumentation 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 @@ namespace NzbDrone.Core.Instrumentation { rule.DisableLoggingForLevel(logLevel); } - else { rule.EnableLoggingForLevel(logLevel); @@ -77,7 +82,7 @@ namespace NzbDrone.Core.Instrumentation 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 994aedc50..d64178f81 100644 --- a/src/NzbDrone.Core/Instrumentation/SlowRunningAsyncTargetWrapper.cs +++ b/src/NzbDrone.Core/Instrumentation/SlowRunningAsyncTargetWrapper.cs @@ -13,7 +13,6 @@ namespace NzbDrone.Core.Instrumentation public SlowRunningAsyncTargetWrapper(Target wrappedTarget) : base(wrappedTarget) { - } protected override void StopLazyWriterThread() @@ -37,7 +36,6 @@ namespace NzbDrone.Core.Instrumentation 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/ScheduledTask.cs b/src/NzbDrone.Core/Jobs/ScheduledTask.cs index 5d842696d..dcf7f5908 100644 --- a/src/NzbDrone.Core/Jobs/ScheduledTask.cs +++ b/src/NzbDrone.Core/Jobs/ScheduledTask.cs @@ -9,4 +9,4 @@ namespace NzbDrone.Core.Jobs public int Interval { get; set; } public DateTime LastExecution { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Jobs/ScheduledTaskRepository.cs b/src/NzbDrone.Core/Jobs/ScheduledTaskRepository.cs index 648ca0450..c565017d2 100644 --- a/src/NzbDrone.Core/Jobs/ScheduledTaskRepository.cs +++ b/src/NzbDrone.Core/Jobs/ScheduledTaskRepository.cs @@ -3,7 +3,6 @@ using System.Linq; using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; - namespace NzbDrone.Core.Jobs { public interface IScheduledTaskRepository : IBasicRepository @@ -14,7 +13,6 @@ namespace NzbDrone.Core.Jobs public class ScheduledTaskRepository : BasicRepository, IScheduledTaskRepository { - public ScheduledTaskRepository(IMainDatabase database, IEventAggregator eventAggregator) : base(database, eventAggregator) { @@ -28,10 +26,10 @@ namespace NzbDrone.Core.Jobs public void SetLastExecutionTime(int id, DateTime executionTime) { var task = new ScheduledTask - { - Id = id, - LastExecution = executionTime - }; + { + Id = id, + LastExecution = executionTime + }; SetFields(task, scheduledTask => scheduledTask.LastExecution); } diff --git a/src/NzbDrone.Core/Jobs/Scheduler.cs b/src/NzbDrone.Core/Jobs/Scheduler.cs index a18aac556..4d854d508 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 @@ namespace NzbDrone.Core.Jobs _commandQueueManager.Push(task.TypeName, task.LastExecution, CommandPriority.Low, CommandTrigger.Scheduled); } } - finally { if (!_cancellationTokenSource.IsCancellationRequested) @@ -69,4 +68,4 @@ namespace NzbDrone.Core.Jobs Timer.Stop(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Jobs/TaskManager.cs b/src/NzbDrone.Core/Jobs/TaskManager.cs index f75264d67..c7c0b6561 100644 --- a/src/NzbDrone.Core/Jobs/TaskManager.cs +++ b/src/NzbDrone.Core/Jobs/TaskManager.cs @@ -8,13 +8,13 @@ using NzbDrone.Core.Configuration.Events; using NzbDrone.Core.Download; using NzbDrone.Core.HealthCheck; using NzbDrone.Core.Housekeeping; -using NzbDrone.Core.Indexers; using NzbDrone.Core.ImportLists; +using NzbDrone.Core.Indexers; using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Update.Commands; using NzbDrone.Core.Music.Commands; +using NzbDrone.Core.Update.Commands; namespace NzbDrone.Core.Jobs { @@ -60,12 +60,12 @@ namespace NzbDrone.Core.Jobs { var defaultTasks = new[] { - new ScheduledTask{ Interval = 1, TypeName = typeof(CheckForFinishedDownloadCommand).FullName}, - new ScheduledTask{ Interval = 5, TypeName = typeof(MessagingCleanupCommand).FullName}, - new ScheduledTask{ Interval = 6*60, TypeName = typeof(ApplicationUpdateCommand).FullName}, - new ScheduledTask{ Interval = 6*60, TypeName = typeof(CheckHealthCommand).FullName}, - new ScheduledTask{ Interval = 24*60, TypeName = typeof(RefreshArtistCommand).FullName}, - new ScheduledTask{ Interval = 24*60, TypeName = typeof(HousekeepingCommand).FullName}, + new ScheduledTask { Interval = 1, TypeName = typeof(CheckForFinishedDownloadCommand).FullName }, + new ScheduledTask { Interval = 5, TypeName = typeof(MessagingCleanupCommand).FullName }, + new ScheduledTask { Interval = 6 * 60, TypeName = typeof(ApplicationUpdateCommand).FullName }, + new ScheduledTask { Interval = 6 * 60, TypeName = typeof(CheckHealthCommand).FullName }, + new ScheduledTask { Interval = 24 * 60, TypeName = typeof(RefreshArtistCommand).FullName }, + new ScheduledTask { Interval = 24 * 60, TypeName = typeof(HousekeepingCommand).FullName }, new ScheduledTask { @@ -80,7 +80,7 @@ namespace NzbDrone.Core.Jobs }, new ScheduledTask - { + { Interval = GetRssSyncInterval(), TypeName = typeof(RssSyncCommand).FullName } diff --git a/src/NzbDrone.Core/Lifecycle/ApplicationShutdownRequested.cs b/src/NzbDrone.Core/Lifecycle/ApplicationShutdownRequested.cs index 42d2f411e..7982c1d36 100644 --- a/src/NzbDrone.Core/Lifecycle/ApplicationShutdownRequested.cs +++ b/src/NzbDrone.Core/Lifecycle/ApplicationShutdownRequested.cs @@ -11,4 +11,4 @@ namespace NzbDrone.Core.Lifecycle Restarting = restarting; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Lifecycle/ApplicationStartedEvent.cs b/src/NzbDrone.Core/Lifecycle/ApplicationStartedEvent.cs index f66622dd3..8e0d45e15 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 { - } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Lifecycle/LifecycleService.cs b/src/NzbDrone.Core/Lifecycle/LifecycleService.cs index e4d727b0d..9ed36a42e 100644 --- a/src/NzbDrone.Core/Lifecycle/LifecycleService.cs +++ b/src/NzbDrone.Core/Lifecycle/LifecycleService.cs @@ -21,7 +21,6 @@ namespace NzbDrone.Core.Lifecycle private readonly IServiceProvider _serviceProvider; private readonly Logger _logger; - public LifecycleService(IEventAggregator eventAggregator, IRuntimeInfo runtimeInfo, IServiceProvider serviceProvider, diff --git a/src/NzbDrone.Core/MediaCover/ImageResizer.cs b/src/NzbDrone.Core/MediaCover/ImageResizer.cs index 0429c8d8a..4e4301363 100644 --- a/src/NzbDrone.Core/MediaCover/ImageResizer.cs +++ b/src/NzbDrone.Core/MediaCover/ImageResizer.cs @@ -1,5 +1,4 @@ -using System; -using NzbDrone.Common.Disk; +using NzbDrone.Common.Disk; using NzbDrone.Common.EnvironmentInfo; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Jpeg; @@ -42,7 +41,10 @@ namespace NzbDrone.Core.MediaCover public void Resize(string source, string destination, int height) { - if (!_enabled) return; + if (!_enabled) + { + return; + } try { @@ -58,6 +60,7 @@ namespace NzbDrone.Core.MediaCover { _diskProvider.DeleteFile(destination); } + throw; } } diff --git a/src/NzbDrone.Core/MediaCover/MediaCover.cs b/src/NzbDrone.Core/MediaCover/MediaCover.cs index 4e5c42b7d..d991a14ec 100644 --- a/src/NzbDrone.Core/MediaCover/MediaCover.cs +++ b/src/NzbDrone.Core/MediaCover/MediaCover.cs @@ -1,11 +1,10 @@ using System.IO; -using NzbDrone.Common.Extensions; using Equ; +using NzbDrone.Common.Extensions; using NzbDrone.Core.Datastore; 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 9e63225d3..e1a89c126 100644 --- a/src/NzbDrone.Core/MediaCover/MediaCoverService.cs +++ b/src/NzbDrone.Core/MediaCover/MediaCoverService.cs @@ -44,9 +44,8 @@ namespace NzbDrone.Core.MediaCover // 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, - IAlbumService albumService, + IAlbumService albumService, IHttpClient httpClient, IDiskProvider diskProvider, IAppFolderInfo appFolderInfo, @@ -122,7 +121,7 @@ namespace NzbDrone.Core.MediaCover { var fileName = GetCoverPath(artist.Id, MediaCoverEntity.Artist, cover.CoverType, cover.Extension); var alreadyExists = false; - + try { var serverFileHeaders = _httpClient.Head(new HttpRequest(cover.Url) { AllowAutoRedirect = true }).Headers; diff --git a/src/NzbDrone.Core/MediaFiles/AudioTag.cs b/src/NzbDrone.Core/MediaFiles/AudioTag.cs index 786f24b5b..70b3d6bf3 100644 --- a/src/NzbDrone.Core/MediaFiles/AudioTag.cs +++ b/src/NzbDrone.Core/MediaFiles/AudioTag.cs @@ -1,17 +1,17 @@ -using NzbDrone.Common.Extensions; -using NzbDrone.Core.Parser.Model; -using System.Linq; -using System.Collections.Generic; using System; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Parser; -using NzbDrone.Common.Instrumentation; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; using NLog; +using NLog.Fluent; +using NzbDrone.Common.Extensions; +using NzbDrone.Common.Instrumentation; +using NzbDrone.Common.Instrumentation.Extensions; +using NzbDrone.Core.Parser; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Qualities; using TagLib; using TagLib.Id3v2; -using NLog.Fluent; -using NzbDrone.Common.Instrumentation.Extensions; -using System.Globalization; namespace NzbDrone.Core.MediaFiles { @@ -100,18 +100,18 @@ namespace NzbDrone.Core.MediaFiles // Do the ones that aren't handled by the generic taglib implementation if (file.TagTypesOnDisk.HasFlag(TagTypes.Id3v2)) { - var id3tag = (TagLib.Id3v2.Tag) file.GetTag(TagTypes.Id3v2); + var id3tag = (TagLib.Id3v2.Tag)file.GetTag(TagTypes.Id3v2); Media = id3tag.GetTextAsString("TMED"); Date = ReadId3Date(id3tag, "TDRC"); OriginalReleaseDate = ReadId3Date(id3tag, "TDOR"); MusicBrainzAlbumComment = UserTextInformationFrame.Get(id3tag, "MusicBrainz Album Comment", false)?.Text.ExclusiveOrDefault(); - MusicBrainzReleaseTrackId = UserTextInformationFrame.Get(id3tag, "MusicBrainz Release Track Id", false)?.Text.ExclusiveOrDefault(); + MusicBrainzReleaseTrackId = UserTextInformationFrame.Get(id3tag, "MusicBrainz Release Track Id", false)?.Text.ExclusiveOrDefault(); } else if (file.TagTypesOnDisk.HasFlag(TagTypes.Xiph)) { // while publisher is handled by taglib, it seems to be mapped to 'ORGANIZATION' and not 'LABEL' like Picard is // https://picard.musicbrainz.org/docs/mappings/ - var flactag = (TagLib.Ogg.XiphComment) file.GetTag(TagLib.TagTypes.Xiph); + var flactag = (TagLib.Ogg.XiphComment)file.GetTag(TagLib.TagTypes.Xiph); Media = flactag.GetField("MEDIA").ExclusiveOrDefault(); Date = DateTime.TryParse(flactag.GetField("DATE").ExclusiveOrDefault(), out tempDate) ? tempDate : default(DateTime?); OriginalReleaseDate = DateTime.TryParse(flactag.GetField("ORIGINALDATE").ExclusiveOrDefault(), out tempDate) ? tempDate : default(DateTime?); @@ -132,7 +132,7 @@ namespace NzbDrone.Core.MediaFiles } else if (file.TagTypesOnDisk.HasFlag(TagTypes.Ape)) { - var apetag = (TagLib.Ape.Tag) file.GetTag(TagTypes.Ape); + var apetag = (TagLib.Ape.Tag)file.GetTag(TagTypes.Ape); Media = apetag.GetItem("Media")?.ToString(); Date = DateTime.TryParse(apetag.GetItem("Year")?.ToString(), out tempDate) ? tempDate : default(DateTime?); OriginalReleaseDate = DateTime.TryParse(apetag.GetItem("Original Date")?.ToString(), out tempDate) ? tempDate : default(DateTime?); @@ -142,7 +142,7 @@ namespace NzbDrone.Core.MediaFiles } else if (file.TagTypesOnDisk.HasFlag(TagTypes.Asf)) { - var asftag = (TagLib.Asf.Tag) file.GetTag(TagTypes.Asf); + var asftag = (TagLib.Asf.Tag)file.GetTag(TagTypes.Asf); Media = asftag.GetDescriptorString("WM/Media"); Date = DateTime.TryParse(asftag.GetDescriptorString("WM/Year"), out tempDate) ? tempDate : default(DateTime?); OriginalReleaseDate = DateTime.TryParse(asftag.GetDescriptorString("WM/OriginalReleaseTime"), out tempDate) ? tempDate : default(DateTime?); @@ -152,7 +152,7 @@ namespace NzbDrone.Core.MediaFiles } else if (file.TagTypesOnDisk.HasFlag(TagTypes.Apple)) { - var appletag = (TagLib.Mpeg4.AppleTag) file.GetTag(TagTypes.Apple); + var appletag = (TagLib.Mpeg4.AppleTag)file.GetTag(TagTypes.Apple); Media = appletag.GetDashBox("com.apple.iTunes", "MEDIA"); Date = DateTime.TryParse(appletag.DataBoxes(FixAppleId("day")).FirstOrDefault()?.Text, out tempDate) ? tempDate : default(DateTime?); OriginalReleaseDate = DateTime.TryParse(appletag.GetDashBox("com.apple.iTunes", "Original Date"), out tempDate) ? tempDate : default(DateTime?); @@ -181,7 +181,8 @@ namespace NzbDrone.Core.MediaFiles Quality = QualityParser.ParseQuality(file.Name, acodec.Description, bitrate, file.Properties.BitsPerSample); Logger.Debug($"Quality parsed: {Quality}, Source: {Quality.QualityDetectionSource}"); - MediaInfo = new MediaInfoModel { + MediaInfo = new MediaInfoModel + { AudioFormat = acodec.Description, AudioBitrate = bitrate, AudioChannels = acodec.AudioChannels, @@ -228,7 +229,7 @@ namespace NzbDrone.Core.MediaFiles // Taglib File.Length is unreliable so use System.IO var size = new System.IO.FileInfo(path).Length; var duration = file.Properties.Duration.TotalSeconds; - bitrate = (int) ((size * 8L) / (duration * 1024)); + bitrate = (int)((size * 8L) / (duration * 1024)); Logger.Trace($"Estimating bitrate. Size: {size} Duration: {duration} Bitrate: {bitrate}"); } @@ -256,7 +257,7 @@ namespace NzbDrone.Core.MediaFiles else { // taglib maps the v3 TORY to TDRC so we just get a year - return Int32.TryParse(date, out int year) && year >= 1860 && year <= DateTime.UtcNow.Year + 1 ? new DateTime(year, 1, 1) : default(DateTime?); + return int.TryParse(date, out int year) && year >= 1860 && year <= DateTime.UtcNow.Year + 1 ? new DateTime(year, 1, 1) : default(DateTime?); } } @@ -269,6 +270,7 @@ namespace NzbDrone.Core.MediaFiles { tag.SetTextFrame(v3ddmm, default(string)); } + tag.SetTextFrame(v4field, date.HasValue ? date.Value.ToString("yyyy-MM-dd") : null); } else @@ -296,21 +298,26 @@ namespace NzbDrone.Core.MediaFiles } } - private static ReadOnlyByteVector FixAppleId(ByteVector id) - { - if (id.Count == 4) { - var roid = id as ReadOnlyByteVector; - if (roid != null) - return roid; + private static ReadOnlyByteVector FixAppleId(ByteVector id) + { + if (id.Count == 4) + { + var roid = id as ReadOnlyByteVector; + if (roid != null) + { + return roid; + } - return new ReadOnlyByteVector(id); - } + return new ReadOnlyByteVector(id); + } - if (id.Count == 3) - return new ReadOnlyByteVector(0xa9, id[0], id[1], id[2]); + if (id.Count == 3) + { + return new ReadOnlyByteVector(0xa9, id[0], id[1], id[2]); + } - return null; - } + return null; + } public void Write(string path) { @@ -355,7 +362,7 @@ namespace NzbDrone.Core.MediaFiles if (file.TagTypes.HasFlag(TagTypes.Id3v2)) { - var id3tag = (TagLib.Id3v2.Tag) file.GetTag(TagTypes.Id3v2); + var id3tag = (TagLib.Id3v2.Tag)file.GetTag(TagTypes.Id3v2); id3tag.SetTextFrame("TMED", Media); WriteId3Date(id3tag, "TDRC", "TYER", "TDAT", Date); WriteId3Date(id3tag, "TDOR", "TORY", null, OriginalReleaseDate); @@ -367,10 +374,11 @@ namespace NzbDrone.Core.MediaFiles // while publisher is handled by taglib, it seems to be mapped to 'ORGANIZATION' and not 'LABEL' like Picard is // https://picard.musicbrainz.org/docs/mappings/ tag.Publisher = null; + // taglib inserts leading zeros so set manually tag.Track = 0; - var flactag = (TagLib.Ogg.XiphComment) file.GetTag(TagLib.TagTypes.Xiph); + var flactag = (TagLib.Ogg.XiphComment)file.GetTag(TagLib.TagTypes.Xiph); flactag.SetField("DATE", Date.HasValue ? Date.Value.ToString("yyyy-MM-dd") : null); flactag.SetField("ORIGINALDATE", OriginalReleaseDate.HasValue ? OriginalReleaseDate.Value.ToString("yyyy-MM-dd") : null); @@ -390,7 +398,7 @@ namespace NzbDrone.Core.MediaFiles } else if (file.TagTypes.HasFlag(TagTypes.Ape)) { - var apetag = (TagLib.Ape.Tag) file.GetTag(TagTypes.Ape); + var apetag = (TagLib.Ape.Tag)file.GetTag(TagTypes.Ape); apetag.SetValue("Year", Date.HasValue ? Date.Value.ToString("yyyy-MM-dd") : null); apetag.SetValue("Original Date", OriginalReleaseDate.HasValue ? OriginalReleaseDate.Value.ToString("yyyy-MM-dd") : null); @@ -402,7 +410,7 @@ namespace NzbDrone.Core.MediaFiles } else if (file.TagTypes.HasFlag(TagTypes.Asf)) { - var asftag = (TagLib.Asf.Tag) file.GetTag(TagTypes.Asf); + var asftag = (TagLib.Asf.Tag)file.GetTag(TagTypes.Asf); asftag.SetDescriptorString(Date.HasValue ? Date.Value.ToString("yyyy-MM-dd") : null, "WM/Year"); asftag.SetDescriptorString(OriginalReleaseDate.HasValue ? OriginalReleaseDate.Value.ToString("yyyy-MM-dd") : null, "WM/OriginalReleaseTime"); @@ -414,7 +422,7 @@ namespace NzbDrone.Core.MediaFiles } else if (file.TagTypes.HasFlag(TagTypes.Apple)) { - var appletag = (TagLib.Mpeg4.AppleTag) file.GetTag(TagTypes.Apple); + var appletag = (TagLib.Mpeg4.AppleTag)file.GetTag(TagTypes.Apple); appletag.SetText(FixAppleId("day"), Date.HasValue ? Date.Value.ToString("yyyy-MM-dd") : null); appletag.SetDashBox("com.apple.iTunes", "Original Date", OriginalReleaseDate.HasValue ? OriginalReleaseDate.Value.ToString("yyyy-MM-dd") : null); @@ -549,11 +557,12 @@ namespace NzbDrone.Core.MediaFiles return output; } - public static implicit operator ParsedTrackInfo (AudioTag tag) + public static implicit operator ParsedTrackInfo(AudioTag tag) { if (!tag.IsValid) { - return new ParsedTrackInfo { + return new ParsedTrackInfo + { Quality = tag.Quality ?? new QualityModel { Quality = NzbDrone.Core.Qualities.Quality.Unknown }, MediaInfo = tag.MediaInfo ?? new MediaInfoModel() }; @@ -572,12 +581,14 @@ namespace NzbDrone.Core.MediaFiles Year = (int)tag.Year }; - return new ParsedTrackInfo { + return new ParsedTrackInfo + { AlbumTitle = tag.Album, ArtistTitle = artist, ArtistMBId = tag.MusicBrainzReleaseArtistId, AlbumMBId = tag.MusicBrainzReleaseGroupId, ReleaseMBId = tag.MusicBrainzReleaseId, + // SIC: the recording ID is stored in this field. // See https://picard.musicbrainz.org/docs/mappings/ RecordingMBId = tag.MusicBrainzTrackId, @@ -586,7 +597,7 @@ namespace NzbDrone.Core.MediaFiles DiscCount = (int)tag.DiscCount, Year = tag.Year, Label = tag.Publisher, - TrackNumbers = new [] { (int) tag.Track }, + TrackNumbers = new[] { (int)tag.Track }, ArtistTitleInfo = artistTitleInfo, Title = tag.Title, CleanTitle = tag.Title?.CleanTrackTitle(), diff --git a/src/NzbDrone.Core/MediaFiles/AudioTagService.cs b/src/NzbDrone.Core/MediaFiles/AudioTagService.cs index 90ade9763..9ae93b386 100644 --- a/src/NzbDrone.Core/MediaFiles/AudioTagService.cs +++ b/src/NzbDrone.Core/MediaFiles/AudioTagService.cs @@ -1,22 +1,21 @@ -using NLog; -using NzbDrone.Core.Parser.Model; -using System.IO; -using System.Linq; -using NzbDrone.Core.Configuration; -using NzbDrone.Core.Messaging.Commands; -using NzbDrone.Core.MediaFiles.Commands; -using NzbDrone.Common.Instrumentation.Extensions; -using NzbDrone.Core.Music; -using System.Collections.Generic; -using NzbDrone.Core.Parser; -using NzbDrone.Common.Disk; using System; +using System.Collections.Generic; +using System.Linq; +using NLog; using NLog.Fluent; -using NzbDrone.Core.MediaFiles.Events; -using NzbDrone.Core.Messaging.Events; -using TagLib; +using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; +using NzbDrone.Common.Instrumentation.Extensions; +using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaCover; +using NzbDrone.Core.MediaFiles.Commands; +using NzbDrone.Core.MediaFiles.Events; +using NzbDrone.Core.Messaging.Commands; +using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Music; +using NzbDrone.Core.Parser; +using NzbDrone.Core.Parser.Model; +using TagLib; namespace NzbDrone.Core.MediaFiles { @@ -32,7 +31,7 @@ namespace NzbDrone.Core.MediaFiles List GetRetagPreviewsByArtist(int artistId); List GetRetagPreviewsByAlbum(int artistId); } - + public class AudioTagService : IAudioTagService, IExecute, IExecute @@ -44,7 +43,7 @@ namespace NzbDrone.Core.MediaFiles private readonly IMapCoversToLocal _mediaCoverService; private readonly IEventAggregator _eventAggregator; private readonly Logger _logger; - + public AudioTagService(IConfigService configService, IMediaFileService mediaFileService, IDiskProvider diskProvider, @@ -98,15 +97,17 @@ namespace NzbDrone.Core.MediaFiles } } - return new AudioTag { + return new AudioTag + { Title = track.Title, - Performers = new [] { artist.Name }, - AlbumArtists = new [] { albumartist.Name }, + Performers = new[] { artist.Name }, + AlbumArtists = new[] { albumartist.Name }, Track = (uint)track.AbsoluteTrackNumber, TrackCount = (uint)release.Tracks.Value.Count(x => x.MediumNumber == track.MediumNumber), Album = album.Title, Disc = (uint)track.MediumNumber, DiscCount = (uint)release.Media.Count, + // We may have omitted media so index in the list isn't the same as medium number Media = release.Media.SingleOrDefault(x => x.Number == track.MediumNumber).Format, Date = release.ReleaseDate, @@ -136,7 +137,7 @@ namespace NzbDrone.Core.MediaFiles var fileInfo = _diskProvider.GetFileInfo(path); trackfile.Size = fileInfo.Length; trackfile.Modified = fileInfo.LastWriteTimeUtc; - + if (trackfile.Id > 0) { _mediaFileService.Update(trackfile); @@ -173,7 +174,7 @@ namespace NzbDrone.Core.MediaFiles public void RemoveMusicBrainzTags(string path) { var tags = new AudioTag(path); - + tags.MusicBrainzReleaseCountry = null; tags.MusicBrainzReleaseStatus = null; tags.MusicBrainzReleaseType = null; @@ -220,7 +221,7 @@ namespace NzbDrone.Core.MediaFiles newTags.Write(path); UpdateTrackfileSizeAndModified(trackfile, path); - + _eventAggregator.PublishEvent(new TrackFileRetaggedEvent(trackfile.Artist.Value, trackfile, diff, _configService.ScrubAudioTags)); } @@ -304,7 +305,7 @@ namespace NzbDrone.Core.MediaFiles _logger.Debug($"Removing MusicBrainz tags for {path}"); RemoveMusicBrainzTags(path); - + UpdateTrackfileSizeAndModified(trackfile, path); } @@ -348,7 +349,8 @@ namespace NzbDrone.Core.MediaFiles if (diff.Any()) { - yield return new RetagTrackFilePreview { + yield return new RetagTrackFilePreview + { ArtistId = file.Artist.Value.Id, AlbumId = file.Album.Value.Id, TrackNumbers = file.Tracks.Value.Select(e => e.AbsoluteTrackNumber).ToList(), @@ -370,9 +372,10 @@ namespace NzbDrone.Core.MediaFiles { WriteTags(file, false, force: true); } + _logger.ProgressInfo("Selected track files re-tagged for {0}", artist.Name); } - + public void Execute(RetagArtistCommand message) { _logger.Debug("Re-tagging all files for selected artists"); @@ -386,6 +389,7 @@ namespace NzbDrone.Core.MediaFiles { WriteTags(file, false, force: true); } + _logger.ProgressInfo("All track files re-tagged for {0}", artist.Name); } } diff --git a/src/NzbDrone.Core/MediaFiles/Commands/BackendCommandAttribute.cs b/src/NzbDrone.Core/MediaFiles/Commands/BackendCommandAttribute.cs index 7e8347897..9ba649e16 100644 --- a/src/NzbDrone.Core/MediaFiles/Commands/BackendCommandAttribute.cs +++ b/src/NzbDrone.Core/MediaFiles/Commands/BackendCommandAttribute.cs @@ -5,4 +5,4 @@ namespace NzbDrone.Core.MediaFiles.Commands public class BackendCommandAttribute : Attribute { } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MediaFiles/Commands/CleanUpRecycleBinCommand.cs b/src/NzbDrone.Core/MediaFiles/Commands/CleanUpRecycleBinCommand.cs index cb8d8c3a6..15f687edd 100644 --- a/src/NzbDrone.Core/MediaFiles/Commands/CleanUpRecycleBinCommand.cs +++ b/src/NzbDrone.Core/MediaFiles/Commands/CleanUpRecycleBinCommand.cs @@ -5,4 +5,4 @@ namespace NzbDrone.Core.MediaFiles.Commands public class CleanUpRecycleBinCommand : Command { } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MediaFiles/DiskScanService.cs b/src/NzbDrone.Core/MediaFiles/DiskScanService.cs index c8ae43358..49b44606d 100644 --- a/src/NzbDrone.Core/MediaFiles/DiskScanService.cs +++ b/src/NzbDrone.Core/MediaFiles/DiskScanService.cs @@ -6,18 +6,18 @@ using System.IO.Abstractions; using System.Linq; using System.Text.RegularExpressions; using NLog; +using NzbDrone.Common; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Common.Instrumentation.Extensions; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.Commands; using NzbDrone.Core.MediaFiles.Events; +using NzbDrone.Core.MediaFiles.TrackImport; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.RootFolders; using NzbDrone.Core.Music; -using NzbDrone.Core.MediaFiles.TrackImport; -using NzbDrone.Common; +using NzbDrone.Core.RootFolders; namespace NzbDrone.Core.MediaFiles { @@ -32,7 +32,7 @@ namespace NzbDrone.Core.MediaFiles public class DiskScanService : IDiskScanService, - IExecute + IExecute { private readonly IDiskProvider _diskProvider; private readonly IMediaFileService _mediaFileService; @@ -67,6 +67,7 @@ namespace NzbDrone.Core.MediaFiles _eventAggregator = eventAggregator; _logger = logger; } + private static readonly Regex ExcludedSubFoldersRegex = new Regex(@"(?:\\|\/|^)(?:extras|@eadir|extrafanart|plex versions|\.[^\\/]+)(?:\\|\/)", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static readonly Regex ExcludedFilesRegex = new Regex(@"^\._|^Thumbs\.db$|^\.DS_store$|\.partial~$", RegexOptions.Compiled | RegexOptions.IgnoreCase); @@ -113,14 +114,14 @@ namespace NzbDrone.Core.MediaFiles var mediaFileList = FilterFiles(artist.Path, GetAudioFiles(artist.Path)).ToList(); musicFilesStopwatch.Stop(); _logger.Trace("Finished getting track files for: {0} [{1}]", artist, musicFilesStopwatch.Elapsed); - + CleanMediaFiles(artist, mediaFileList.Select(x => x.FullName).ToList()); var decisionsStopwatch = Stopwatch.StartNew(); var decisions = _importDecisionMaker.GetImportDecisions(mediaFileList, artist, filter, true); decisionsStopwatch.Stop(); _logger.Debug("Import decisions complete for: {0} [{1}]", artist, decisionsStopwatch.Elapsed); - + var importStopwatch = Stopwatch.StartNew(); _importApprovedTracks.Import(decisions, false); @@ -128,20 +129,21 @@ namespace NzbDrone.Core.MediaFiles // Now we need to make sure anything new but not approved gets inserted // Note that knownFiles will include anything imported just now var knownFiles = _mediaFileService.GetFilesWithBasePath(artist.Path); - + var newFiles = decisions .ExceptBy(x => x.Item.Path, knownFiles, x => x.Path, PathEqualityComparer.Instance) - .Select(decision => new TrackFile { - Path = decision.Item.Path, - Size = decision.Item.Size, - Modified = decision.Item.Modified, - DateAdded = DateTime.UtcNow, - Quality = decision.Item.Quality, - MediaInfo = decision.Item.FileTrackInfo.MediaInfo - }) + .Select(decision => new TrackFile + { + Path = decision.Item.Path, + Size = decision.Item.Size, + Modified = decision.Item.Modified, + DateAdded = DateTime.UtcNow, + Quality = decision.Item.Quality, + MediaInfo = decision.Item.FileTrackInfo.MediaInfo + }) .ToList(); _mediaFileService.AddMany(newFiles); - + _logger.Debug($"Inserted {newFiles.Count} new unmatched trackfiles"); // finally update info on size/modified for existing files @@ -149,28 +151,30 @@ namespace NzbDrone.Core.MediaFiles .Join(decisions, x => x.Path, x => x.Item.Path, - (file, decision) => new { + (file, decision) => new + { File = file, Item = decision.Item }, PathEqualityComparer.Instance) .Where(x => x.File.Size != x.Item.Size || - Math.Abs((x.File.Modified - x.Item.Modified).TotalSeconds) > 1 ) - .Select(x => { - x.File.Size = x.Item.Size; - x.File.Modified = x.Item.Modified; - x.File.MediaInfo = x.Item.FileTrackInfo.MediaInfo; - x.File.Quality = x.Item.Quality; - return x.File; - }) + Math.Abs((x.File.Modified - x.Item.Modified).TotalSeconds) > 1) + .Select(x => + { + x.File.Size = x.Item.Size; + x.File.Modified = x.Item.Modified; + x.File.MediaInfo = x.Item.FileTrackInfo.MediaInfo; + x.File.Quality = x.Item.Quality; + return x.File; + }) .ToList(); _mediaFileService.Update(updatedFiles); - + _logger.Debug($"Updated info for {updatedFiles.Count} known files"); RemoveEmptyArtistFolder(artist.Path); - + CompletedScanning(artist); importStopwatch.Stop(); _logger.Debug("Track import complete for: {0} [{1}]", artist, importStopwatch.Elapsed); @@ -246,10 +250,8 @@ namespace NzbDrone.Core.MediaFiles 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); } @@ -277,7 +279,6 @@ namespace NzbDrone.Core.MediaFiles var artist = _artistService.GetArtist(message.ArtistId.Value); Scan(artist, message.Filter); } - else { var allArtists = _artistService.GetAllArtists(); diff --git a/src/NzbDrone.Core/MediaFiles/DownloadedAlbumsCommandService.cs b/src/NzbDrone.Core/MediaFiles/DownloadedAlbumsCommandService.cs index e117b6b1f..0fa97b9fa 100644 --- a/src/NzbDrone.Core/MediaFiles/DownloadedAlbumsCommandService.cs +++ b/src/NzbDrone.Core/MediaFiles/DownloadedAlbumsCommandService.cs @@ -1,15 +1,13 @@ -using System.Collections.Generic; using System; +using System.Collections.Generic; using System.Linq; using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; -using NzbDrone.Core.Configuration; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.MediaFiles.Commands; -using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.MediaFiles.TrackImport; -using NzbDrone.Common.Instrumentation.Extensions; +using NzbDrone.Core.Messaging.Commands; namespace NzbDrone.Core.MediaFiles { diff --git a/src/NzbDrone.Core/MediaFiles/DownloadedTracksImportService.cs b/src/NzbDrone.Core/MediaFiles/DownloadedTracksImportService.cs index 120ed117f..274985f0a 100644 --- a/src/NzbDrone.Core/MediaFiles/DownloadedTracksImportService.cs +++ b/src/NzbDrone.Core/MediaFiles/DownloadedTracksImportService.cs @@ -104,7 +104,7 @@ namespace NzbDrone.Core.MediaFiles LogInaccessiblePathError(path); _eventAggregator.PublishEvent(new TrackImportFailedEvent(null, null, true, downloadClientItem)); - + return new List(); } diff --git a/src/NzbDrone.Core/MediaFiles/Events/AlbumImportIncompleteEvent.cs b/src/NzbDrone.Core/MediaFiles/Events/AlbumImportIncompleteEvent.cs index 08167337a..94d7b7424 100644 --- a/src/NzbDrone.Core/MediaFiles/Events/AlbumImportIncompleteEvent.cs +++ b/src/NzbDrone.Core/MediaFiles/Events/AlbumImportIncompleteEvent.cs @@ -1,7 +1,5 @@ -using System.Collections.Generic; using NzbDrone.Common.Messaging; using NzbDrone.Core.Download.TrackedDownloads; -using NzbDrone.Core.Music; namespace NzbDrone.Core.MediaFiles.Events { diff --git a/src/NzbDrone.Core/MediaFiles/Events/AlbumImportedEvent.cs b/src/NzbDrone.Core/MediaFiles/Events/AlbumImportedEvent.cs index 675c670b8..d2fed1aeb 100644 --- a/src/NzbDrone.Core/MediaFiles/Events/AlbumImportedEvent.cs +++ b/src/NzbDrone.Core/MediaFiles/Events/AlbumImportedEvent.cs @@ -30,7 +30,6 @@ namespace NzbDrone.Core.MediaFiles.Events DownloadClient = downloadClientItem.DownloadClient; DownloadId = downloadClientItem.DownloadId; } - } } } diff --git a/src/NzbDrone.Core/MediaFiles/Events/ArtistRenamedEvent.cs b/src/NzbDrone.Core/MediaFiles/Events/ArtistRenamedEvent.cs index f20f4f280..bea4ed219 100644 --- a/src/NzbDrone.Core/MediaFiles/Events/ArtistRenamedEvent.cs +++ b/src/NzbDrone.Core/MediaFiles/Events/ArtistRenamedEvent.cs @@ -1,9 +1,5 @@ using NzbDrone.Common.Messaging; using NzbDrone.Core.Music; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace NzbDrone.Core.MediaFiles.Events { diff --git a/src/NzbDrone.Core/MediaFiles/Events/ArtistScanSkippedEvent.cs b/src/NzbDrone.Core/MediaFiles/Events/ArtistScanSkippedEvent.cs index 5188ffd07..9dae29110 100644 --- a/src/NzbDrone.Core/MediaFiles/Events/ArtistScanSkippedEvent.cs +++ b/src/NzbDrone.Core/MediaFiles/Events/ArtistScanSkippedEvent.cs @@ -1,9 +1,5 @@ using NzbDrone.Common.Messaging; using NzbDrone.Core.Music; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace NzbDrone.Core.MediaFiles.Events { diff --git a/src/NzbDrone.Core/MediaFiles/Events/ArtistScannedEvent.cs b/src/NzbDrone.Core/MediaFiles/Events/ArtistScannedEvent.cs index 63f5f4656..d798cd0fd 100644 --- a/src/NzbDrone.Core/MediaFiles/Events/ArtistScannedEvent.cs +++ b/src/NzbDrone.Core/MediaFiles/Events/ArtistScannedEvent.cs @@ -1,9 +1,5 @@ using NzbDrone.Common.Messaging; using NzbDrone.Core.Music; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace NzbDrone.Core.MediaFiles.Events { diff --git a/src/NzbDrone.Core/MediaFiles/Events/TrackFileAddedEvent.cs b/src/NzbDrone.Core/MediaFiles/Events/TrackFileAddedEvent.cs index d8333833b..236365ac9 100644 --- a/src/NzbDrone.Core/MediaFiles/Events/TrackFileAddedEvent.cs +++ b/src/NzbDrone.Core/MediaFiles/Events/TrackFileAddedEvent.cs @@ -1,8 +1,4 @@ using NzbDrone.Common.Messaging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace NzbDrone.Core.MediaFiles.Events { diff --git a/src/NzbDrone.Core/MediaFiles/Events/TrackFileDeletedEvent.cs b/src/NzbDrone.Core/MediaFiles/Events/TrackFileDeletedEvent.cs index 19017e686..d28c7205d 100644 --- a/src/NzbDrone.Core/MediaFiles/Events/TrackFileDeletedEvent.cs +++ b/src/NzbDrone.Core/MediaFiles/Events/TrackFileDeletedEvent.cs @@ -1,8 +1,4 @@ using NzbDrone.Common.Messaging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace NzbDrone.Core.MediaFiles.Events { diff --git a/src/NzbDrone.Core/MediaFiles/Events/TrackImportedEvent.cs b/src/NzbDrone.Core/MediaFiles/Events/TrackImportedEvent.cs index eeb00398b..7139fd7fd 100644 --- a/src/NzbDrone.Core/MediaFiles/Events/TrackImportedEvent.cs +++ b/src/NzbDrone.Core/MediaFiles/Events/TrackImportedEvent.cs @@ -26,7 +26,6 @@ namespace NzbDrone.Core.MediaFiles.Events DownloadClient = downloadClientItem.DownloadClient; DownloadId = downloadClientItem.DownloadId; } - } } } diff --git a/src/NzbDrone.Core/MediaFiles/MediaFileAttributeService.cs b/src/NzbDrone.Core/MediaFiles/MediaFileAttributeService.cs index 9c2f157ed..cc7c400c1 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaFileAttributeService.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaFileAttributeService.cs @@ -52,7 +52,6 @@ namespace NzbDrone.Core.MediaFiles } } } - else { SetMonoPermissions(path, _configService.FileChmod); @@ -87,7 +86,6 @@ namespace NzbDrone.Core.MediaFiles { _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/MediaFileDeletionService.cs b/src/NzbDrone.Core/MediaFiles/MediaFileDeletionService.cs index 463f893e6..238f3c7e2 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaFileDeletionService.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaFileDeletionService.cs @@ -108,7 +108,10 @@ namespace NzbDrone.Core.MediaFiles foreach (var s in allArtists) { - if (s.Id == artist.Id) continue; + if (s.Id == artist.Id) + { + continue; + } if (artist.Path.IsParentPath(s.Path)) { @@ -122,6 +125,7 @@ namespace NzbDrone.Core.MediaFiles return; } } + if (_diskProvider.FolderExists(message.Artist.Path)) { _recycleBinProvider.DeleteFolder(message.Artist.Path); diff --git a/src/NzbDrone.Core/MediaFiles/MediaFileExtensions.cs b/src/NzbDrone.Core/MediaFiles/MediaFileExtensions.cs index e248a4796..8d749a98a 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaFileExtensions.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaFileExtensions.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using NzbDrone.Core.Qualities; - namespace NzbDrone.Core.MediaFiles { public static class MediaFileExtensions @@ -23,7 +22,7 @@ namespace NzbDrone.Core.MediaFiles { ".opus", Quality.Unknown }, { ".wma", Quality.WMA }, { ".wav", Quality.WAV }, - { ".wv" , Quality.WAVPACK }, + { ".wv", Quality.WAVPACK }, { ".flac", Quality.FLAC }, { ".ape", Quality.APE } }; diff --git a/src/NzbDrone.Core/MediaFiles/MediaFileRepository.cs b/src/NzbDrone.Core/MediaFiles/MediaFileRepository.cs index b8f0da825..4720d183a 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaFileRepository.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaFileRepository.cs @@ -20,7 +20,6 @@ namespace NzbDrone.Core.MediaFiles void UnlinkFilesByAlbum(int albumId); } - public class MediaFileRepository : BasicRepository, IMediaFileRepository { public MediaFileRepository(IMainDatabase database, IEventAggregator eventAggregator) @@ -84,7 +83,7 @@ namespace NzbDrone.Core.MediaFiles .Where(x => x.AlbumReleaseId == releaseId) .ToList(); } - + public List GetFilesWithBasePath(string path) { // ensure path ends with a single trailing path separator to avoid matching partial paths @@ -93,7 +92,7 @@ namespace NzbDrone.Core.MediaFiles .Where(x => x.Path.StartsWith(safePath)) .ToList(); } - + public TrackFile GetFileWithPath(string path) { return Query.Where(x => x.Path == path).SingleOrDefault(); diff --git a/src/NzbDrone.Core/MediaFiles/MediaFileService.cs b/src/NzbDrone.Core/MediaFiles/MediaFileService.cs index f446e0ca3..f794f6c7e 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaFileService.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaFileService.cs @@ -1,14 +1,14 @@ +using System; using System.Collections.Generic; using System.IO.Abstractions; using System.Linq; using NLog; +using NzbDrone.Common; +using NzbDrone.Common.Extensions; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Common; using NzbDrone.Core.Music; -using System; using NzbDrone.Core.Music.Events; -using NzbDrone.Common.Extensions; namespace NzbDrone.Core.MediaFiles { @@ -71,10 +71,10 @@ namespace NzbDrone.Core.MediaFiles _mediaFileRepository.UpdateMany(trackFiles); } - public void Delete(TrackFile trackFile, DeleteMediaFileReason reason) { _mediaFileRepository.Delete(trackFile); + // If the trackfile wasn't mapped to a track, don't publish an event if (trackFile.AlbumId > 0) { @@ -100,13 +100,16 @@ namespace NzbDrone.Core.MediaFiles var knownFiles = GetFilesWithBasePath(artist.Path); _logger.Trace($"Got {knownFiles.Count} existing files"); - if (!knownFiles.Any()) return files; + if (!knownFiles.Any()) + { + return files; + } var combined = files .Join(knownFiles, f => f.FullName, af => af.Path, - (f, af) => new { DiskFile = f, DbFile = af}, + (f, af) => new { DiskFile = f, DbFile = af }, PathEqualityComparer.Instance) .ToList(); diff --git a/src/NzbDrone.Core/MediaFiles/MediaInfoFormatter.cs b/src/NzbDrone.Core/MediaFiles/MediaInfoFormatter.cs index 11bb0cf6e..60bb6b75d 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaInfoFormatter.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaInfoFormatter.cs @@ -37,21 +37,22 @@ namespace NzbDrone.Core.MediaFiles return mediaInfo.AudioChannels; } - public static readonly Dictionary CodecNames = new Dictionary { - {Codec.MP1, "MP1"}, - {Codec.MP2, "MP2"}, - {Codec.AAC, "AAC"}, - {Codec.AACVBR, "AAC"}, - {Codec.ALAC, "ALAC"}, - {Codec.APE, "APE"}, - {Codec.FLAC, "FLAC"}, - {Codec.MP3CBR, "MP3"}, - {Codec.MP3VBR, "MP3"}, - {Codec.OGG, "OGG"}, - {Codec.OPUS, "OPUS"}, - {Codec.WAV, "PCM"}, - {Codec.WAVPACK, "WavPack"}, - {Codec.WMA, "WMA"} + public static readonly Dictionary CodecNames = new Dictionary + { + { Codec.MP1, "MP1" }, + { Codec.MP2, "MP2" }, + { Codec.AAC, "AAC" }, + { Codec.AACVBR, "AAC" }, + { Codec.ALAC, "ALAC" }, + { Codec.APE, "APE" }, + { Codec.FLAC, "FLAC" }, + { Codec.MP3CBR, "MP3" }, + { Codec.MP3VBR, "MP3" }, + { Codec.OGG, "OGG" }, + { Codec.OPUS, "OPUS" }, + { Codec.WAV, "PCM" }, + { Codec.WAVPACK, "WavPack" }, + { Codec.WMA, "WMA" } }; public static string FormatAudioCodec(MediaInfoModel mediaInfo) @@ -68,7 +69,7 @@ namespace NzbDrone.Core.MediaFiles .Message("Unknown audio format: '{0}'.", string.Join(", ", mediaInfo.AudioFormat)) .WriteSentryWarn("UnknownAudioFormat", mediaInfo.AudioFormat) .Write(); - + return "Unknown"; } } diff --git a/src/NzbDrone.Core/MediaFiles/RecycleBinProvider.cs b/src/NzbDrone.Core/MediaFiles/RecycleBinProvider.cs index f2afe139e..a34933565 100644 --- a/src/NzbDrone.Core/MediaFiles/RecycleBinProvider.cs +++ b/src/NzbDrone.Core/MediaFiles/RecycleBinProvider.cs @@ -7,8 +7,6 @@ using NzbDrone.Common.Extensions; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.Commands; using NzbDrone.Core.Messaging.Commands; -using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Music.Events; namespace NzbDrone.Core.MediaFiles { @@ -27,7 +25,6 @@ namespace NzbDrone.Core.MediaFiles private readonly IConfigService _configService; private readonly Logger _logger; - public RecycleBinProvider(IDiskTransferService diskTransferService, IDiskProvider diskProvider, IConfigService configService, @@ -50,7 +47,6 @@ namespace NzbDrone.Core.MediaFiles _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 +82,6 @@ namespace NzbDrone.Core.MediaFiles _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/RenameTrackFileService.cs b/src/NzbDrone.Core/MediaFiles/RenameTrackFileService.cs index 0e5fa572f..bee38a49b 100644 --- a/src/NzbDrone.Core/MediaFiles/RenameTrackFileService.cs +++ b/src/NzbDrone.Core/MediaFiles/RenameTrackFileService.cs @@ -10,8 +10,8 @@ using NzbDrone.Core.MediaFiles.Commands; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Organizer; using NzbDrone.Core.Music; +using NzbDrone.Core.Organizer; namespace NzbDrone.Core.MediaFiles { @@ -56,7 +56,6 @@ namespace NzbDrone.Core.MediaFiles public List GetRenamePreviews(int artistId) { - var artist = _artistService.GetArtist(artistId); var tracks = _trackService.GetTracksByArtist(artistId); var files = _mediaFileService.GetFilesByArtist(artistId); @@ -69,7 +68,6 @@ namespace NzbDrone.Core.MediaFiles public List GetRenamePreviews(int artistId, int albumId) { - var artist = _artistService.GetArtist(artistId); var tracks = _trackService.GetTracksByAlbum(albumId); var files = _mediaFileService.GetFilesByAlbum(albumId); @@ -153,7 +151,6 @@ namespace NzbDrone.Core.MediaFiles public void Execute(RenameFilesCommand message) { - var artist = _artistService.GetArtist(message.ArtistId); var trackFiles = _mediaFileService.Get(message.Files); @@ -164,7 +161,6 @@ namespace NzbDrone.Core.MediaFiles public void Execute(RenameArtistCommand message) { - _logger.Debug("Renaming all files for selected artist"); var artistToRename = _artistService.GetArtists(message.ArtistIds); diff --git a/src/NzbDrone.Core/MediaFiles/SameFilenameException.cs b/src/NzbDrone.Core/MediaFiles/SameFilenameException.cs index c2a8cbd1f..d191bf55d 100644 --- a/src/NzbDrone.Core/MediaFiles/SameFilenameException.cs +++ b/src/NzbDrone.Core/MediaFiles/SameFilenameException.cs @@ -6,7 +6,8 @@ namespace NzbDrone.Core.MediaFiles { 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 879cd9ca2..a3bb71acc 100644 --- a/src/NzbDrone.Core/MediaFiles/TorrentInfo/TorrentFileInfoReader.cs +++ b/src/NzbDrone.Core/MediaFiles/TorrentInfo/TorrentFileInfoReader.cs @@ -2,12 +2,12 @@ namespace NzbDrone.Core.MediaFiles.TorrentInfo { - public interface ITorrentFileInfoReader + 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/TrackFile.cs b/src/NzbDrone.Core/MediaFiles/TrackFile.cs index 2b353541f..d606a3273 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackFile.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackFile.cs @@ -1,11 +1,11 @@ -using Marr.Data; -using NzbDrone.Core.Datastore; -using NzbDrone.Core.Music; -using NzbDrone.Core.Qualities; using System; using System.Collections.Generic; +using Marr.Data; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Datastore; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.MediaFiles { @@ -21,7 +21,7 @@ namespace NzbDrone.Core.MediaFiles public QualityModel Quality { get; set; } public MediaInfoModel MediaInfo { get; set; } public int AlbumId { get; set; } - + // These are queried from the database public LazyLoaded> Tracks { get; set; } public LazyLoaded Artist { get; set; } diff --git a/src/NzbDrone.Core/MediaFiles/TrackFileMoveResult.cs b/src/NzbDrone.Core/MediaFiles/TrackFileMoveResult.cs index 8b4b3d854..b115e3b65 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackFileMoveResult.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackFileMoveResult.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System.Collections.Generic; namespace NzbDrone.Core.MediaFiles { diff --git a/src/NzbDrone.Core/MediaFiles/TrackFileMovingService.cs b/src/NzbDrone.Core/MediaFiles/TrackFileMovingService.cs index 17e9d285f..b53d09e03 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackFileMovingService.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackFileMovingService.cs @@ -1,3 +1,6 @@ +using System; +using System.Collections.Generic; +using System.IO; using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.EnsureThat; @@ -9,11 +12,6 @@ using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Music; using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; namespace NzbDrone.Core.MediaFiles { @@ -62,7 +60,6 @@ namespace NzbDrone.Core.MediaFiles public TrackFile MoveTrackFile(TrackFile trackFile, Artist artist) { - var tracks = _trackService.GetTracksByFileId(trackFile.Id); var album = _albumService.GetAlbum(trackFile.AlbumId); var newFileName = _buildFileNames.BuildTrackFileName(tracks, artist, album, trackFile); @@ -77,7 +74,6 @@ namespace NzbDrone.Core.MediaFiles public TrackFile MoveTrackFile(TrackFile trackFile, LocalTrack localTrack) { - var newFileName = _buildFileNames.BuildTrackFileName(localTrack.Tracks, localTrack.Artist, localTrack.Album, trackFile); var filePath = _buildFileNames.BuildTrackFilePath(localTrack.Artist, localTrack.Album, newFileName, Path.GetExtension(localTrack.Path)); @@ -107,7 +103,6 @@ namespace NzbDrone.Core.MediaFiles private TrackFile TransferFile(TrackFile trackFile, Artist artist, List tracks, string destinationFilePath, TransferMode mode) { - Ensure.That(trackFile, () => trackFile).IsNotNull(); Ensure.That(artist, () => artist).IsNotNull(); Ensure.That(destinationFilePath, () => destinationFilePath).IsValidPath(); @@ -141,7 +136,6 @@ namespace NzbDrone.Core.MediaFiles _mediaFileAttributeService.SetFolderLastWriteTime(albumFolder, trackFile.DateAdded); } } - catch (Exception ex) { _logger.Warn(ex, "Unable to set last write time"); diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/Aggregation/AggregationFailedException.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/Aggregation/AggregationFailedException.cs index a3c4a2682..6d31c819e 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/Aggregation/AggregationFailedException.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/Aggregation/AggregationFailedException.cs @@ -5,19 +5,23 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.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/TrackImport/Aggregation/AggregationService.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/Aggregation/AggregationService.cs index 4659c73a2..b9674bf9a 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/Aggregation/AggregationService.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/Aggregation/AggregationService.cs @@ -73,7 +73,6 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Aggregation { _logger.Warn(ex, ex.Message); } - } return localAlbum; diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/Aggregation/Aggregators/AggregateFilenameInfo.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/Aggregation/Aggregators/AggregateFilenameInfo.cs index b09d2d630..dec828cc9 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/Aggregation/Aggregators/AggregateFilenameInfo.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/Aggregation/Aggregators/AggregateFilenameInfo.cs @@ -13,7 +13,8 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Aggregation.Aggregators { private readonly Logger _logger; - private static readonly List> charsAndSeps = new List> { + private static readonly List> CharsAndSeps = new List> + { Tuple.Create(@"a-z0-9,\(\)\.&'’\s", @"\s_-"), Tuple.Create(@"a-z0-9,\(\)\.\&'’_", @"\s-") }; @@ -26,16 +27,17 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Aggregation.Aggregators var track = $@"(?\d+)"; var title = $@"(?[{chars}]+)"; var tag = $@"(?<tag>[{chars}]+)"; - - return new [] { + + return new[] + { new Regex($@"^{track}{sep1}{artist}{sepn}{title}{sepn}{tag}$", RegexOptions.IgnoreCase), new Regex($@"^{track}{sep1}{artist}{sepn}{tag}{sepn}{title}$", RegexOptions.IgnoreCase), new Regex($@"^{track}{sep1}{artist}{sepn}{title}$", RegexOptions.IgnoreCase), - + new Regex($@"^{artist}{sep1}{tag}{sepn}{track}{sepn}{title}$", RegexOptions.IgnoreCase), new Regex($@"^{artist}{sep1}{track}{sepn}{title}{sepn}{tag}$", RegexOptions.IgnoreCase), new Regex($@"^{artist}{sep1}{track}{sepn}{title}$", RegexOptions.IgnoreCase), - + new Regex($@"^{artist}{sep1}{title}{sepn}{tag}$", RegexOptions.IgnoreCase), new Regex($@"^{artist}{sep1}{tag}{sepn}{title}$", RegexOptions.IgnoreCase), new Regex($@"^{artist}{sep1}{title}$", RegexOptions.IgnoreCase), @@ -43,7 +45,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Aggregation.Aggregators new Regex($@"^{track}{sep1}{title}$", RegexOptions.IgnoreCase), new Regex($@"^{track}{sep1}{tag}{sepn}{title}$", RegexOptions.IgnoreCase), new Regex($@"^{track}{sep1}{title}{sepn}{tag}$", RegexOptions.IgnoreCase), - + new Regex($@"^{title}$", RegexOptions.IgnoreCase), }; } @@ -52,7 +54,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Aggregation.Aggregators { _logger = logger; } - + public LocalAlbumRelease Aggregate(LocalAlbumRelease release, bool others) { var tracks = release.LocalTracks; @@ -61,7 +63,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Aggregation.Aggregators || tracks.Count(x => x.FileTrackInfo.DiscNumber == 0) > 0) { _logger.Debug("Missing data in tags, trying filename augmentation"); - foreach (var charSep in charsAndSeps) + foreach (var charSep in CharsAndSeps) { foreach (var pattern in Patterns(charSep.Item1, charSep.Item2)) { @@ -94,6 +96,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Aggregation.Aggregators return null; } } + return matches; } @@ -105,7 +108,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Aggregation.Aggregators private void ApplyMatches(Dictionary<LocalTrack, Match> matches, Regex pattern) { _logger.Debug("Got filename match with regex {0}", pattern); - + var keys = pattern.GetGroupNames(); var someMatch = matches.First().Value; @@ -136,6 +139,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Aggregation.Aggregators else { _logger.Trace("Abort - both artist and title vary between matches"); + // both vary, abort return; } @@ -176,8 +180,9 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Aggregation.Aggregators _logger.Debug("Got disc number from filename: {0}", tracknum / 100); tracknum = tracknum % 100; } + _logger.Debug("Got track number from filename: {0}", tracknum); - track.FileTrackInfo.TrackNumbers = new [] { tracknum }; + track.FileTrackInfo.TrackNumbers = new[] { tracknum }; } } } diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/CandidateAlbumRelease.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/CandidateAlbumRelease.cs index bfeb739fb..267d9b5cc 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/CandidateAlbumRelease.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/CandidateAlbumRelease.cs @@ -8,15 +8,14 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification public CandidateAlbumRelease() { } - + public CandidateAlbumRelease(AlbumRelease release) { AlbumRelease = release; ExistingTracks = new List<TrackFile>(); } - + public AlbumRelease AlbumRelease { get; set; } public List<TrackFile> ExistingTracks { get; set; } } } - diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/Distance.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/Distance.cs index 565fa260f..b0888fa33 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/Distance.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/Distance.cs @@ -7,10 +7,8 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification { public class Distance { - private Dictionary<string, List<double>> penalties; - // from beets default config - private static readonly Dictionary<string, double> weights = new Dictionary<string, double> + private static readonly Dictionary<string, double> Weights = new Dictionary<string, double> { { "source", 2.0 }, { "artist", 3.0 }, @@ -33,32 +31,34 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification { "recording_id", 10.0 }, }; + private Dictionary<string, List<double>> _penalties; + public Distance() { - penalties = new Dictionary<string, List<double>>(15); + _penalties = new Dictionary<string, List<double>>(15); } - public Dictionary<string, List<double>> Penalties => penalties; - public string Reasons => penalties.Count(x => x.Value.Max() > 0.0) > 0 ? "[" + string.Join(", ", Penalties.Where(x => x.Value.Max() > 0.0).Select(x => x.Key.Replace('_', ' '))) + "]" : string.Empty; + public Dictionary<string, List<double>> Penalties => _penalties; + public string Reasons => _penalties.Count(x => x.Value.Max() > 0.0) > 0 ? "[" + string.Join(", ", Penalties.Where(x => x.Value.Max() > 0.0).Select(x => x.Key.Replace('_', ' '))) + "]" : string.Empty; private double MaxDistance(Dictionary<string, List<double>> penalties) { - return penalties.Select(x => x.Value.Count * weights[x.Key]).Sum(); + return penalties.Select(x => x.Value.Count * Weights[x.Key]).Sum(); } public double MaxDistance() { - return MaxDistance(penalties); + return MaxDistance(_penalties); } private double RawDistance(Dictionary<string, List<double>> penalties) { - return penalties.Select(x => x.Value.Sum() * weights[x.Key]).Sum(); + return penalties.Select(x => x.Value.Sum() * Weights[x.Key]).Sum(); } - + public double RawDistance() { - return RawDistance(penalties); + return RawDistance(_penalties); } private double NormalizedDistance(Dictionary<string, List<double>> penalties) @@ -69,23 +69,23 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification public double NormalizedDistance() { - return NormalizedDistance(penalties); + return NormalizedDistance(_penalties); } public double NormalizedDistanceExcluding(List<string> keys) { - return NormalizedDistance(penalties.Where(x => !keys.Contains(x.Key)).ToDictionary(y => y.Key, y => y.Value)); + return NormalizedDistance(_penalties.Where(x => !keys.Contains(x.Key)).ToDictionary(y => y.Key, y => y.Value)); } public void Add(string key, double dist) { - if (penalties.ContainsKey(key)) + if (_penalties.ContainsKey(key)) { - penalties[key].Add(dist); + _penalties[key].Add(dist); } else { - penalties[key] = new List<double> { dist }; + _penalties[key] = new List<double> { dist }; } } @@ -117,7 +117,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification { char[] arr = input.ToLower().RemoveAccent().ToCharArray(); - arr = Array.FindAll<char>(arr, c => (char.IsLetterOrDigit(c))); + arr = Array.FindAll<char>(arr, c => char.IsLetterOrDigit(c)); return new string(arr); } @@ -127,7 +127,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification // Adds a penaltly based on the distance between value and target var cleanValue = Clean(value); var cleanTarget = Clean(target); - + if (cleanValue.IsNullOrWhiteSpace() && cleanTarget.IsNotNullOrWhiteSpace()) { Add(key, 1.0); @@ -147,14 +147,16 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification Add(key, expr ? 1.0 : 0.0); } - public void AddEquality<T>(string key, T value, List<T> options) where T : IEquatable<T> + public void AddEquality<T>(string key, T value, List<T> options) + where T : IEquatable<T> { Add(key, options.Contains(value) ? 0.0 : 1.0); } - public void AddPriority<T>(string key, T value, List<T> options) where T : IEquatable<T> + public void AddPriority<T>(string key, T value, List<T> options) + where T : IEquatable<T> { - var unit = 1.0 / (options.Count > 0 ? (double) options.Count : 1.0); + var unit = 1.0 / (options.Count > 0 ? options.Count : 1.0); var index = options.IndexOf(value); if (index == -1) { @@ -166,9 +168,10 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification } } - public void AddPriority<T>(string key, List<T> values, List<T> options) where T : IEquatable<T> + public void AddPriority<T>(string key, List<T> values, List<T> options) + where T : IEquatable<T> { - for(int i = 0; i < options.Count; i++) + for (int i = 0; i < options.Count; i++) { if (values.Contains(options[i])) { diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/IdentificationService.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/IdentificationService.cs index 2b56e7d11..12b848298 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/IdentificationService.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/IdentificationService.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.IO; using System.Linq; using Newtonsoft.Json; using NLog; @@ -60,26 +59,31 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification _logger = logger; } - private readonly List<IsoCountry> preferredCountries = new List<string> { + private readonly List<IsoCountry> _preferredCountries = new List<string> + { "United States", "United Kingdom", "Europe", "[Worldwide]" }.Select(x => IsoCountries.Find(x)).ToList(); - private readonly List<string> VariousArtistNames = new List<string> { "various artists", "various", "va", "unknown" }; - private readonly List<string> VariousArtistIds = new List<string> { "89ad4ac3-39f7-470e-963a-56509c546377" }; + private readonly List<string> _variousArtistNames = new List<string> { "various artists", "various", "va", "unknown" }; + private readonly List<string> _variousArtistIds = new List<string> { "89ad4ac3-39f7-470e-963a-56509c546377" }; private void LogTestCaseOutput(List<LocalTrack> localTracks, Artist artist, Album album, AlbumRelease release, bool newDownload, bool singleRelease) { - var trackData = localTracks.Select(x => new BasicLocalTrack { - Path = x.Path, - FileTrackInfo = x.FileTrackInfo - }); - var options = new IdTestCase { - ExpectedMusicBrainzReleaseIds = new List<string> {"expected-id-1", "expected-id-2", "..."}, - LibraryArtists = new List<ArtistTestCase> { - new ArtistTestCase { + var trackData = localTracks.Select(x => new BasicLocalTrack + { + Path = x.Path, + FileTrackInfo = x.FileTrackInfo + }); + var options = new IdTestCase + { + ExpectedMusicBrainzReleaseIds = new List<string> { "expected-id-1", "expected-id-2", "..." }, + LibraryArtists = new List<ArtistTestCase> + { + new ArtistTestCase + { Artist = artist?.Metadata.Value.ForeignArtistId ?? "expected-artist-id (dev: don't forget to add metadata profile)", MetadataProfile = artist?.MetadataProfile.Value } @@ -92,10 +96,10 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification Tracks = trackData.ToList() }; - var SerializerSettings = Json.GetSerializerSettings(); - SerializerSettings.Formatting = Formatting.None; + var serializerSettings = Json.GetSerializerSettings(); + serializerSettings.Formatting = Formatting.None; - var output = JsonConvert.SerializeObject(options, SerializerSettings); + var output = JsonConvert.SerializeObject(options, serializerSettings); _logger.Debug($"*** IdentificationService TestCaseGenerator ***\n{output}"); } @@ -106,7 +110,6 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification // 2 get candidates given specified artist, album and release. Candidates can include extra files already on disk. // 3 find best candidate // 4 If best candidate worse than threshold, try fingerprinting - var watch = System.Diagnostics.Stopwatch.StartNew(); _logger.Debug("Starting track identification"); @@ -115,7 +118,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification List<LocalAlbumRelease> releases = null; if (singleRelease) { - releases = new List<LocalAlbumRelease>{ new LocalAlbumRelease(localTracks) }; + releases = new List<LocalAlbumRelease> { new LocalAlbumRelease(localTracks) }; } else { @@ -123,7 +126,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification } _logger.Debug($"Sorted {localTracks.Count} tracks into {releases.Count} releases in {watch.ElapsedMilliseconds}ms"); - + foreach (var localRelease in releases) { try @@ -134,6 +137,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification { _logger.Warn($"Augmentation failed for {localRelease}"); } + IdentifyRelease(localRelease, artist, album, release, newDownload, includeExisting); } @@ -161,7 +165,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification .OrderByDescending(x => x.Value.Item2.NormalizedDistance()) .First() .Value.Item2.NormalizedDistance() ?? 1.0; - + if (localAlbumRelease.Distance.NormalizedDistance() > 0.15 || localAlbumRelease.TrackMapping.LocalExtra.Any() || localAlbumRelease.TrackMapping.MBExtra.Any() || @@ -177,15 +181,16 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification { var scanned = trackfiles.Join(localRelease.LocalTracks, t => t.Path, l => l.Path, (track, localTrack) => localTrack); var toScan = trackfiles.ExceptBy(t => t.Path, scanned, s => s.Path, StringComparer.InvariantCulture); - var localTracks = scanned.Concat(toScan.Select(x => new LocalTrack { - Path = x.Path, - Size = x.Size, - Modified = x.Modified, - FileTrackInfo = _audioTagService.ReadTags(x.Path), - ExistingFile = true, - AdditionalFile = true, - Quality = x.Quality - })) + var localTracks = scanned.Concat(toScan.Select(x => new LocalTrack + { + Path = x.Path, + Size = x.Size, + Modified = x.Modified, + FileTrackInfo = _audioTagService.ReadTags(x.Path), + ExistingFile = true, + AdditionalFile = true, + Quality = x.Quality + })) .ToList(); localTracks.ForEach(x => _augmentingService.Augment(x, true)); @@ -197,7 +202,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification { var watch = System.Diagnostics.Stopwatch.StartNew(); bool fingerprinted = false; - + var candidateReleases = GetCandidatesFromTags(localAlbumRelease, artist, album, release, includeExisting); if (candidateReleases.Count == 0 && FingerprintingAllowed(newDownload)) { @@ -223,7 +228,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification .DistinctBy(x => x.Path), localAlbumRelease); _logger.Debug($"Retrieved {allTracks.Count} possible tracks in {watch.ElapsedMilliseconds}ms"); - + GetBestRelease(localAlbumRelease, candidateReleases, allTracks, allLocalTracks); // If result isn't great and we haven't fingerprinted, try that @@ -242,7 +247,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification candidateReleases.AddRange(newCandidates); allTracks.AddRange(_trackService.GetTracksByReleases(newCandidates.Select(x => x.AlbumRelease.Id).ToList())); allLocalTracks.AddRange(ToLocalTrack(newCandidates - .SelectMany(x => x.ExistingTracks) + .SelectMany(x => x.ExistingTracks) .DistinctBy(x => x.Path) .ExceptBy(x => x.Path, allLocalTracks, x => x.Path, PathEqualityComparer.Instance), localAlbumRelease)); @@ -250,7 +255,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification // fingerprint all the local files in candidates we might be matching against _fingerprintingService.Lookup(allLocalTracks, 0.5); - + GetBestRelease(localAlbumRelease, candidateReleases, allTracks, allLocalTracks); } @@ -264,22 +269,21 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification public List<CandidateAlbumRelease> GetCandidatesFromTags(LocalAlbumRelease localAlbumRelease, Artist artist, Album album, AlbumRelease release, bool includeExisting) { var watch = System.Diagnostics.Stopwatch.StartNew(); - + // Generally artist, album and release are null. But if they're not then limit candidates appropriately. // We've tried to make sure that tracks are all for a single release. - List<CandidateAlbumRelease> candidateReleases; // if we have a release ID, use that AlbumRelease tagMbidRelease = null; List<CandidateAlbumRelease> tagCandidate = null; - + var releaseIds = localAlbumRelease.LocalTracks.Select(x => x.FileTrackInfo.ReleaseMBId).Distinct().ToList(); if (releaseIds.Count == 1 && releaseIds[0].IsNotNullOrWhiteSpace()) { _logger.Debug("Selecting release from consensus ForeignReleaseId [{0}]", releaseIds[0]); tagMbidRelease = _releaseService.GetReleaseByForeignReleaseId(releaseIds[0], true); - + if (tagMbidRelease != null) { tagCandidate = GetCandidatesByRelease(new List<AlbumRelease> { tagMbidRelease }, includeExisting); @@ -324,7 +328,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification } else { - candidateReleases = GetCandidates(localAlbumRelease, includeExisting); + candidateReleases = GetCandidates(localAlbumRelease, includeExisting); } } @@ -342,10 +346,11 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification .Distinct() .ToDictionary(id => id, id => includeExisting ? _mediaFileService.GetFilesByAlbum(id) : new List<TrackFile>()); - return releases.Select(x => new CandidateAlbumRelease { - AlbumRelease = x, - ExistingTracks = albumTracks[x.AlbumId] - }).ToList(); + return releases.Select(x => new CandidateAlbumRelease + { + AlbumRelease = x, + ExistingTracks = albumTracks[x.AlbumId] + }).ToList(); } private List<CandidateAlbumRelease> GetCandidatesByAlbum(LocalAlbumRelease localAlbumRelease, Album album, bool includeExisting) @@ -361,7 +366,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification { _logger.Trace("Getting candidates for {0}", artist); var candidateReleases = new List<CandidateAlbumRelease>(); - + var albumTag = MostCommon(localAlbumRelease.LocalTracks.Select(x => x.FileTrackInfo.AlbumTitle)) ?? ""; if (albumTag.IsNotNullOrWhiteSpace()) { @@ -387,7 +392,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification } var candidateReleases = new List<CandidateAlbumRelease>(); - + var artistTag = MostCommon(localAlbumRelease.LocalTracks.Select(x => x.FileTrackInfo.ArtistTitle)) ?? ""; if (artistTag.IsNotNullOrWhiteSpace()) { @@ -420,11 +425,12 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification allReleases = allReleases.Where(x => x.Album.Value.ArtistMetadataId == artist.ArtistMetadataId).ToList(); } - return GetCandidatesByRelease(allReleases.Select(x => new { - Release = x, - TrackCount = x.TrackCount, - CommonProportion = x.Tracks.Value.Select(y => y.ForeignRecordingId).Intersect(recordingIds).Count() / localAlbumRelease.TrackCount - }) + return GetCandidatesByRelease(allReleases.Select(x => new + { + Release = x, + TrackCount = x.TrackCount, + CommonProportion = x.Tracks.Value.Select(y => y.ForeignRecordingId).Intersect(recordingIds).Count() / localAlbumRelease.TrackCount + }) .Where(x => x.CommonProportion > 0.6) .ToList() .OrderBy(x => Math.Abs(x.TrackCount - localAlbumRelease.TrackCount)) @@ -442,7 +448,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification private void GetBestRelease(LocalAlbumRelease localAlbumRelease, List<CandidateAlbumRelease> candidateReleases, List<Track> dbTracks, List<LocalTrack> extraTracksOnDisk) { var watch = System.Diagnostics.Stopwatch.StartNew(); - + _logger.Debug("Matching {0} track files against {1} candidates", localAlbumRelease.TrackCount, candidateReleases.Count); _logger.Trace("Processing files:\n{0}", string.Join("\n", localAlbumRelease.LocalTracks.Select(x => x.Path))); @@ -457,14 +463,18 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification var extraTrackPaths = candidateRelease.ExistingTracks.Select(x => x.Path).ToList(); var extraTracks = extraTracksOnDisk.Where(x => extraTrackPaths.Contains(x.Path)).ToList(); var allLocalTracks = localAlbumRelease.LocalTracks.Concat(extraTracks).DistinctBy(x => x.Path).ToList(); - + var mapping = MapReleaseTracks(allLocalTracks, dbTracks.Where(x => x.AlbumReleaseId == release.Id).ToList()); var distance = AlbumReleaseDistance(allLocalTracks, release, mapping); var currDistance = distance.NormalizedDistance(); rwatch.Stop(); _logger.Debug("Release {0} [{1} tracks] has distance {2} vs best distance {3} [{4}ms]", - release, release.TrackCount, currDistance, bestDistance, rwatch.ElapsedMilliseconds); + release, + release.TrackCount, + currDistance, + bestDistance, + rwatch.ElapsedMilliseconds); if (currDistance < bestDistance) { bestDistance = currDistance; @@ -512,10 +522,10 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification result.Mapping.Add(localTracks[pair.Item1], Tuple.Create(mbTracks[pair.Item2], distances[pair.Item1, pair.Item2])); _logger.Trace("Mapped {0} to {1}, dist: {2}", localTracks[pair.Item1], mbTracks[pair.Item2], costs[pair.Item1, pair.Item2]); } - + result.LocalExtra = localTracks.Except(result.Mapping.Keys).ToList(); _logger.Trace($"Unmapped files:\n{string.Join("\n", result.LocalExtra)}"); - + result.MBExtra = mbTracks.Except(result.Mapping.Values.Select(x => x.Item1)).ToList(); _logger.Trace($"Missing tracks:\n{string.Join("\n", result.MBExtra)}"); @@ -546,7 +556,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification dist.AddString("track_title", localTrack.FileTrackInfo.CleanTitle ?? "", mbTrack.Title); if (includeArtist && localTrack.FileTrackInfo.ArtistTitle.IsNotNullOrWhiteSpace() - && !VariousArtistNames.Any(x => x.Equals(localTrack.FileTrackInfo.ArtistTitle, StringComparison.InvariantCultureIgnoreCase))) + && !_variousArtistNames.Any(x => x.Equals(localTrack.FileTrackInfo.ArtistTitle, StringComparison.InvariantCultureIgnoreCase))) { dist.AddString("track_artist", localTrack.FileTrackInfo.ArtistTitle, mbTrack.ArtistMetadata.Value.Name); } @@ -576,7 +586,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification { var dist = new Distance(); - if (!VariousArtistIds.Contains(release.Album.Value.ArtistMetadata.Value.ForeignArtistId)) + if (!_variousArtistIds.Contains(release.Album.Value.ArtistMetadata.Value.ForeignArtistId)) { var artist = MostCommon(localTracks.Select(x => x.FileTrackInfo.ArtistTitle)) ?? ""; dist.AddString("artist", artist, release.Album.Value.ArtistMetadata.Value.Name); @@ -584,6 +594,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification } var title = MostCommon(localTracks.Select(x => x.FileTrackInfo.AlbumTitle)) ?? ""; + // Use the album title since the differences in release titles can cause confusion and // aren't always correct in the tags dist.AddString("album", title, release.Album.Value.Title); @@ -621,6 +632,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification var diff_max = Math.Abs(DateTime.Now.Year - remoteYear); dist.AddRatio("year", diff, diff_max); } + _logger.Trace($"year: {localYear} vs {release.Album.Value.ReleaseDate?.Year} or {release.ReleaseDate?.Year}; {dist.NormalizedDistance()}"); } @@ -633,10 +645,10 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification dist.AddEquality("country", country.Name, release.Country); _logger.Trace("country: {0} vs {1}; {2}", country.Name, string.Join(", ", release.Country), dist.NormalizedDistance()); } - else if (preferredCountries.Count > 0) + else if (_preferredCountries.Count > 0) { - dist.AddPriority("country", release.Country, preferredCountries.Select(x => x.Name).ToList()); - _logger.Trace("country priority: {0} vs {1}; {2}", string.Join(", ", preferredCountries.Select(x => x.Name)), string.Join(", ", release.Country), dist.NormalizedDistance()); + dist.AddPriority("country", release.Country, _preferredCountries.Select(x => x.Name).ToList()); + _logger.Trace("country priority: {0} vs {1}; {2}", string.Join(", ", _preferredCountries.Select(x => x.Name)), string.Join(", ", release.Country), dist.NormalizedDistance()); } } else @@ -658,7 +670,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification dist.AddString("album_disambiguation", disambig, release.Disambiguation); _logger.Trace("album_disambiguation: {0} vs {1}; {2}", disambig, release.Disambiguation, dist.NormalizedDistance()); } - + var mbAlbumId = MostCommon(localTracks.Select(x => x.FileTrackInfo.ReleaseMBId)); if (mbAlbumId.IsNotNullOrWhiteSpace()) { @@ -671,6 +683,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification { dist.Add("tracks", pair.Value.Item2.NormalizedDistance()); } + _logger.Trace("after trackMapping: {0}", dist.NormalizedDistance()); // missing tracks @@ -678,6 +691,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification { dist.Add("missing_tracks", 1.0); } + _logger.Trace("after missing tracks: {0}", dist.NormalizedDistance()); // unmatched tracks @@ -685,6 +699,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification { dist.Add("unmatched_tracks", 1.0); } + _logger.Trace("after unmatched tracks: {0}", dist.NormalizedDistance()); return dist; diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/IdentificationTestCase.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/IdentificationTestCase.cs index 5ad2aa8e2..0e2dabb40 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/IdentificationTestCase.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/IdentificationTestCase.cs @@ -21,7 +21,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification public string Path { get; set; } public List<string> AcoustIdResults { get; set; } } - + public class IdTestCase { public List<string> ExpectedMusicBrainzReleaseIds { get; set; } @@ -35,4 +35,3 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification public List<AcoustIdTestCase> Fingerprints { get; set; } } } - diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/Munkres.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/Munkres.cs index 651fb21a1..02348ee10 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/Munkres.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/Munkres.cs @@ -26,9 +26,11 @@ */ +#pragma warning disable SX1101, SA1108, SA1119, SA1124, SA1200, SA1208, SA1214, SA1314, SA1403, SA1503, SA1514, SA1515, SA1519, SX1309 + using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; namespace NzbDrone.Core.MediaFiles.TrackImport.Identification { @@ -54,12 +56,12 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification n = C.GetLength(0); nrow_orig = costMatrix.GetLength(0); ncol_orig = costMatrix.GetLength(1); - + C_orig = C.Clone() as double[,]; RowCover = new int[n]; ColCover = new int[n]; M = new int[n, n]; - path = new int[2*n + 1, 2]; + path = new int[(2 * n) + 1, 2]; step = 1; } @@ -87,6 +89,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification } } } + return value; } } @@ -111,6 +114,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification outp[row, col] = matrix[row, col]; } } + return outp; } @@ -130,16 +134,18 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification min_in_row = C[r, c]; } } + for (int c = 0; c < n; c++) { C[r, c] -= min_in_row; } } + step = 2; } - //Find a zero (Z) in the resulting matrix. If there is no starred - //zero in its row or column, star Z. Repeat for each element in the + //Find a zero (Z) in the resulting matrix. If there is no starred + //zero in its row or column, star Z. Repeat for each element in the //matrix. Go to Step 3. private void step_two(ref int step) { @@ -155,19 +161,22 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification } } } + for (int r = 0; r < n; r++) { RowCover[r] = 0; } + for (int c = 0; c < n; c++) { ColCover[c] = 0; } + step = 3; } - //Cover each column containing a starred zero. If K columns are covered, - //the starred zeros describe a complete set of unique assignments. In this + //Cover each column containing a starred zero. If K columns are covered, + //the starred zeros describe a complete set of unique assignments. In this //case, Go to DONE, otherwise, Go to Step 4. private void step_three(ref int step) { @@ -191,6 +200,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification colcount += 1; } } + if (colcount >= n) { step = 7; @@ -221,12 +231,14 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification col = c; done = true; } + c += 1; if (c >= n || done) { break; } } + r += 1; if (r >= n) { @@ -245,6 +257,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification tmp = true; } } + return tmp; } @@ -260,10 +273,10 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification } } - //Find a noncovered zero and prime it. If there is no starred zero - //in the row containing this primed zero, Go to Step 5. Otherwise, - //cover this row and uncover the column containing the starred zero. - //Continue in this manner until there are no uncovered zeros left. + //Find a noncovered zero and prime it. If there is no starred zero + //in the row containing this primed zero, Go to Step 5. Otherwise, + //cover this row and uncover the column containing the starred zero. + //Continue in this manner until there are no uncovered zeros left. //Save the smallest uncovered value and Go to Step 6. private void step_four(ref int step) { @@ -345,6 +358,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification { RowCover[r] = 0; } + for (int c = 0; c < n; c++) { ColCover[c] = 0; @@ -365,13 +379,12 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification } } - - //Construct a series of alternating primed and starred zeros as follows. - //Let Z0 represent the uncovered primed zero found in Step 4. Let Z1 denote - //the starred zero in the column of Z0 (if any). Let Z2 denote the primed zero - //in the row of Z1 (there will always be one). Continue until the series - //terminates at a primed zero that has no starred zero in its column. - //Unstar each starred zero of the series, star each primed zero of the series, + //Construct a series of alternating primed and starred zeros as follows. + //Let Z0 represent the uncovered primed zero found in Step 4. Let Z1 denote + //the starred zero in the column of Z0 (if any). Let Z2 denote the primed zero + //in the row of Z1 (there will always be one). Continue until the series + //terminates at a primed zero that has no starred zero in its column. + //Unstar each starred zero of the series, star each primed zero of the series, //erase all primes and uncover every line in the matrix. Return to Step 3. private void step_five(ref int step) { @@ -396,6 +409,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification { done = true; } + if (!done) { find_prime_in_row(path[path_count - 1, 0], ref c); @@ -404,6 +418,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification path[path_count - 1, 1] = c; } } + augment_path(); clear_covers(); erase_primes(); @@ -428,8 +443,8 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification } } - //Add the value found in Step 4 to every element of each covered row, and subtract - //it from every element of each uncovered column. Return to Step 4 without + //Add the value found in Step 4 to every element of each covered row, and subtract + //it from every element of each uncovered column. Return to Step 4 without //altering any stars, primes, or covered lines. private void step_six(ref int step) { @@ -443,12 +458,14 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification { C[r, c] += minval; } + if (ColCover[c] == 0) { C[r, c] -= minval; } } } + step = 4; } diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/TrackGroupingService.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/TrackGroupingService.cs index 6878f7dd1..4caa48bc2 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/TrackGroupingService.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/Identification/TrackGroupingService.cs @@ -4,7 +4,6 @@ using System.IO; using System.Linq; using System.Text.RegularExpressions; using NLog; -using NzbDrone.Common; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Common.Instrumentation; @@ -21,8 +20,8 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification { private static readonly Logger _logger = NzbDroneLogger.GetLogger(typeof(TrackGroupingService)); - private static readonly List<string> multiDiscMarkers = new List<string> { @"dis[ck]", @"cd" }; - private static readonly string multiDiscPatternFormat = @"^(?<root>.*%s[\W_]*)\d"; + private static readonly List<string> MultiDiscMarkers = new List<string> { @"dis[ck]", @"cd" }; + private static readonly string MultiDiscPatternFormat = @"^(?<root>.*%s[\W_]*)\d"; private static readonly List<string> VariousArtistTitles = new List<string> { "", "various artists", "various", "va", "unknown" }; public List<LocalAlbumRelease> GroupTracks(List<LocalTrack> localTracks) @@ -61,7 +60,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification } // Finally fall back to grouping by Album/Artist pair - foreach (var group in unprocessed2.GroupBy(x => new { x.FileTrackInfo.ArtistTitle, x.FileTrackInfo.AlbumTitle} )) + foreach (var group in unprocessed2.GroupBy(x => new { x.FileTrackInfo.ArtistTitle, x.FileTrackInfo.AlbumTitle })) { _logger.Debug("Falling back to grouping by album+artist tag"); releases.Add(new LocalAlbumRelease(group.ToList())); @@ -79,7 +78,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification var totalCount = values.Count(); // merge groups that are close to the most common value - foreach(var group in groups.Skip(1)) + foreach (var group in groups.Skip(1)) { if (mostCommonEntry.IsNotNullOrWhiteSpace() && group.Key.IsNotNullOrWhiteSpace() && @@ -94,7 +93,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification if (distinctCount > 1 && (distinctCount / (double)totalCount > threshold || - mostCommonCount / (double) totalCount < 1 - threshold)) + mostCommonCount / (double)totalCount < 1 - threshold)) { return false; } @@ -108,11 +107,10 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification // artist/album tags must be the same for 75% of tracks, with no more than 25% having different values // (except in the case of various artists) - const double albumTagThreshold = 0.25; const double artistTagThreshold = 0.25; const double tagFuzz = 0.9; - + // check that any Album/Release MBID is unique if (tracks.Select(x => x.FileTrackInfo.AlbumMBId).Distinct().Where(x => x.IsNotNullOrWhiteSpace()).Count() > 1 || tracks.Select(x => x.FileTrackInfo.ReleaseMBId).Distinct().Where(x => x.IsNotNullOrWhiteSpace()).Count() > 1) @@ -120,7 +118,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification _logger.Trace("LooksLikeSingleRelease: MBIDs are not unique"); return false; } - + // check that there's a common album tag. var albumTags = tracks.Select(x => x.FileTrackInfo.AlbumTitle); if (!HasCommonEntry(albumTags, albumTagThreshold, tagFuzz)) @@ -178,7 +176,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification // we only bother doing this for the immediate parent directory. var trackFolders = tracks.Select(x => Tuple.Create(x, Path.GetDirectoryName(x.Path))); - + var distinctFolders = trackFolders.Select(x => x.Item2).Distinct().ToList(); distinctFolders.Sort(); @@ -215,10 +213,10 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Identification output.AddRange(currentTracks); // check if the start of another multi disc match - foreach (var marker in multiDiscMarkers) + foreach (var marker in MultiDiscMarkers) { // check if this is the first of a multi-disc set of folders - var pattern = multiDiscPatternFormat.Replace("%s", marker); + var pattern = MultiDiscPatternFormat.Replace("%s", marker); var multiStartRegex = new Regex(pattern, RegexOptions.IgnoreCase); var match = multiStartRegex.Match(folder); diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/ImportApprovedTracks.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/ImportApprovedTracks.cs index 0c3b7afbb..5f64c1a2e 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/ImportApprovedTracks.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/ImportApprovedTracks.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.IO; using System.Linq; using NLog; using NzbDrone.Common.Disk; @@ -65,7 +64,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport .ThenByDescending(c => c.Item.Size)) .SelectMany(c => c) .ToList(); - + _logger.Debug($"Importing {qualifiedImports.Count} files. replaceExisting: {replaceExisting}"); var importResults = new List<ImportResult>(); @@ -87,7 +86,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport var previousFiles = _mediaFileService.GetFilesByAlbum(album.Id); _logger.Debug($"Deleting {previousFiles.Count} existing files for {album}"); - + foreach (var previousFile in previousFiles) { var subfolder = rootFolder.GetRelativePath(_diskProvider.GetParentFolder(previousFile.Path)); @@ -96,6 +95,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport _logger.Debug("Removing existing track file: {0}", previousFile); _recycleBinProvider.DeleteFile(previousFile.Path, subfolder); } + _mediaFileService.Delete(previousFile, DeleteMediaFileReason.Upgrade); } } @@ -112,7 +112,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport var filesToAdd = new List<TrackFile>(qualifiedImports.Count); var albumReleasesDict = new Dictionary<int, List<AlbumRelease>>(albumDecisions.Count); var trackImportedEvents = new List<TrackImportedEvent>(qualifiedImports.Count); - + foreach (var importDecision in qualifiedImports.OrderBy(e => e.Item.Tracks.Select(track => track.AbsoluteTrackNumber).MinOrDefault()) .ThenByDescending(e => e.Item.Size)) { @@ -137,10 +137,12 @@ namespace NzbDrone.Core.MediaFiles.TrackImport { albumReleasesDict.Add(localTrack.Album.Id, localTrack.Album.AlbumReleases.Value); } + if (!localTrack.Album.AlbumReleases.IsLoaded) { localTrack.Album.AlbumReleases = albumReleasesDict[localTrack.Album.Id]; } + localTrack.Album.Artist = localTrack.Artist; foreach (var track in localTrack.Tracks) @@ -149,8 +151,9 @@ namespace NzbDrone.Core.MediaFiles.TrackImport track.AlbumRelease = localTrack.Release; track.Album = localTrack.Album; } - - var trackFile = new TrackFile { + + var trackFile = new TrackFile + { Path = localTrack.Path.CleanFilePath(), Size = localTrack.Size, Modified = localTrack.Modified, @@ -230,7 +233,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport { _logger.Warn(e, "Couldn't import track " + localTrack); _eventAggregator.PublishEvent(new TrackImportFailedEvent(e, localTrack, !localTrack.ExistingFile, downloadClientItem)); - + importResults.Add(new ImportResult(importDecision, "Failed to import track, Permissions error")); } catch (Exception e) @@ -270,10 +273,10 @@ namespace NzbDrone.Core.MediaFiles.TrackImport album, release, allImportedTrackFiles.Where(s => s.AlbumId == album.Id).ToList(), - allOldTrackFiles.Where(s => s.AlbumId == album.Id).ToList(), replaceExisting, + allOldTrackFiles.Where(s => s.AlbumId == album.Id).ToList(), + replaceExisting, downloadClientItem)); } - } //Adding all the rejected decisions @@ -299,6 +302,5 @@ namespace NzbDrone.Core.MediaFiles.TrackImport return null; } - } } diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/ImportDecision.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/ImportDecision.cs index 36a1df843..fb15eca90 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/ImportDecision.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/ImportDecision.cs @@ -1,10 +1,7 @@ -using NzbDrone.Common.Extensions; -using NzbDrone.Core.DecisionEngine; -using NzbDrone.Core.Parser.Model; -using System; using System.Collections.Generic; using System.Linq; -using System.Text; +using NzbDrone.Common.Extensions; +using NzbDrone.Core.DecisionEngine; namespace NzbDrone.Core.MediaFiles.TrackImport { diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/ImportDecisionMaker.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/ImportDecisionMaker.cs index f2e7c5ad7..4c5200631 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/ImportDecisionMaker.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/ImportDecisionMaker.cs @@ -1,17 +1,17 @@ using System; using System.Collections.Generic; +using System.IO.Abstractions; using System.Linq; using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Core.DecisionEngine; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Music; -using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Download; using NzbDrone.Core.MediaFiles.TrackImport.Aggregation; using NzbDrone.Core.MediaFiles.TrackImport.Identification; -using System.IO.Abstractions; +using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Music; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.MediaFiles.TrackImport { @@ -124,7 +124,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport catch (Exception e) { _logger.Error(e, "Couldn't import file. {0}", localTrack.Path); - + decisions.Add(new ImportDecision<LocalTrack>(localTrack, new Rejection("Unexpected error processing file"))); } } diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/ImportResult.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/ImportResult.cs index 38235a29a..f52cb5260 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/ImportResult.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/ImportResult.cs @@ -1,9 +1,7 @@ -using NzbDrone.Common.EnsureThat; -using NzbDrone.Core.Parser.Model; -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; -using System.Text; +using NzbDrone.Common.EnsureThat; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.MediaFiles.TrackImport { diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/Manual/ManualImportFile.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/Manual/ManualImportFile.cs index a34d2a8ab..9faec9a65 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/Manual/ManualImportFile.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/Manual/ManualImportFile.cs @@ -22,20 +22,25 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Manual { return false; } + return Path.PathEquals(other.Path); } + public override bool Equals(object obj) { if (obj == null) { return false; } + if (obj.GetType() != GetType()) { return false; } + return Path.PathEquals(((ManualImportFile)obj).Path); } + public override int GetHashCode() { return Path != null ? Path.GetHashCode() : 0; diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/Manual/ManualImportItem.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/Manual/ManualImportItem.cs index ef6c04e81..ca83a6e17 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/Manual/ManualImportItem.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/Manual/ManualImportItem.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; -using NzbDrone.Core.DecisionEngine; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Music; using NzbDrone.Core.Datastore; +using NzbDrone.Core.DecisionEngine; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.MediaFiles.TrackImport.Manual { diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/Manual/ManualImportService.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/Manual/ManualImportService.cs index 4dfbe605d..8e3776535 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/Manual/ManualImportService.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/Manual/ManualImportService.cs @@ -4,6 +4,8 @@ using System.IO; using System.IO.Abstractions; using System.Linq; using NLog; +using NzbDrone.Common; +using NzbDrone.Common.Crypto; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Common.Instrumentation.Extensions; @@ -11,11 +13,9 @@ using NzbDrone.Core.Download; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Music; -using NzbDrone.Common.Crypto; -using NzbDrone.Common; namespace NzbDrone.Core.MediaFiles.TrackImport.Manual { @@ -140,7 +140,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Manual var result = new List<ManualImportItem>(); - foreach(var group in groupedItems) + foreach (var group in groupedItems) { _logger.Debug("UpdateItems, group key: {0}", group.Key); diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/RootFolderNotFoundException.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/RootFolderNotFoundException.cs index 15c3f997c..f865176be 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/RootFolderNotFoundException.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/RootFolderNotFoundException.cs @@ -10,15 +10,18 @@ namespace NzbDrone.Core.MediaFiles.TrackImport { } - public RootFolderNotFoundException(string message) : base(message) + public RootFolderNotFoundException(string message) + : base(message) { } - public RootFolderNotFoundException(string message, Exception innerException) : base(message, innerException) + public RootFolderNotFoundException(string message, Exception innerException) + : base(message, innerException) { } - protected RootFolderNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) + protected RootFolderNotFoundException(SerializationInfo info, StreamingContext context) + : base(info, context) { } } diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/AlbumUpgradeSpecification.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/AlbumUpgradeSpecification.cs index a1126f93a..c383a33f5 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/AlbumUpgradeSpecification.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/AlbumUpgradeSpecification.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using NLog; using NzbDrone.Core.DecisionEngine; @@ -31,7 +30,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Specifications // min quality of all new tracks var newMinQuality = localAlbumRelease.LocalTracks.Select(x => x.Quality).OrderBy(x => x, qualityComparer).First(); _logger.Debug("Min quality of new files: {0}", newMinQuality); - + // get minimum quality of existing release var existingQualities = currentRelease.Tracks.Value.Where(x => x.TrackFileId != 0).Select(x => x.TrackFile.Value.Quality); if (existingQualities.Any()) diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/CloseAlbumMatchSpecification.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/CloseAlbumMatchSpecification.cs index 4c6e53f75..7daae0e6f 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/CloseAlbumMatchSpecification.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/CloseAlbumMatchSpecification.cs @@ -8,9 +8,9 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Specifications { public class CloseAlbumMatchSpecification : IImportDecisionEngineSpecification<LocalAlbumRelease> { - private readonly Logger _logger; private const double _albumThreshold = 0.20; private const double _trackThreshold = 0.40; + private readonly Logger _logger; public CloseAlbumMatchSpecification(Logger logger) { @@ -21,7 +21,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Specifications { double dist; string reasons; - + // strict when a new download if (localAlbumRelease.NewDownload) { @@ -30,7 +30,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Specifications if (dist > _albumThreshold) { _logger.Debug($"Album match is not close enough: {dist} vs {_albumThreshold} {reasons}. Skipping {localAlbumRelease}"); - return Decision.Reject($"Album match is not close enough: {1-dist:P1} vs {1-_albumThreshold:P0} {reasons}"); + return Decision.Reject($"Album match is not close enough: {1 - dist:P1} vs {1 - _albumThreshold:P0} {reasons}"); } var worstTrackMatch = localAlbumRelease.LocalTracks.Where(x => x.Distance != null).OrderByDescending(x => x.Distance.NormalizedDistance()).FirstOrDefault(); @@ -46,10 +46,11 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Specifications if (maxTrackDist > _trackThreshold) { _logger.Debug($"Worst track match: {maxTrackDist} vs {_trackThreshold} {trackReasons}. Skipping {localAlbumRelease}"); - return Decision.Reject($"Worst track match: {1-maxTrackDist:P1} vs {1-_trackThreshold:P0} {trackReasons}"); + return Decision.Reject($"Worst track match: {1 - maxTrackDist:P1} vs {1 - _trackThreshold:P0} {trackReasons}"); } } } + // otherwise importing existing files in library else { @@ -59,7 +60,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Specifications if (dist > _albumThreshold) { _logger.Debug($"Album match is not close enough: {dist} vs {_albumThreshold} {reasons}. Skipping {localAlbumRelease}"); - return Decision.Reject($"Album match is not close enough: {1-dist:P1} vs {1-_albumThreshold:P0} {reasons}"); + return Decision.Reject($"Album match is not close enough: {1 - dist:P1} vs {1 - _albumThreshold:P0} {reasons}"); } } diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/CloseTrackMatchSpecification.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/CloseTrackMatchSpecification.cs index 0603dce95..9bb9c5186 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/CloseTrackMatchSpecification.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/CloseTrackMatchSpecification.cs @@ -1,4 +1,3 @@ -using System.Linq; using NLog; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Parser.Model; @@ -7,8 +6,8 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Specifications { public class CloseTrackMatchSpecification : IImportDecisionEngineSpecification<LocalTrack> { - private readonly Logger _logger; private const double _threshold = 0.4; + private readonly Logger _logger; public CloseTrackMatchSpecification(Logger logger) { @@ -23,7 +22,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Specifications if (dist > _threshold) { _logger.Debug($"Track match is not close enough: {dist} vs {_threshold} {reasons}. Skipping {localTrack}"); - return Decision.Reject($"Track match is not close enough: {1-dist:P1} vs {1-_threshold:P0} {reasons}"); + return Decision.Reject($"Track match is not close enough: {1 - dist:P1} vs {1 - _threshold:P0} {reasons}"); } _logger.Debug($"Track accepted: {dist} vs {_threshold} {reasons}."); diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/NoMissingOrUnmatchedTracksSpecification.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/NoMissingOrUnmatchedTracksSpecification.cs index 2d072fc91..510eaa76c 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/NoMissingOrUnmatchedTracksSpecification.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/NoMissingOrUnmatchedTracksSpecification.cs @@ -1,4 +1,3 @@ -using System.Linq; using NLog; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Parser.Model; @@ -27,7 +26,7 @@ namespace NzbDrone.Core.MediaFiles.TrackImport.Specifications _logger.Debug("This release is missing tracks. Skipping {0}", localAlbumRelease); return Decision.Reject("Has missing tracks"); } - + return Decision.Accept(); } } diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/ReleaseWantedSpecification.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/ReleaseWantedSpecification.cs index 6fd7df12e..d5022b8d6 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/ReleaseWantedSpecification.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/ReleaseWantedSpecification.cs @@ -1,4 +1,3 @@ -using System.Linq; using NLog; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Parser.Model; diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/SameFileSpecification.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/SameFileSpecification.cs index ffb9fee27..b4124601b 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/SameFileSpecification.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/SameFileSpecification.cs @@ -1,7 +1,6 @@ using System.Linq; using NLog; using NzbDrone.Core.DecisionEngine; -using NzbDrone.Core.Download; using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.MediaFiles.TrackImport.Specifications diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/SameTracksImportSpecification.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/SameTracksImportSpecification.cs index 57535f0d6..28519db91 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/SameTracksImportSpecification.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/SameTracksImportSpecification.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using NLog; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.DecisionEngine.Specifications; diff --git a/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/UpgradeSpecification.cs b/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/UpgradeSpecification.cs index 7dd26ade8..19496e8e8 100644 --- a/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/UpgradeSpecification.cs +++ b/src/NzbDrone.Core/MediaFiles/TrackImport/Specifications/UpgradeSpecification.cs @@ -1,10 +1,9 @@ -using System; using System.Linq; using NLog; +using NzbDrone.Core.Configuration; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Configuration; namespace NzbDrone.Core.MediaFiles.TrackImport.Specifications { diff --git a/src/NzbDrone.Core/MediaFiles/UpdateTrackFileService.cs b/src/NzbDrone.Core/MediaFiles/UpdateTrackFileService.cs index 08bbe6de3..d4aac29a0 100644 --- a/src/NzbDrone.Core/MediaFiles/UpdateTrackFileService.cs +++ b/src/NzbDrone.Core/MediaFiles/UpdateTrackFileService.cs @@ -1,11 +1,9 @@ using System; using System.Collections.Generic; -using System.IO; using System.Linq; using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.EnvironmentInfo; -using NzbDrone.Common.Extensions; using NzbDrone.Common.Instrumentation.Extensions; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.Events; @@ -83,7 +81,6 @@ namespace NzbDrone.Core.MediaFiles return true; } - catch (Exception ex) { _logger.Warn(ex, "Unable to set date of file [" + trackFilePath + "]"); @@ -126,7 +123,6 @@ namespace NzbDrone.Core.MediaFiles { _logger.ProgressDebug("Changed file date for {0} files of {1} in {2}", updated.Count, trackFiles.Count, message.Artist.Name); } - else { _logger.ProgressDebug("No file dates changed for {0}", message.Artist.Name); diff --git a/src/NzbDrone.Core/MediaFiles/UpgradeMediaFileService.cs b/src/NzbDrone.Core/MediaFiles/UpgradeMediaFileService.cs index ad4ee13ff..0dd3c3e62 100644 --- a/src/NzbDrone.Core/MediaFiles/UpgradeMediaFileService.cs +++ b/src/NzbDrone.Core/MediaFiles/UpgradeMediaFileService.cs @@ -1,4 +1,3 @@ -using System.IO; using System.Linq; using NLog; using NzbDrone.Common.Disk; diff --git a/src/NzbDrone.Core/Messaging/Commands/BackendCommandAttribute.cs b/src/NzbDrone.Core/Messaging/Commands/BackendCommandAttribute.cs index b40f64f9c..85f162a23 100644 --- a/src/NzbDrone.Core/Messaging/Commands/BackendCommandAttribute.cs +++ b/src/NzbDrone.Core/Messaging/Commands/BackendCommandAttribute.cs @@ -5,4 +5,4 @@ namespace NzbDrone.Core.Messaging.Commands public class BackendCommandAttribute : Attribute { } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandEqualityComparer.cs b/src/NzbDrone.Core/Messaging/Commands/CommandEqualityComparer.cs index 65f21b935..ea24a29df 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandEqualityComparer.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandEqualityComparer.cs @@ -10,12 +10,14 @@ namespace NzbDrone.Core.Messaging.Commands 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 @@ namespace NzbDrone.Core.Messaging.Commands continue; } - if (xProperty.DeclaringType == typeof (Command)) + if (xProperty.DeclaringType == typeof(Command)) { continue; } @@ -60,7 +62,6 @@ namespace NzbDrone.Core.Messaging.Commands 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 53ed14a6c..bc7c0d4b8 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandExecutor.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandExecutor.cs @@ -11,13 +11,14 @@ namespace NzbDrone.Core.Messaging.Commands public class CommandExecutor : IHandle<ApplicationStartedEvent>, IHandle<ApplicationShutdownRequested> { + private const int THREAD_LIMIT = 3; + private readonly Logger _logger; private readonly IServiceFactory _serviceFactory; private readonly IManageCommandQueue _commandQueueManager; private readonly IEventAggregator _eventAggregator; private static CancellationTokenSource _cancellationTokenSource; - private const int THREAD_LIMIT = 3; public CommandExecutor(IServiceFactory serviceFactory, IManageCommandQueue commandQueueManager, @@ -53,7 +54,7 @@ namespace NzbDrone.Core.Messaging.Commands } catch (OperationCanceledException) { - _logger.Trace("Stopped one command execution pipeline"); + _logger.Trace("Stopped one command execution pipeline"); } catch (Exception ex) { @@ -61,7 +62,8 @@ namespace NzbDrone.Core.Messaging.Commands } } - private void ExecuteCommand<TCommand>(TCommand command, CommandModel commandModel) where TCommand : Command + private void ExecuteCommand<TCommand>(TCommand command, CommandModel commandModel) + where TCommand : Command { var handlerContract = typeof(IExecute<>).MakeGenericType(command.GetType()); var handler = (IExecute<TCommand>)_serviceFactory.Build(handlerContract); diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandFailedException.cs b/src/NzbDrone.Core/Messaging/Commands/CommandFailedException.cs index 3dcbf60cc..cfb41883f 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 656037138..503dadadf 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandNotFoundException.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandNotFoundException.cs @@ -8,6 +8,5 @@ namespace NzbDrone.Core.Messaging.Commands : 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 f5e0de695..c5b4c5772 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandQueue.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandQueue.cs @@ -124,7 +124,6 @@ namespace NzbDrone.Core.Messaging.Commands { rval = false; } - else { var startedCommands = _items.Where(c => c.Status == CommandStatus.Started) @@ -149,7 +148,7 @@ namespace NzbDrone.Core.Messaging.Commands var localItem = queuedCommands.OrderByDescending(c => c.Priority) .ThenBy(c => c.QueuedAt) .FirstOrDefault(); - + // Nothing queued that meets the requirements if (localItem == null) { diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandQueueManager.cs b/src/NzbDrone.Core/Messaging/Commands/CommandQueueManager.cs index ce9b3c5cc..5567fbd63 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandQueueManager.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandQueueManager.cs @@ -7,16 +7,18 @@ using NLog; using NzbDrone.Common; using NzbDrone.Common.EnsureThat; using NzbDrone.Common.Serializer; -using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Exceptions; +using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Events; namespace NzbDrone.Core.Messaging.Commands { public interface IManageCommandQueue { - List<CommandModel> PushMany<TCommand>(List<TCommand> commands) where TCommand : Command; - CommandModel Push<TCommand>(TCommand command, CommandPriority priority = CommandPriority.Normal, CommandTrigger trigger = CommandTrigger.Unspecified) where TCommand : Command; + List<CommandModel> PushMany<TCommand>(List<TCommand> commands) + where TCommand : Command; + CommandModel Push<TCommand>(TCommand command, CommandPriority priority = CommandPriority.Normal, CommandTrigger trigger = CommandTrigger.Unspecified) + where TCommand : Command; CommandModel Push(string commandName, DateTime? lastExecutionTime, CommandPriority priority = CommandPriority.Normal, CommandTrigger trigger = CommandTrigger.Unspecified); IEnumerable<CommandModel> Queue(CancellationToken cancellationToken); List<CommandModel> All(); @@ -50,7 +52,8 @@ namespace NzbDrone.Core.Messaging.Commands _commandQueue = new CommandQueue(); } - public List<CommandModel> PushMany<TCommand>(List<TCommand> commands) where TCommand : Command + public List<CommandModel> PushMany<TCommand>(List<TCommand> commands) + where TCommand : Command { _logger.Trace("Publishing {0} commands", commands.Count); @@ -67,7 +70,6 @@ namespace NzbDrone.Core.Messaging.Commands } var commandModel = new CommandModel - { Name = command.Name, Body = command, @@ -90,8 +92,8 @@ namespace NzbDrone.Core.Messaging.Commands return commandModels; } - - public CommandModel Push<TCommand>(TCommand command, CommandPriority priority = CommandPriority.Normal, CommandTrigger trigger = CommandTrigger.Unspecified) where TCommand : Command + public CommandModel Push<TCommand>(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/IExecute.cs b/src/NzbDrone.Core/Messaging/Commands/IExecute.cs index 4e058e4d0..63bcc02d6 100644 --- a/src/NzbDrone.Core/Messaging/Commands/IExecute.cs +++ b/src/NzbDrone.Core/Messaging/Commands/IExecute.cs @@ -1,7 +1,8 @@ namespace NzbDrone.Core.Messaging.Commands { - public interface IExecute<TCommand> : IProcessMessage<TCommand> where TCommand : Command + public interface IExecute<TCommand> : IProcessMessage<TCommand> + where TCommand : Command { void Execute(TCommand message); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Messaging/Commands/TestCommand.cs b/src/NzbDrone.Core/Messaging/Commands/TestCommand.cs index f52fdeae7..9fe7c77c6 100644 --- a/src/NzbDrone.Core/Messaging/Commands/TestCommand.cs +++ b/src/NzbDrone.Core/Messaging/Commands/TestCommand.cs @@ -11,4 +11,4 @@ namespace NzbDrone.Core.Messaging.Commands Duration = 4000; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Messaging/Commands/TestCommandExecutor.cs b/src/NzbDrone.Core/Messaging/Commands/TestCommandExecutor.cs index 09c0f777d..40def385f 100644 --- a/src/NzbDrone.Core/Messaging/Commands/TestCommandExecutor.cs +++ b/src/NzbDrone.Core/Messaging/Commands/TestCommandExecutor.cs @@ -20,4 +20,4 @@ namespace NzbDrone.Core.Messaging.Commands _logger.ProgressInfo("Completed Test command"); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Messaging/Events/CommandExecutedEvent.cs b/src/NzbDrone.Core/Messaging/Events/CommandExecutedEvent.cs index 43556c47d..56ff5556c 100644 --- a/src/NzbDrone.Core/Messaging/Events/CommandExecutedEvent.cs +++ b/src/NzbDrone.Core/Messaging/Events/CommandExecutedEvent.cs @@ -12,4 +12,4 @@ namespace NzbDrone.Core.Messaging.Events Command = command; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Messaging/Events/EventAggregator.cs b/src/NzbDrone.Core/Messaging/Events/EventAggregator.cs index 97cc9156f..989a8687b 100644 --- a/src/NzbDrone.Core/Messaging/Events/EventAggregator.cs +++ b/src/NzbDrone.Core/Messaging/Events/EventAggregator.cs @@ -18,7 +18,8 @@ namespace NzbDrone.Core.Messaging.Events private readonly Dictionary<string, object> _eventSubscribers; - private class EventSubscribers<TEvent> where TEvent : class, IEvent + private class EventSubscribers<TEvent> + where TEvent : class, IEvent { private IServiceFactory _serviceFactory; @@ -50,7 +51,8 @@ namespace NzbDrone.Core.Messaging.Events _eventSubscribers = new Dictionary<string, object>(); } - public void PublishEvent<TEvent>(TEvent @event) where TEvent : class, IEvent + public void PublishEvent<TEvent>(TEvent @event) + where TEvent : class, IEvent { Ensure.That(@event, () => @event).IsNotNull(); @@ -87,7 +89,6 @@ namespace NzbDrone.Core.Messaging.Events subscribers = target as EventSubscribers<TEvent>; } - //call synchronous handlers first. var handlers = subscribers._syncHandlers; @@ -140,7 +141,8 @@ namespace NzbDrone.Core.Messaging.Events return string.Format("{0}<{1}>", eventType.Name.Remove(eventType.Name.IndexOf('`')), eventType.GetGenericArguments()[0].Name); } - internal static int GetEventHandleOrder<TEvent>(IHandle<TEvent> eventHandler) where TEvent : class, IEvent + internal static int GetEventHandleOrder<TEvent>(IHandle<TEvent> 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) }); diff --git a/src/NzbDrone.Core/Messaging/Events/IEventAggregator.cs b/src/NzbDrone.Core/Messaging/Events/IEventAggregator.cs index 9df32d66d..924cac454 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>(TEvent @event) where TEvent : class, IEvent; + void PublishEvent<TEvent>(TEvent @event) + where TEvent : class, IEvent; } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Messaging/Events/IHandle.cs b/src/NzbDrone.Core/Messaging/Events/IHandle.cs index 291e099d2..17c232e62 100644 --- a/src/NzbDrone.Core/Messaging/Events/IHandle.cs +++ b/src/NzbDrone.Core/Messaging/Events/IHandle.cs @@ -2,13 +2,15 @@ using NzbDrone.Common.Messaging; namespace NzbDrone.Core.Messaging.Events { - public interface IHandle<TEvent> : IProcessMessage<TEvent> where TEvent : IEvent + public interface IHandle<TEvent> : IProcessMessage<TEvent> + where TEvent : IEvent { void Handle(TEvent message); } - public interface IHandleAsync<TEvent> : IProcessMessageAsync<TEvent> where TEvent : IEvent + public interface IHandleAsync<TEvent> : IProcessMessageAsync<TEvent> + where TEvent : IEvent { void HandleAsync(TEvent message); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Messaging/IProcessMessage.cs b/src/NzbDrone.Core/Messaging/IProcessMessage.cs index 2207e803d..f0463ce2e 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<TMessage> : IProcessMessage { } + public interface IProcessMessage<TMessage> : IProcessMessage + { + } - public interface IProcessMessageAsync<TMessage> : IProcessMessageAsync { } -} \ No newline at end of file + public interface IProcessMessageAsync<TMessage> : IProcessMessageAsync + { + } +} diff --git a/src/NzbDrone.Core/MetadataSource/IMetadataRequestBuilder.cs b/src/NzbDrone.Core/MetadataSource/IMetadataRequestBuilder.cs index 552464cab..eb0f26c11 100644 --- a/src/NzbDrone.Core/MetadataSource/IMetadataRequestBuilder.cs +++ b/src/NzbDrone.Core/MetadataSource/IMetadataRequestBuilder.cs @@ -5,11 +5,11 @@ using NzbDrone.Core.Configuration; namespace NzbDrone.Core.MetadataSource { - public interface IMetadataRequestBuilder { IHttpRequestBuilderFactory GetRequestBuilder(); } + public class MetadataRequestBuilder : IMetadataRequestBuilder { private readonly IConfigService _configService; diff --git a/src/NzbDrone.Core/MetadataSource/IProvideAlbumInfo.cs b/src/NzbDrone.Core/MetadataSource/IProvideAlbumInfo.cs index 0aeb10200..4856d289e 100644 --- a/src/NzbDrone.Core/MetadataSource/IProvideAlbumInfo.cs +++ b/src/NzbDrone.Core/MetadataSource/IProvideAlbumInfo.cs @@ -1,6 +1,6 @@ -using NzbDrone.Core.Music; using System; using System.Collections.Generic; +using NzbDrone.Core.Music; namespace NzbDrone.Core.MetadataSource { diff --git a/src/NzbDrone.Core/MetadataSource/IProvideArtistInfo.cs b/src/NzbDrone.Core/MetadataSource/IProvideArtistInfo.cs index bf49d2797..0dadfa990 100644 --- a/src/NzbDrone.Core/MetadataSource/IProvideArtistInfo.cs +++ b/src/NzbDrone.Core/MetadataSource/IProvideArtistInfo.cs @@ -1,7 +1,4 @@ using NzbDrone.Core.Music; -using System; -using System.Collections.Generic; -using NzbDrone.Core.Profiles.Metadata; namespace NzbDrone.Core.MetadataSource { diff --git a/src/NzbDrone.Core/MetadataSource/ISearchForNewAlbum.cs b/src/NzbDrone.Core/MetadataSource/ISearchForNewAlbum.cs index a3e6ebc11..d1561b46a 100644 --- a/src/NzbDrone.Core/MetadataSource/ISearchForNewAlbum.cs +++ b/src/NzbDrone.Core/MetadataSource/ISearchForNewAlbum.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using NzbDrone.Core.Music; diff --git a/src/NzbDrone.Core/MetadataSource/ISearchForNewArtist.cs b/src/NzbDrone.Core/MetadataSource/ISearchForNewArtist.cs index 65cdb28e8..5a593712a 100644 --- a/src/NzbDrone.Core/MetadataSource/ISearchForNewArtist.cs +++ b/src/NzbDrone.Core/MetadataSource/ISearchForNewArtist.cs @@ -7,4 +7,4 @@ namespace NzbDrone.Core.MetadataSource { List<Artist> SearchForNewArtist(string title); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MetadataSource/ISearchForNewEntity.cs b/src/NzbDrone.Core/MetadataSource/ISearchForNewEntity.cs index 30a0125f2..b11be909d 100644 --- a/src/NzbDrone.Core/MetadataSource/ISearchForNewEntity.cs +++ b/src/NzbDrone.Core/MetadataSource/ISearchForNewEntity.cs @@ -5,6 +5,6 @@ namespace NzbDrone.Core.MetadataSource { public interface ISearchForNewEntity { - List<Object> SearchForNewEntity(string title); + List<object> SearchForNewEntity(string title); } } diff --git a/src/NzbDrone.Core/MetadataSource/SearchArtistComparer.cs b/src/NzbDrone.Core/MetadataSource/SearchArtistComparer.cs index f01e8107f..13a6f8201 100644 --- a/src/NzbDrone.Core/MetadataSource/SearchArtistComparer.cs +++ b/src/NzbDrone.Core/MetadataSource/SearchArtistComparer.cs @@ -20,7 +20,7 @@ namespace NzbDrone.Core.MetadataSource public SearchArtistComparer(string searchQuery) { SearchQuery = searchQuery; - + var match = Regex.Match(SearchQuery, @"^(?<query>.+)\s+(?:\((?<year>\d{4})\)|(?<year>\d{4}))$"); if (match.Success) { @@ -39,19 +39,28 @@ namespace NzbDrone.Core.MetadataSource // Prefer exact matches result = Compare(x, y, s => CleanPunctuation(s.Name).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.Name).Equals(CleanArticles(SearchQuery))); - if (result != 0) return -result; + if (result != 0) + { + return -result; + } // Prefer close matches result = Compare(x, y, s => CleanPunctuation(s.Name).LevenshteinDistance(CleanPunctuation(SearchQuery)) <= 1); - if (result != 0) return -result; - + if (result != 0) + { + return -result; + } + return Compare(x, y, s => SearchQuery.LevenshteinDistanceClean(s.Name)); } - + public int Compare<T>(Artist x, Artist y, Func<Artist, T> keySelector) where T : IComparable<T> { @@ -82,6 +91,5 @@ namespace NzbDrone.Core.MetadataSource return title.Trim().ToLowerInvariant(); } - } } diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ArtistResource.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ArtistResource.cs index 170617391..ff56b4950 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ArtistResource.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ArtistResource.cs @@ -24,6 +24,5 @@ namespace NzbDrone.Core.MetadataSource.SkyHook.Resource public List<AlbumResource> Albums { get; set; } public string Status { get; set; } public RatingResource Rating { get; set; } - } } diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/EntityResource.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/EntityResource.cs index 96e803ab0..ab2b5f987 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/EntityResource.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/EntityResource.cs @@ -5,6 +5,5 @@ namespace NzbDrone.Core.MetadataSource.SkyHook.Resource public int Score { get; set; } public ArtistResource Artist { get; set; } public AlbumResource Album { get; set; } - } } diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ImageResource.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ImageResource.cs index b600bd0c0..2e478c647 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ImageResource.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ImageResource.cs @@ -7,4 +7,4 @@ public int Height { get; set; } public int Width { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/MediumResource.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/MediumResource.cs index 3f7d00ac9..5f017010d 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/MediumResource.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/MediumResource.cs @@ -1,8 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - namespace NzbDrone.Core.MetadataSource.SkyHook.Resource { public class MediumResource @@ -11,6 +6,4 @@ namespace NzbDrone.Core.MetadataSource.SkyHook.Resource public string Format { get; set; } public int Position { get; set; } } - - } diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/RatingResource.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/RatingResource.cs index d3958378b..c14e188e4 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/RatingResource.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/RatingResource.cs @@ -5,4 +5,4 @@ public int Count { get; set; } public decimal Value { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/TrackResource.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/TrackResource.cs index b9296d4ad..611380de5 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/TrackResource.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/TrackResource.cs @@ -6,7 +6,6 @@ namespace NzbDrone.Core.MetadataSource.SkyHook.Resource { public TrackResource() { - } public string ArtistId { get; set; } @@ -20,6 +19,5 @@ namespace NzbDrone.Core.MetadataSource.SkyHook.Resource public int TrackPosition { get; set; } public bool Explicit { get; set; } public int MediumNumber { get; set; } - } } diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookException.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookException.cs index a9591fd6b..aabfe757f 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 351714efb..e554f702b 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookProxy.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookProxy.cs @@ -5,11 +5,11 @@ using System.Net; using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; +using NzbDrone.Core.Configuration; using NzbDrone.Core.Exceptions; using NzbDrone.Core.MediaCover; using NzbDrone.Core.MetadataSource.SkyHook.Resource; using NzbDrone.Core.Music; -using NzbDrone.Core.Configuration; using NzbDrone.Core.Profiles.Metadata; namespace NzbDrone.Core.MetadataSource.SkyHook @@ -24,8 +24,8 @@ namespace NzbDrone.Core.MetadataSource.SkyHook private readonly IConfigService _configService; private readonly IMetadataProfileService _metadataProfileService; - private static readonly List<string> nonAudioMedia = new List<string> { "DVD", "DVD-Video", "Blu-ray", "HD-DVD", "VCD", "SVCD", "UMD", "VHS" }; - private static readonly List<string> skippedTracks = new List<string> { "[data track]" }; + private static readonly List<string> NonAudioMedia = new List<string> { "DVD", "DVD-Video", "Blu-ray", "HD-DVD", "VCD", "SVCD", "UMD", "VHS" }; + private static readonly List<string> SkippedTracks = new List<string> { "[data track]" }; public SkyHookProxy(IHttpClient httpClient, IMetadataRequestBuilder requestBuilder, @@ -46,7 +46,6 @@ namespace NzbDrone.Core.MetadataSource.SkyHook public Artist GetArtistInfo(string foreignArtistId, int metadataProfileId) { - _logger.Debug("Getting Artist with LidarrAPI.MetadataID of {0}", foreignArtistId); var httpRequest = _requestBuilder.GetRequestBuilder().Create() @@ -58,7 +57,6 @@ namespace NzbDrone.Core.MetadataSource.SkyHook var httpResponse = _httpClient.Get<ArtistResource>(httpRequest); - if (httpResponse.HasHttpError) { if (httpResponse.StatusCode == HttpStatusCode.NotFound) @@ -93,9 +91,8 @@ namespace NzbDrone.Core.MetadataSource.SkyHook var secondaryTypes = new HashSet<string>(metadataProfile.SecondaryAlbumTypes.Where(s => s.Allowed).Select(s => s.SecondaryAlbumType.Name)); var releaseStatuses = new HashSet<string>(metadataProfile.ReleaseStatuses.Where(s => s.Allowed).Select(s => s.ReleaseStatus.Name)); - return albums.Where(album => primaryTypes.Contains(album.Type) && - (!album.SecondaryTypes.Any() && secondaryTypes.Contains("Studio") || + ((!album.SecondaryTypes.Any() && secondaryTypes.Contains("Studio")) || album.SecondaryTypes.Any(x => secondaryTypes.Contains(x))) && album.ReleaseStatuses.Any(x => releaseStatuses.Contains(x))); } @@ -103,7 +100,7 @@ namespace NzbDrone.Core.MetadataSource.SkyHook public Tuple<string, Album, List<ArtistMetadata>> GetAlbumInfo(string foreignAlbumId) { _logger.Debug("Getting Album with LidarrAPI.MetadataID of {0}", foreignAlbumId); - + var httpRequest = _requestBuilder.GetRequestBuilder().Create() .SetSegment("route", "album/" + foreignAlbumId) .Build(); @@ -180,8 +177,6 @@ namespace NzbDrone.Core.MetadataSource.SkyHook .AddQueryParam("query", title.ToLower().Trim()) .Build(); - - var httpResponse = _httpClient.Get<List<ArtistResource>>(httpRequest); return httpResponse.Resource.SelectList(MapSearchResult); @@ -224,7 +219,8 @@ namespace NzbDrone.Core.MetadataSource.SkyHook { var data = GetAlbumInfo(searchGuid.ToString()); var album = data.Item2; - album.Artist = _artistService.FindById(data.Item1) ?? new Artist { + album.Artist = _artistService.FindById(data.Item1) ?? new Artist + { Metadata = data.Item3.Single(x => x.ForeignArtistId == data.Item1) }; @@ -232,8 +228,7 @@ namespace NzbDrone.Core.MetadataSource.SkyHook } existingAlbum.Artist = _artistService.GetArtist(existingAlbum.ArtistId); - return new List<Album>{existingAlbum}; - + return new List<Album> { existingAlbum }; } catch (ArtistNotFoundException) { @@ -249,8 +244,6 @@ namespace NzbDrone.Core.MetadataSource.SkyHook .AddQueryParam("includeTracks", "1") .Build(); - - var httpResponse = _httpClient.Get<List<AlbumResource>>(httpRequest); return httpResponse.Resource.SelectList(MapSearchResult); @@ -266,7 +259,7 @@ namespace NzbDrone.Core.MetadataSource.SkyHook } } - public List<Object> SearchForNewEntity(string title) + public List<object> SearchForNewEntity(string title) { try { @@ -321,7 +314,7 @@ namespace NzbDrone.Core.MetadataSource.SkyHook return album; } - private Object MapSearchResult(EntityResource resource) + private object MapSearchResult(EntityResource resource) { if (resource.Artist != null) { @@ -382,23 +375,23 @@ namespace NzbDrone.Core.MetadataSource.SkyHook var allTracks = resource.Tracks.Select(x => MapTrack(x, artistDict)); if (!allMedia.Any()) { - foreach(int n in allTracks.Select(x => x.MediumNumber).Distinct()) + foreach (int n in allTracks.Select(x => x.MediumNumber).Distinct()) { allMedia.Add(new Medium { Name = "Unknown", Number = n, Format = "Unknown" }); } } // Skip non-audio media - var audioMediaNumbers = allMedia.Where(x => !nonAudioMedia.Contains(x.Format)).Select(x => x.Number); + var audioMediaNumbers = allMedia.Where(x => !NonAudioMedia.Contains(x.Format)).Select(x => x.Number); // Get tracks on the audio media and omit any that are skipped - release.Tracks = allTracks.Where(x => audioMediaNumbers.Contains(x.MediumNumber) && !skippedTracks.Contains(x.Title)).ToList(); + release.Tracks = allTracks.Where(x => audioMediaNumbers.Contains(x.MediumNumber) && !SkippedTracks.Contains(x.Title)).ToList(); release.TrackCount = release.Tracks.Value.Count; // Only include the media that contain the tracks we have selected var usedMediaNumbers = release.Tracks.Value.Select(track => track.MediumNumber); release.Media = allMedia.Where(medium => usedMediaNumbers.Contains(medium.Number)).ToList(); - + release.Duration = release.Tracks.Value.Sum(x => x.Duration); return release; @@ -437,7 +430,6 @@ namespace NzbDrone.Core.MetadataSource.SkyHook private static ArtistMetadata MapArtistMetadata(ArtistResource resource) { - ArtistMetadata artist = new ArtistMetadata(); artist.Name = resource.ArtistName; diff --git a/src/NzbDrone.Core/Music/Events/AlbumDeletedEvent.cs b/src/NzbDrone.Core/Music/Events/AlbumDeletedEvent.cs index f5630c30d..23c08d8ed 100644 --- a/src/NzbDrone.Core/Music/Events/AlbumDeletedEvent.cs +++ b/src/NzbDrone.Core/Music/Events/AlbumDeletedEvent.cs @@ -1,8 +1,4 @@ using NzbDrone.Common.Messaging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace NzbDrone.Core.Music.Events { diff --git a/src/NzbDrone.Core/Music/Events/AlbumEditedEvent.cs b/src/NzbDrone.Core/Music/Events/AlbumEditedEvent.cs index aed8f155e..7cd64cb19 100644 --- a/src/NzbDrone.Core/Music/Events/AlbumEditedEvent.cs +++ b/src/NzbDrone.Core/Music/Events/AlbumEditedEvent.cs @@ -1,8 +1,4 @@ using NzbDrone.Common.Messaging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace NzbDrone.Core.Music.Events { diff --git a/src/NzbDrone.Core/Music/Events/AlbumInfoRefreshedEvent.cs b/src/NzbDrone.Core/Music/Events/AlbumInfoRefreshedEvent.cs index 5fdb3f539..25ad9aca3 100644 --- a/src/NzbDrone.Core/Music/Events/AlbumInfoRefreshedEvent.cs +++ b/src/NzbDrone.Core/Music/Events/AlbumInfoRefreshedEvent.cs @@ -1,9 +1,6 @@ -using NzbDrone.Common.Messaging; -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Linq; -using System.Text; +using NzbDrone.Common.Messaging; namespace NzbDrone.Core.Music.Events { diff --git a/src/NzbDrone.Core/Music/Events/ArtistDeletedEvent.cs b/src/NzbDrone.Core/Music/Events/ArtistDeletedEvent.cs index 5c448f133..0c1bf0043 100644 --- a/src/NzbDrone.Core/Music/Events/ArtistDeletedEvent.cs +++ b/src/NzbDrone.Core/Music/Events/ArtistDeletedEvent.cs @@ -1,8 +1,4 @@ using NzbDrone.Common.Messaging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace NzbDrone.Core.Music.Events { diff --git a/src/NzbDrone.Core/Music/Events/ArtistEditedEvent.cs b/src/NzbDrone.Core/Music/Events/ArtistEditedEvent.cs index 4511e8943..f1ca73b68 100644 --- a/src/NzbDrone.Core/Music/Events/ArtistEditedEvent.cs +++ b/src/NzbDrone.Core/Music/Events/ArtistEditedEvent.cs @@ -1,8 +1,4 @@ using NzbDrone.Common.Messaging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace NzbDrone.Core.Music.Events { diff --git a/src/NzbDrone.Core/Music/Events/ReleaseDeletedEvent.cs b/src/NzbDrone.Core/Music/Events/ReleaseDeletedEvent.cs index a9cfa26bb..cd4fa2254 100644 --- a/src/NzbDrone.Core/Music/Events/ReleaseDeletedEvent.cs +++ b/src/NzbDrone.Core/Music/Events/ReleaseDeletedEvent.cs @@ -1,8 +1,4 @@ using NzbDrone.Common.Messaging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace NzbDrone.Core.Music.Events { diff --git a/src/NzbDrone.Core/Music/Model/AddAlbumOptions.cs b/src/NzbDrone.Core/Music/Model/AddAlbumOptions.cs index 3e059c7e8..537856c12 100644 --- a/src/NzbDrone.Core/Music/Model/AddAlbumOptions.cs +++ b/src/NzbDrone.Core/Music/Model/AddAlbumOptions.cs @@ -11,7 +11,7 @@ namespace NzbDrone.Core.Music } public AlbumAddType AddType { get; set; } - public bool SearchForNewAlbum { get; set; } + public bool SearchForNewAlbum { get; set; } } public enum AlbumAddType diff --git a/src/NzbDrone.Core/Music/Model/Album.cs b/src/NzbDrone.Core/Music/Model/Album.cs index df339537d..a09314c5e 100644 --- a/src/NzbDrone.Core/Music/Model/Album.cs +++ b/src/NzbDrone.Core/Music/Model/Album.cs @@ -1,9 +1,9 @@ -using NzbDrone.Common.Extensions; using System; using System.Collections.Generic; -using Marr.Data; -using Equ; using System.Linq; +using Equ; +using Marr.Data; +using NzbDrone.Common.Extensions; namespace NzbDrone.Core.Music { @@ -38,7 +38,7 @@ namespace NzbDrone.Core.Music public List<SecondaryAlbumType> SecondaryTypes { get; set; } public Ratings Ratings { get; set; } - // These are Lidarr generated/config + // These are Lidarr generated/config public string CleanTitle { get; set; } public int ProfileId { get; set; } public bool Monitored { get; set; } @@ -58,7 +58,10 @@ namespace NzbDrone.Core.Music //compatibility properties with old version of Album [MemberwiseEqualityIgnore] - public int ArtistId { get { return Artist?.Value?.Id ?? 0; } set { Artist.Value.Id = value; } } + public int ArtistId + { + get { return Artist?.Value?.Id ?? 0; } set { Artist.Value.Id = value; } + } public override string ToString() { diff --git a/src/NzbDrone.Core/Music/Model/Artist.cs b/src/NzbDrone.Core/Music/Model/Artist.cs index 54421bbcb..f2c1c90ae 100644 --- a/src/NzbDrone.Core/Music/Model/Artist.cs +++ b/src/NzbDrone.Core/Music/Model/Artist.cs @@ -1,10 +1,10 @@ -using Marr.Data; -using NzbDrone.Common.Extensions; -using NzbDrone.Core.Profiles.Qualities; -using NzbDrone.Core.Profiles.Metadata; using System; using System.Collections.Generic; using Equ; +using Marr.Data; +using NzbDrone.Common.Extensions; +using NzbDrone.Core.Profiles.Metadata; +using NzbDrone.Core.Profiles.Qualities; namespace NzbDrone.Core.Music { @@ -44,9 +44,16 @@ namespace NzbDrone.Core.Music //compatibility properties [MemberwiseEqualityIgnore] - public string Name { get { return Metadata.Value.Name; } set { Metadata.Value.Name = value; } } + public string Name + { + get { return Metadata.Value.Name; } set { Metadata.Value.Name = value; } + } + [MemberwiseEqualityIgnore] - public string ForeignArtistId { get { return Metadata.Value.ForeignArtistId; } set { Metadata.Value.ForeignArtistId = value; } } + public string ForeignArtistId + { + get { return Metadata.Value.ForeignArtistId; } set { Metadata.Value.ForeignArtistId = value; } + } public override string ToString() { diff --git a/src/NzbDrone.Core/Music/Model/ArtistMetadata.cs b/src/NzbDrone.Core/Music/Model/ArtistMetadata.cs index bb56bf7c9..108dad867 100644 --- a/src/NzbDrone.Core/Music/Model/ArtistMetadata.cs +++ b/src/NzbDrone.Core/Music/Model/ArtistMetadata.cs @@ -1,6 +1,6 @@ -using NzbDrone.Common.Extensions; using System.Collections.Generic; using System.Linq; +using NzbDrone.Common.Extensions; namespace NzbDrone.Core.Music { diff --git a/src/NzbDrone.Core/Music/Model/Entity.cs b/src/NzbDrone.Core/Music/Model/Entity.cs index b0dc4d822..03a93707f 100644 --- a/src/NzbDrone.Core/Music/Model/Entity.cs +++ b/src/NzbDrone.Core/Music/Model/Entity.cs @@ -1,6 +1,6 @@ -using NzbDrone.Core.Datastore; using System; using Equ; +using NzbDrone.Core.Datastore; namespace NzbDrone.Core.Music { @@ -15,9 +15,13 @@ namespace NzbDrone.Core.Music Id = other.Id; } - public virtual void UseMetadataFrom(T other) { } + public virtual void UseMetadataFrom(T other) + { + } - public virtual void ApplyChanges(T other) { } + public virtual void ApplyChanges(T other) + { + } public bool Equals(T other) { diff --git a/src/NzbDrone.Core/Music/Model/MonitoringOptions.cs b/src/NzbDrone.Core/Music/Model/MonitoringOptions.cs index a51849b35..382c40a57 100644 --- a/src/NzbDrone.Core/Music/Model/MonitoringOptions.cs +++ b/src/NzbDrone.Core/Music/Model/MonitoringOptions.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Datastore; using System.Collections.Generic; +using NzbDrone.Core.Datastore; namespace NzbDrone.Core.Music { @@ -9,7 +9,7 @@ namespace NzbDrone.Core.Music { AlbumsToMonitor = new List<string>(); } - + public MonitorTypes Monitor { get; set; } public List<string> AlbumsToMonitor { get; set; } public bool Monitored { get; set; } diff --git a/src/NzbDrone.Core/Music/Model/PrimaryAlbumType.cs b/src/NzbDrone.Core/Music/Model/PrimaryAlbumType.cs index 399587734..068bf1779 100644 --- a/src/NzbDrone.Core/Music/Model/PrimaryAlbumType.cs +++ b/src/NzbDrone.Core/Music/Model/PrimaryAlbumType.cs @@ -36,10 +36,12 @@ namespace NzbDrone.Core.Music { return false; } + if (ReferenceEquals(this, other)) { return true; } + return Id.Equals(other.Id); } @@ -49,6 +51,7 @@ namespace NzbDrone.Core.Music { return false; } + return ReferenceEquals(this, obj) || Equals(obj as PrimaryAlbumType); } @@ -68,7 +71,6 @@ namespace NzbDrone.Core.Music public static PrimaryAlbumType Broadcast => new PrimaryAlbumType(3, "Broadcast"); public static PrimaryAlbumType Other => new PrimaryAlbumType(4, "Other"); - public static readonly List<PrimaryAlbumType> All = new List<PrimaryAlbumType> { Album, @@ -78,7 +80,6 @@ namespace NzbDrone.Core.Music Other }; - public static PrimaryAlbumType FindById(int id) { if (id == 0) diff --git a/src/NzbDrone.Core/Music/Model/Release.cs b/src/NzbDrone.Core/Music/Model/Release.cs index 2ad6936af..3639b62ed 100644 --- a/src/NzbDrone.Core/Music/Model/Release.cs +++ b/src/NzbDrone.Core/Music/Model/Release.cs @@ -1,8 +1,8 @@ -using NzbDrone.Common.Extensions; using System; using System.Collections.Generic; -using Marr.Data; using Equ; +using Marr.Data; +using NzbDrone.Common.Extensions; namespace NzbDrone.Core.Music { diff --git a/src/NzbDrone.Core/Music/Model/ReleaseStatus.cs b/src/NzbDrone.Core/Music/Model/ReleaseStatus.cs index aa8809492..b22f08ba2 100644 --- a/src/NzbDrone.Core/Music/Model/ReleaseStatus.cs +++ b/src/NzbDrone.Core/Music/Model/ReleaseStatus.cs @@ -36,10 +36,12 @@ namespace NzbDrone.Core.Music { return false; } + if (ReferenceEquals(this, other)) { return true; } + return Id.Equals(other.Id); } @@ -49,6 +51,7 @@ namespace NzbDrone.Core.Music { return false; } + return ReferenceEquals(this, obj) || Equals(obj as ReleaseStatus); } @@ -67,7 +70,6 @@ namespace NzbDrone.Core.Music public static ReleaseStatus Bootleg => new ReleaseStatus(2, "Bootleg"); public static ReleaseStatus Pseudo => new ReleaseStatus(3, "Pseudo-Release"); - public static readonly List<ReleaseStatus> All = new List<ReleaseStatus> { Official, @@ -76,7 +78,6 @@ namespace NzbDrone.Core.Music Pseudo }; - public static ReleaseStatus FindById(int id) { if (id == 0) diff --git a/src/NzbDrone.Core/Music/Model/SecondaryAlbumType.cs b/src/NzbDrone.Core/Music/Model/SecondaryAlbumType.cs index 9e43cac8a..ac9202eda 100644 --- a/src/NzbDrone.Core/Music/Model/SecondaryAlbumType.cs +++ b/src/NzbDrone.Core/Music/Model/SecondaryAlbumType.cs @@ -36,10 +36,12 @@ namespace NzbDrone.Core.Music { return false; } + if (ReferenceEquals(this, other)) { return true; } + return Id.Equals(other.Id); } @@ -49,6 +51,7 @@ namespace NzbDrone.Core.Music { return false; } + return ReferenceEquals(this, obj) || Equals(obj as SecondaryAlbumType); } @@ -74,7 +77,6 @@ namespace NzbDrone.Core.Music public static SecondaryAlbumType Mixtape => new SecondaryAlbumType(9, "Mixtape/Street"); public static SecondaryAlbumType Demo => new SecondaryAlbumType(10, "Demo"); - public static readonly List<SecondaryAlbumType> All = new List<SecondaryAlbumType> { Studio, @@ -89,7 +91,6 @@ namespace NzbDrone.Core.Music Demo }; - public static SecondaryAlbumType FindById(int id) { if (id == 0) diff --git a/src/NzbDrone.Core/Music/Model/Track.cs b/src/NzbDrone.Core/Music/Model/Track.cs index ceaabc3d9..c83f654ea 100644 --- a/src/NzbDrone.Core/Music/Model/Track.cs +++ b/src/NzbDrone.Core/Music/Model/Track.cs @@ -1,8 +1,8 @@ -using NzbDrone.Core.MediaFiles; -using Marr.Data; -using NzbDrone.Common.Extensions; using System.Collections.Generic; using Equ; +using Marr.Data; +using NzbDrone.Common.Extensions; +using NzbDrone.Core.MediaFiles; namespace NzbDrone.Core.Music { @@ -47,7 +47,11 @@ namespace NzbDrone.Core.Music // These are retained for compatibility // TODO: Remove set, bodged in because tests expect this to be writable [MemberwiseEqualityIgnore] - public int AlbumId { get { return AlbumRelease?.Value?.Album?.Value?.Id ?? 0; } set { /* empty */ } } + public int AlbumId + { + get { return AlbumRelease?.Value?.Album?.Value?.Id ?? 0; } set { /* empty */ } + } + [MemberwiseEqualityIgnore] public Album Album { get; set; } diff --git a/src/NzbDrone.Core/Music/Repositories/AlbumRepository.cs b/src/NzbDrone.Core/Music/Repositories/AlbumRepository.cs index d2e1f5db0..900255e31 100644 --- a/src/NzbDrone.Core/Music/Repositories/AlbumRepository.cs +++ b/src/NzbDrone.Core/Music/Repositories/AlbumRepository.cs @@ -1,12 +1,12 @@ using System; +using System.Collections.Generic; using System.Linq; using Marr.Data.QGen; +using NzbDrone.Common.Extensions; using NzbDrone.Core.Datastore; using NzbDrone.Core.Datastore.Extensions; -using System.Collections.Generic; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Qualities; -using NzbDrone.Common.Extensions; namespace NzbDrone.Core.Music { @@ -95,7 +95,6 @@ namespace NzbDrone.Core.Music var currentTime = DateTime.UtcNow; //pagingSpec.TotalRecords = GetMissingAlbumsQuery(pagingSpec, currentTime).GetRowCount(); Cant Use GetRowCount with a Manual Query - pagingSpec.TotalRecords = GetMissingAlbumsQueryCount(pagingSpec, currentTime); pagingSpec.Records = GetMissingAlbumsQuery(pagingSpec, currentTime).ToList(); @@ -104,7 +103,6 @@ namespace NzbDrone.Core.Music public PagingSpec<Album> AlbumsWhereCutoffUnmet(PagingSpec<Album> pagingSpec, List<QualitiesBelowCutoff> qualitiesBelowCutoff) { - pagingSpec.TotalRecords = GetCutOffAlbumsQueryCount(pagingSpec, qualitiesBelowCutoff); pagingSpec.Records = GetCutOffAlbumsQuery(pagingSpec, qualitiesBelowCutoff).ToList(); @@ -117,7 +115,6 @@ namespace NzbDrone.Core.Music .Where<Album>(rg => rg.ReleaseDate >= startDate) .AndWhere(rg => rg.ReleaseDate <= endDate); - if (!includeUnmonitored) { query.AndWhere(e => e.Monitored) @@ -134,7 +131,6 @@ namespace NzbDrone.Core.Music .AndWhere(e => e.ReleaseDate <= endDate) .AndWhere(e => e.ArtistMetadataId == artist.ArtistMetadataId); - if (!includeUnmonitored) { query.AndWhere(e => e.Monitored) @@ -269,7 +265,6 @@ namespace NzbDrone.Core.Music pagingSpec.PagingOffset()); return Query.QueryText(query); - } private int GetCutOffAlbumsQueryCount(PagingSpec<Album> pagingSpec, List<QualitiesBelowCutoff> qualitiesBelowCutoff) @@ -334,10 +329,12 @@ namespace NzbDrone.Core.Music public Album FindByTitle(int artistMetadataId, string title) { var cleanTitle = Parser.Parser.CleanArtistName(title); - + if (string.IsNullOrEmpty(cleanTitle)) + { cleanTitle = title; - + } + return Query.Where(s => s.CleanTitle == cleanTitle || s.Title == title) .AndWhere(s => s.ArtistMetadataId == artistMetadataId) .ExclusiveOrDefault(); diff --git a/src/NzbDrone.Core/Music/Repositories/ArtistMetadataRepository.cs b/src/NzbDrone.Core/Music/Repositories/ArtistMetadataRepository.cs index 78cb763b3..bf83e5145 100644 --- a/src/NzbDrone.Core/Music/Repositories/ArtistMetadataRepository.cs +++ b/src/NzbDrone.Core/Music/Repositories/ArtistMetadataRepository.cs @@ -1,8 +1,8 @@ -using System.Linq; -using System.Collections.Generic; +using System.Collections.Generic; +using System.Linq; +using NLog; using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; -using NLog; namespace NzbDrone.Core.Music { @@ -54,12 +54,12 @@ namespace NzbDrone.Core.Music addMetadataList.Add(meta); } } - + UpdateMany(updateMetadataList); InsertMany(addMetadataList); - + _logger.Debug($"{upToDateMetadataCount} artist metadata up to date; Updating {updateMetadataList.Count}, Adding {addMetadataList.Count} artist metadata entries."); - + return updateMetadataList.Count > 0 || addMetadataList.Count > 0; } } diff --git a/src/NzbDrone.Core/Music/Repositories/ArtistRepository.cs b/src/NzbDrone.Core/Music/Repositories/ArtistRepository.cs index baca718da..70df40d08 100644 --- a/src/NzbDrone.Core/Music/Repositories/ArtistRepository.cs +++ b/src/NzbDrone.Core/Music/Repositories/ArtistRepository.cs @@ -1,8 +1,8 @@ using System.Linq; -using NzbDrone.Core.Datastore; -using NzbDrone.Core.Messaging.Events; using Marr.Data.QGen; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Datastore; +using NzbDrone.Core.Messaging.Events; namespace NzbDrone.Core.Music { diff --git a/src/NzbDrone.Core/Music/Repositories/ReleaseRepository.cs b/src/NzbDrone.Core/Music/Repositories/ReleaseRepository.cs index 3d6714b0e..6ab0a3f0e 100644 --- a/src/NzbDrone.Core/Music/Repositories/ReleaseRepository.cs +++ b/src/NzbDrone.Core/Music/Repositories/ReleaseRepository.cs @@ -35,7 +35,7 @@ namespace NzbDrone.Core.Music release = Query.Where(x => x.OldForeignReleaseIds.Contains(id)) .SingleOrDefault(); } - + return release; } diff --git a/src/NzbDrone.Core/Music/Repositories/TrackRepository.cs b/src/NzbDrone.Core/Music/Repositories/TrackRepository.cs index 883588430..7fc678bbf 100644 --- a/src/NzbDrone.Core/Music/Repositories/TrackRepository.cs +++ b/src/NzbDrone.Core/Music/Repositories/TrackRepository.cs @@ -36,7 +36,7 @@ namespace NzbDrone.Core.Music "WHERE Artists.Id = {0} " + "AND AlbumReleases.Monitored = 1", artistId); - + return Query.QueryText(query).ToList(); } diff --git a/src/NzbDrone.Core/Music/Services/AddArtistService.cs b/src/NzbDrone.Core/Music/Services/AddArtistService.cs index c0affd051..70604b9bc 100644 --- a/src/NzbDrone.Core/Music/Services/AddArtistService.cs +++ b/src/NzbDrone.Core/Music/Services/AddArtistService.cs @@ -81,13 +81,12 @@ namespace NzbDrone.Core.Music // Catch Import Errors for now until we get things fixed up _logger.Error(ex, "Failed to import id: {0} - {1}", s.Metadata.Value.ForeignArtistId, s.Metadata.Value.Name); } - } // add metadata _artistMetadataService.UpsertMany(artistsToAdd.Select(x => x.Metadata.Value).ToList()); artistsToAdd.ForEach(x => x.ArtistMetadataId = x.Metadata.Value.Id); - + return _artistService.AddArtists(artistsToAdd); } diff --git a/src/NzbDrone.Core/Music/Services/AlbumEditedService.cs b/src/NzbDrone.Core/Music/Services/AlbumEditedService.cs index 4fefd8fbc..a02b115d7 100644 --- a/src/NzbDrone.Core/Music/Services/AlbumEditedService.cs +++ b/src/NzbDrone.Core/Music/Services/AlbumEditedService.cs @@ -14,7 +14,7 @@ namespace NzbDrone.Core.Music private readonly ITrackService _trackService; public AlbumEditedService(IManageCommandQueue commandQueueManager, - ITrackService trackService) + ITrackService trackService) { _commandQueueManager = commandQueueManager; _trackService = trackService; diff --git a/src/NzbDrone.Core/Music/Services/AlbumMonitoredService.cs b/src/NzbDrone.Core/Music/Services/AlbumMonitoredService.cs index 87417d926..137d0ac55 100644 --- a/src/NzbDrone.Core/Music/Services/AlbumMonitoredService.cs +++ b/src/NzbDrone.Core/Music/Services/AlbumMonitoredService.cs @@ -75,7 +75,7 @@ namespace NzbDrone.Core.Music break; case MonitorTypes.Latest: ToggleAlbumsMonitoredState(albums, false); - ToggleAlbumsMonitoredState(albums.OrderByDescending(e=>e.ReleaseDate).Take(1),true); + ToggleAlbumsMonitoredState(albums.OrderByDescending(e => e.ReleaseDate).Take(1), true); break; case MonitorTypes.First: ToggleAlbumsMonitoredState(albums, false); diff --git a/src/NzbDrone.Core/Music/Services/AlbumService.cs b/src/NzbDrone.Core/Music/Services/AlbumService.cs index faa90be6a..23a555310 100644 --- a/src/NzbDrone.Core/Music/Services/AlbumService.cs +++ b/src/NzbDrone.Core/Music/Services/AlbumService.cs @@ -1,12 +1,12 @@ -using NLog; -using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Music.Events; using System; using System.Collections.Generic; using System.Linq; -using NzbDrone.Core.Datastore; -using NzbDrone.Core.Parser; +using NLog; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Datastore; +using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Music.Events; +using NzbDrone.Core.Parser; namespace NzbDrone.Core.Music { @@ -86,8 +86,9 @@ namespace NzbDrone.Core.Music private List<Tuple<Func<Album, string, double>, string>> AlbumScoringFunctions(string title, string cleanTitle) { - Func< Func<Album, string, double>, string, Tuple<Func<Album, string, double>, string>> tc = Tuple.Create; - var scoringFunctions = new List<Tuple<Func<Album, string, double>, string>> { + Func<Func<Album, string, double>, string, Tuple<Func<Album, string, double>, string>> tc = Tuple.Create; + var scoringFunctions = new List<Tuple<Func<Album, string, double>, string>> + { tc((a, t) => a.CleanTitle.FuzzyMatch(t), cleanTitle), tc((a, t) => a.Title.FuzzyMatch(t), title), tc((a, t) => a.CleanTitle.FuzzyMatch(t), title.RemoveBracketsAndContents().CleanArtistName()), @@ -120,7 +121,7 @@ namespace NzbDrone.Core.Music { var albums = GetAlbumsByArtistMetadataId(artistMetadataId); var output = new List<Album>(); - + foreach (var func in AlbumScoringFunctions(title, title.CleanArtistName())) { output.AddRange(FindByStringInexact(albums, func.Item1, func.Item2)); @@ -135,10 +136,10 @@ namespace NzbDrone.Core.Music const double fuzzGap = 0.4; var sortedAlbums = albums.Select(s => new - { - MatchProb = scoreFunction(s, title), - Album = s - }) + { + MatchProb = scoreFunction(s, title), + Album = s + }) .ToList() .OrderByDescending(s => s.MatchProb) .ToList(); @@ -264,6 +265,7 @@ namespace NzbDrone.Core.Music { storedAlbum.AlbumReleases.LazyLoad(); } + _eventAggregator.PublishEvent(new AlbumEditedEvent(updatedAlbum, storedAlbum)); return updatedAlbum; diff --git a/src/NzbDrone.Core/Music/Services/ArtistService.cs b/src/NzbDrone.Core/Music/Services/ArtistService.cs index 8fdc0db7c..d5cde9ec7 100644 --- a/src/NzbDrone.Core/Music/Services/ArtistService.cs +++ b/src/NzbDrone.Core/Music/Services/ArtistService.cs @@ -1,11 +1,11 @@ -using NLog; -using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Music.Events; using System; using System.Collections.Generic; using System.Linq; -using NzbDrone.Common.Extensions; +using NLog; using NzbDrone.Common.Cache; +using NzbDrone.Common.Extensions; +using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Music.Events; using NzbDrone.Core.Parser; namespace NzbDrone.Core.Music @@ -94,8 +94,9 @@ namespace NzbDrone.Core.Music public List<Tuple<Func<Artist, string, double>, string>> ArtistScoringFunctions(string title, string cleanTitle) { - Func< Func<Artist, string, double>, string, Tuple<Func<Artist, string, double>, string>> tc = Tuple.Create; - var scoringFunctions = new List<Tuple<Func<Artist, string, double>, string>> { + Func<Func<Artist, string, double>, string, Tuple<Func<Artist, string, double>, string>> tc = Tuple.Create; + var scoringFunctions = new List<Tuple<Func<Artist, string, double>, string>> + { tc((a, t) => a.CleanName.FuzzyMatch(t), cleanTitle), tc((a, t) => a.Name.FuzzyMatch(t), title), }; @@ -147,10 +148,10 @@ namespace NzbDrone.Core.Music const double fuzzGap = 0.2; var sortedArtists = artists.Select(s => new - { - MatchProb = scoreFunction(s, title), - Artist = s - }) + { + MatchProb = scoreFunction(s, title), + Artist = s + }) .ToList() .OrderByDescending(s => s.MatchProb) .ToList(); diff --git a/src/NzbDrone.Core/Music/Services/MoveArtistService.cs b/src/NzbDrone.Core/Music/Services/MoveArtistService.cs index 14d5d91a5..21ee8a2e1 100644 --- a/src/NzbDrone.Core/Music/Services/MoveArtistService.cs +++ b/src/NzbDrone.Core/Music/Services/MoveArtistService.cs @@ -4,9 +4,9 @@ using NzbDrone.Common.Disk; using NzbDrone.Common.Instrumentation.Extensions; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Organizer; using NzbDrone.Core.Music.Commands; using NzbDrone.Core.Music.Events; +using NzbDrone.Core.Organizer; namespace NzbDrone.Core.Music { diff --git a/src/NzbDrone.Core/Music/Services/RefreshAlbumReleaseService.cs b/src/NzbDrone.Core/Music/Services/RefreshAlbumReleaseService.cs index c6ab26e3a..bd5535dba 100644 --- a/src/NzbDrone.Core/Music/Services/RefreshAlbumReleaseService.cs +++ b/src/NzbDrone.Core/Music/Services/RefreshAlbumReleaseService.cs @@ -81,7 +81,7 @@ namespace NzbDrone.Core.Music .Concat(remoteChildren.SelectMany(x => x.OldForeignTrackIds))); } - protected override Tuple<Track, List<Track> > GetMatchingExistingChildren(List<Track> existingChildren, Track remote) + protected override Tuple<Track, List<Track>> GetMatchingExistingChildren(List<Track> existingChildren, Track remote) { var existingChild = existingChildren.SingleOrDefault(x => x.ForeignTrackId == remote.ForeignTrackId); var mergeChildren = existingChildren.Where(x => remote.OldForeignTrackIds.Contains(x.ForeignTrackId)).ToList(); @@ -120,4 +120,3 @@ namespace NzbDrone.Core.Music } } } - diff --git a/src/NzbDrone.Core/Music/Services/RefreshAlbumService.cs b/src/NzbDrone.Core/Music/Services/RefreshAlbumService.cs index d5b7e73df..020e093e2 100644 --- a/src/NzbDrone.Core/Music/Services/RefreshAlbumService.cs +++ b/src/NzbDrone.Core/Music/Services/RefreshAlbumService.cs @@ -69,7 +69,7 @@ namespace NzbDrone.Core.Music protected override RemoteData GetRemoteData(Album local, List<Album> remote) { var result = new RemoteData(); - + // remove not in remote list and ShouldDelete is true if (remote != null && !remote.Any(x => x.ForeignAlbumId == local.ForeignAlbumId || x.OldForeignAlbumIds.Contains(local.ForeignAlbumId)) && @@ -77,7 +77,7 @@ namespace NzbDrone.Core.Music { return result; } - + Tuple<string, Album, List<ArtistMetadata>> tuple = null; try { @@ -93,28 +93,29 @@ namespace NzbDrone.Core.Music _logger.Debug($"{local} has no valid releases, removing."); return result; } - + result.Entity = tuple.Item2; result.Entity.Id = local.Id; result.Metadata = tuple.Item3; return result; } - + protected override void EnsureNewParent(Album local, Album remote) { // Make sure the appropriate artist exists (it could be that an album changes parent) // The artistMetadata entry will be in the db but make sure a corresponding artist is too // so that the album doesn't just disappear. - + // TODO filter by metadata id before hitting database _logger.Trace($"Ensuring parent artist exists [{remote.ArtistMetadata.Value.ForeignArtistId}]"); - + var newArtist = _artistService.FindById(remote.ArtistMetadata.Value.ForeignArtistId); - + if (newArtist == null) { var oldArtist = local.Artist.Value; - var addArtist = new Artist { + var addArtist = new Artist + { Metadata = remote.ArtistMetadata.Value, MetadataProfileId = oldArtist.MetadataProfileId, QualityProfileId = oldArtist.QualityProfileId, @@ -245,13 +246,14 @@ namespace NzbDrone.Core.Music { files.AddRange(_mediaFileService.GetFilesByRelease(release.Id)); } + files.ForEach(x => x.AlbumId = entity.Id); _mediaFileService.Update(files); return children; } - protected override Tuple<AlbumRelease, List<AlbumRelease> > GetMatchingExistingChildren(List<AlbumRelease> existingChildren, AlbumRelease remote) + protected override Tuple<AlbumRelease, List<AlbumRelease>> GetMatchingExistingChildren(List<AlbumRelease> existingChildren, AlbumRelease remote) { var existingChild = existingChildren.SingleOrDefault(x => x.ForeignReleaseId == remote.ForeignReleaseId); var mergeChildren = existingChildren.Where(x => remote.OldForeignReleaseIds.Contains(x.ForeignReleaseId)).ToList(); @@ -284,7 +286,7 @@ namespace NzbDrone.Core.Music { monitored = releases; } - + var toMonitor = monitored.OrderByDescending(x => _mediaFileService.GetFilesByRelease(x.Id).Count) .ThenByDescending(x => x.TrackCount) .First(); @@ -296,13 +298,13 @@ namespace NzbDrone.Core.Music protected override bool RefreshChildren(SortedChildren localChildren, List<AlbumRelease> remoteChildren, bool forceChildRefresh, bool forceUpdateFileTags) { var refreshList = localChildren.All; - + // make sure only one of the releases ends up monitored localChildren.Old.ForEach(x => x.Monitored = false); MonitorSingleRelease(localChildren.Future); refreshList.ForEach(x => _logger.Trace($"release: {x} monitored: {x.Monitored}")); - + return _refreshAlbumReleaseService.RefreshEntityInfo(refreshList, remoteChildren, forceChildRefresh, forceUpdateFileTags); } @@ -322,6 +324,7 @@ namespace NzbDrone.Core.Music updated |= RefreshAlbumInfo(album, remoteAlbums, forceUpdateFileTags); } } + return updated; } @@ -346,4 +349,3 @@ namespace NzbDrone.Core.Music } } } - diff --git a/src/NzbDrone.Core/Music/Services/RefreshArtistService.cs b/src/NzbDrone.Core/Music/Services/RefreshArtistService.cs index 52e00c7fa..78b2779bf 100644 --- a/src/NzbDrone.Core/Music/Services/RefreshArtistService.cs +++ b/src/NzbDrone.Core/Music/Services/RefreshArtistService.cs @@ -1,21 +1,21 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; using NLog; +using NzbDrone.Common.EnsureThat; using NzbDrone.Common.Extensions; -using NzbDrone.Core.Configuration; using NzbDrone.Common.Instrumentation.Extensions; +using NzbDrone.Core.Configuration; using NzbDrone.Core.Exceptions; +using NzbDrone.Core.History; +using NzbDrone.Core.ImportLists.Exclusions; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.MetadataSource; using NzbDrone.Core.Music.Commands; using NzbDrone.Core.Music.Events; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using NzbDrone.Core.ImportLists.Exclusions; -using NzbDrone.Common.EnsureThat; -using NzbDrone.Core.History; namespace NzbDrone.Core.Music { @@ -62,7 +62,7 @@ namespace NzbDrone.Core.Music _importListExclusionService = importListExclusionService; _logger = logger; } - + protected override RemoteData GetRemoteData(Artist local, List<Artist> remote) { var result = new RemoteData(); @@ -78,17 +78,17 @@ namespace NzbDrone.Core.Music return result; } - + protected override bool ShouldDelete(Artist local) { return !_mediaFileService.GetFilesByArtist(local.Id).Any(); } - + protected override void LogProgress(Artist local) { - _logger.ProgressInfo("Updating Info for {0}", local.Name); + _logger.ProgressInfo("Updating Info for {0}", local.Name); } - + protected override bool IsMerge(Artist local, Artist remote) { return local.ArtistMetadataId != remote.Metadata.Value.Id; @@ -97,8 +97,8 @@ namespace NzbDrone.Core.Music protected override UpdateResult UpdateEntity(Artist local, Artist remote) { UpdateResult result = UpdateResult.None; - - if(!local.Metadata.Value.Equals(remote.Metadata.Value)) + + if (!local.Metadata.Value.Equals(remote.Metadata.Value)) { result = UpdateResult.UpdateTags; } @@ -119,7 +119,7 @@ namespace NzbDrone.Core.Music return result; } - + protected override UpdateResult MoveEntity(Artist local, Artist remote) { _logger.Debug($"Updating MusicBrainz id for {local} to {remote}"); @@ -139,7 +139,7 @@ namespace NzbDrone.Core.Music // Do the standard update UpdateEntity(local, remote); - + // We know we need to update tags as artist id has changed return UpdateResult.UpdateTags; } @@ -205,14 +205,14 @@ namespace NzbDrone.Core.Music remoteChildren.Select(x => x.ForeignAlbumId) .Concat(remoteChildren.SelectMany(x => x.OldForeignAlbumIds))); } - - protected override Tuple<Album, List<Album> > GetMatchingExistingChildren(List<Album> existingChildren, Album remote) + + protected override Tuple<Album, List<Album>> GetMatchingExistingChildren(List<Album> existingChildren, Album remote) { var existingChild = existingChildren.SingleOrDefault(x => x.ForeignAlbumId == remote.ForeignAlbumId); var mergeChildren = existingChildren.Where(x => remote.OldForeignAlbumIds.Contains(x.ForeignAlbumId)).ToList(); return Tuple.Create(existingChild, mergeChildren); } - + protected override void PrepareNewChild(Album child, Artist entity) { child.Artist = entity; @@ -223,14 +223,14 @@ namespace NzbDrone.Core.Music child.ProfileId = entity.QualityProfileId; child.Monitored = entity.Monitored; } - + protected override void PrepareExistingChild(Album local, Album remote, Artist entity) { local.Artist = entity; local.ArtistMetadata = entity.Metadata.Value; local.ArtistMetadataId = entity.Metadata.Value.Id; } - + protected override void AddChildren(List<Album> children) { _albumService.InsertMany(children); @@ -242,7 +242,7 @@ namespace NzbDrone.Core.Music Ensure.That(localChildren.UpToDate.Count, () => localChildren.UpToDate.Count).IsLessThanOrEqualTo(0); return _refreshAlbumService.RefreshAlbumInfo(localChildren.All, remoteChildren, forceChildRefresh, forceUpdateFileTags); } - + protected override void PublishEntityUpdatedEvent(Artist entity) { _eventAggregator.PublishEvent(new ArtistUpdatedEvent(entity)); @@ -268,13 +268,11 @@ namespace NzbDrone.Core.Music _logger.Trace("Forcing rescan of {0}. Reason: New artist", artist); shouldRescan = true; } - else if (rescanAfterRefresh == RescanAfterRefreshType.Never) { _logger.Trace("Skipping rescan of {0}. Reason: never recan after refresh", artist); shouldRescan = false; } - else if (rescanAfterRefresh == RescanAfterRefreshType.AfterManual && trigger != CommandTrigger.Manual) { _logger.Trace("Skipping rescan of {0}. Reason: not after automatic scans", artist); diff --git a/src/NzbDrone.Core/Music/Services/RefreshEntityServiceBase.cs b/src/NzbDrone.Core/Music/Services/RefreshEntityServiceBase.cs index 095c69cd1..b03a08361 100644 --- a/src/NzbDrone.Core/Music/Services/RefreshEntityServiceBase.cs +++ b/src/NzbDrone.Core/Music/Services/RefreshEntityServiceBase.cs @@ -1,12 +1,12 @@ -using NLog; -using NzbDrone.Common.Extensions; using System; using System.Collections.Generic; using System.Linq; +using NLog; +using NzbDrone.Common.Extensions; namespace NzbDrone.Core.Music { - public abstract class RefreshEntityServiceBase<Entity, Child> + public abstract class RefreshEntityServiceBase<TEntity, TChild> { private readonly Logger _logger; private readonly IArtistMetadataService _artistMetadataService; @@ -17,103 +17,103 @@ namespace NzbDrone.Core.Music _logger = logger; _artistMetadataService = artistMetadataService; } - + public enum UpdateResult { None, Standard, UpdateTags - }; + } public class SortedChildren { public SortedChildren() { - UpToDate = new List<Child>(); - Added = new List<Child>(); - Updated = new List<Child>(); - Merged = new List<Tuple<Child, Child> >(); - Deleted = new List<Child>(); + UpToDate = new List<TChild>(); + Added = new List<TChild>(); + Updated = new List<TChild>(); + Merged = new List<Tuple<TChild, TChild>>(); + Deleted = new List<TChild>(); } - public List<Child> UpToDate { get; set; } - public List<Child> Added { get; set; } - public List<Child> Updated { get; set; } - public List<Tuple<Child, Child> > Merged { get; set; } - public List<Child> Deleted { get; set; } - - public List<Child> All => UpToDate.Concat(Added).Concat(Updated).Concat(Merged.Select(x => x.Item1)).Concat(Deleted).ToList(); - public List<Child> Future => UpToDate.Concat(Added).Concat(Updated).ToList(); - public List<Child> Old => Merged.Select(x => x.Item1).Concat(Deleted).ToList(); + public List<TChild> UpToDate { get; set; } + public List<TChild> Added { get; set; } + public List<TChild> Updated { get; set; } + public List<Tuple<TChild, TChild>> Merged { get; set; } + public List<TChild> Deleted { get; set; } + + public List<TChild> All => UpToDate.Concat(Added).Concat(Updated).Concat(Merged.Select(x => x.Item1)).Concat(Deleted).ToList(); + public List<TChild> Future => UpToDate.Concat(Added).Concat(Updated).ToList(); + public List<TChild> Old => Merged.Select(x => x.Item1).Concat(Deleted).ToList(); } public class RemoteData { - public Entity Entity { get; set; } + public TEntity Entity { get; set; } public List<ArtistMetadata> Metadata { get; set; } } - protected virtual void LogProgress(Entity local) + protected virtual void LogProgress(TEntity local) { } - - protected abstract RemoteData GetRemoteData(Entity local, List<Entity> remote); - protected virtual void EnsureNewParent(Entity local, Entity remote) + protected abstract RemoteData GetRemoteData(TEntity local, List<TEntity> remote); + + protected virtual void EnsureNewParent(TEntity local, TEntity remote) { } - - protected abstract bool IsMerge(Entity local, Entity remote); - - protected virtual bool ShouldDelete(Entity local) + + protected abstract bool IsMerge(TEntity local, TEntity remote); + + protected virtual bool ShouldDelete(TEntity local) { return true; } - - protected abstract UpdateResult UpdateEntity(Entity local, Entity remote); - - protected virtual UpdateResult MoveEntity(Entity local, Entity remote) + + protected abstract UpdateResult UpdateEntity(TEntity local, TEntity remote); + + protected virtual UpdateResult MoveEntity(TEntity local, TEntity remote) { return UpdateEntity(local, remote); } - - protected virtual UpdateResult MergeEntity(Entity local, Entity target, Entity remote) + + protected virtual UpdateResult MergeEntity(TEntity local, TEntity target, TEntity remote) { DeleteEntity(local, true); return UpdateResult.UpdateTags; } - protected abstract Entity GetEntityByForeignId(Entity local); - protected abstract void SaveEntity(Entity local); - protected abstract void DeleteEntity(Entity local, bool deleteFiles); - - protected abstract List<Child> GetRemoteChildren(Entity remote); - protected abstract List<Child> GetLocalChildren(Entity entity, List<Child> remoteChildren); - protected abstract Tuple<Child, List<Child> > GetMatchingExistingChildren(List<Child> existingChildren, Child remote); - - protected abstract void PrepareNewChild(Child child, Entity entity); - protected abstract void PrepareExistingChild(Child local, Child remote, Entity entity); - protected abstract void AddChildren(List<Child> children); - protected abstract bool RefreshChildren(SortedChildren localChildren, List<Child> remoteChildren, bool forceChildRefresh, bool forceUpdateFileTags); + protected abstract TEntity GetEntityByForeignId(TEntity local); + protected abstract void SaveEntity(TEntity local); + protected abstract void DeleteEntity(TEntity local, bool deleteFiles); - protected virtual void PublishEntityUpdatedEvent(Entity entity) + protected abstract List<TChild> GetRemoteChildren(TEntity remote); + protected abstract List<TChild> GetLocalChildren(TEntity entity, List<TChild> remoteChildren); + protected abstract Tuple<TChild, List<TChild>> GetMatchingExistingChildren(List<TChild> existingChildren, TChild remote); + + protected abstract void PrepareNewChild(TChild child, TEntity entity); + protected abstract void PrepareExistingChild(TChild local, TChild remote, TEntity entity); + protected abstract void AddChildren(List<TChild> children); + protected abstract bool RefreshChildren(SortedChildren localChildren, List<TChild> remoteChildren, bool forceChildRefresh, bool forceUpdateFileTags); + + protected virtual void PublishEntityUpdatedEvent(TEntity entity) { } - protected virtual void PublishRefreshCompleteEvent(Entity entity) + protected virtual void PublishRefreshCompleteEvent(TEntity entity) { } - protected virtual void PublishChildrenUpdatedEvent(Entity entity, List<Child> newChildren, List<Child> updateChildren) + protected virtual void PublishChildrenUpdatedEvent(TEntity entity, List<TChild> newChildren, List<TChild> updateChildren) { } - public bool RefreshEntityInfo(Entity local, List<Entity> remoteList, bool forceChildRefresh, bool forceUpdateFileTags) + public bool RefreshEntityInfo(TEntity local, List<TEntity> remoteList, bool forceChildRefresh, bool forceUpdateFileTags) { bool updated = false; - + LogProgress(local); - + var data = GetRemoteData(local, remoteList); var remote = data.Entity; @@ -121,13 +121,13 @@ namespace NzbDrone.Core.Music { if (ShouldDelete(local)) { - _logger.Warn($"{typeof(Entity).Name} {local} not found in metadata and is being deleted"); + _logger.Warn($"{typeof(TEntity).Name} {local} not found in metadata and is being deleted"); DeleteEntity(local, true); return false; } else { - _logger.Error($"{typeof(Entity).Name} {local} was not found, it may have been removed from Metadata sources."); + _logger.Error($"{typeof(TEntity).Name} {local} was not found, it may have been removed from Metadata sources."); return false; } } @@ -147,15 +147,15 @@ namespace NzbDrone.Core.Music { // get entity we're merging into var target = GetEntityByForeignId(remote); - + if (target == null) { - _logger.Trace($"Moving {typeof(Entity).Name} {local} to {remote}"); + _logger.Trace($"Moving {typeof(TEntity).Name} {local} to {remote}"); result = MoveEntity(local, remote); } else { - _logger.Trace($"Merging {typeof(Entity).Name} {local} into {target}"); + _logger.Trace($"Merging {typeof(TEntity).Name} {local} into {target}"); result = MergeEntity(local, target, remote); // having merged local into target, do update for target using remote @@ -167,7 +167,7 @@ namespace NzbDrone.Core.Music } else { - _logger.Trace($"Updating {typeof(Entity).Name} {local}"); + _logger.Trace($"Updating {typeof(TEntity).Name} {local}"); result = UpdateEntity(local, remote); } @@ -175,12 +175,12 @@ namespace NzbDrone.Core.Music forceUpdateFileTags |= result == UpdateResult.UpdateTags; _logger.Trace($"updated: {updated} forceUpdateFileTags: {forceUpdateFileTags}"); - + var remoteChildren = GetRemoteChildren(remote); updated |= SortChildren(local, remoteChildren, forceChildRefresh, forceUpdateFileTags); // Do this last so entity only marked as refreshed if refresh of children completed successfully - _logger.Trace($"Saving {typeof(Entity).Name} {local}"); + _logger.Trace($"Saving {typeof(TEntity).Name} {local}"); SaveEntity(local); if (updated) @@ -190,18 +190,19 @@ namespace NzbDrone.Core.Music PublishRefreshCompleteEvent(local); - _logger.Debug($"Finished {typeof(Entity).Name} refresh for {local}"); + _logger.Debug($"Finished {typeof(TEntity).Name} refresh for {local}"); return updated; } - public bool RefreshEntityInfo(List<Entity> localList, List<Entity> remoteList, bool forceChildRefresh, bool forceUpdateFileTags) + public bool RefreshEntityInfo(List<TEntity> localList, List<TEntity> remoteList, bool forceChildRefresh, bool forceUpdateFileTags) { bool updated = false; foreach (var entity in localList) { updated |= RefreshEntityInfo(entity, remoteList, forceChildRefresh, forceUpdateFileTags); } + return updated; } @@ -212,7 +213,7 @@ namespace NzbDrone.Core.Music return updated ? UpdateResult.UpdateTags : UpdateResult.None; } - protected bool SortChildren(Entity entity, List<Child> remoteChildren, bool forceChildRefresh, bool forceUpdateFileTags) + protected bool SortChildren(TEntity entity, List<TChild> remoteChildren, bool forceChildRefresh, bool forceUpdateFileTags) { // Get existing children (and children to be) from the database var localChildren = GetLocalChildren(entity, remoteChildren); @@ -254,27 +255,31 @@ namespace NzbDrone.Core.Music { PrepareNewChild(remoteChild, entity); sortedChildren.Added.Add(remoteChild); - + // note the children that will be merged into remoteChild (once added) foreach (var child in mergedChildren) { sortedChildren.Merged.Add(Tuple.Create(child, remoteChild)); sortedChildren.Deleted.Remove(child); } - } } _logger.Debug("{0} {1} {2}s up to date. Adding {3}, Updating {4}, Merging {5}, Deleting {6}.", - entity, sortedChildren.UpToDate.Count, typeof(Child).Name.ToLower(), - sortedChildren.Added.Count, sortedChildren.Updated.Count, sortedChildren.Merged.Count, sortedChildren.Deleted.Count); + entity, + sortedChildren.UpToDate.Count, + typeof(TChild).Name.ToLower(), + sortedChildren.Added.Count, + sortedChildren.Updated.Count, + sortedChildren.Merged.Count, + sortedChildren.Deleted.Count); // Add in the new children (we have checked that foreign IDs don't clash) AddChildren(sortedChildren.Added); // now trigger updates var updated = RefreshChildren(sortedChildren, remoteChildren, forceChildRefresh, forceUpdateFileTags); - + PublishChildrenUpdatedEvent(entity, sortedChildren.Added, sortedChildren.Updated); return updated; } diff --git a/src/NzbDrone.Core/Music/Services/RefreshTrackService.cs b/src/NzbDrone.Core/Music/Services/RefreshTrackService.cs index c89cc3ed1..947e4bec2 100644 --- a/src/NzbDrone.Core/Music/Services/RefreshTrackService.cs +++ b/src/NzbDrone.Core/Music/Services/RefreshTrackService.cs @@ -1,14 +1,14 @@ -using NLog; -using NzbDrone.Core.MediaFiles; using System; using System.Collections.Generic; using System.Linq; +using NLog; +using NzbDrone.Core.MediaFiles; namespace NzbDrone.Core.Music { public interface IRefreshTrackService { - bool RefreshTrackInfo(List<Track> add, List<Track> update, List<Tuple<Track, Track> > merge, List<Track> delete, List<Track> upToDate, List<Track> remoteTracks, bool forceUpdateFileTags); + bool RefreshTrackInfo(List<Track> add, List<Track> update, List<Tuple<Track, Track>> merge, List<Track> delete, List<Track> upToDate, List<Track> remoteTracks, bool forceUpdateFileTags); } public class RefreshTrackService : IRefreshTrackService @@ -26,7 +26,7 @@ namespace NzbDrone.Core.Music _logger = logger; } - public bool RefreshTrackInfo(List<Track> add, List<Track> update, List<Tuple<Track, Track> > merge, List<Track> delete, List<Track> upToDate, List<Track> remoteTracks, bool forceUpdateFileTags) + public bool RefreshTrackInfo(List<Track> add, List<Track> update, List<Tuple<Track, Track>> merge, List<Track> delete, List<Track> upToDate, List<Track> remoteTracks, bool forceUpdateFileTags) { var updateList = new List<Track>(); @@ -40,7 +40,7 @@ namespace NzbDrone.Core.Music track.Title = track.Title ?? "Unknown"; updateList.Add(track); } - + // Move trackfiles from merged entities into new one foreach (var item in merge) { @@ -67,10 +67,10 @@ namespace NzbDrone.Core.Music _logger.Debug("Forcing tag update due to Artist/Album/Release updates"); tagsToUpdate = updateList.Concat(upToDate).ToList(); } + _audioTagService.SyncTags(tagsToUpdate); return add.Any() || delete.Any() || updateList.Any() || merge.Any(); } } } - diff --git a/src/NzbDrone.Core/Music/Services/ReleaseService.cs b/src/NzbDrone.Core/Music/Services/ReleaseService.cs index a8bb90057..7b86ced1a 100644 --- a/src/NzbDrone.Core/Music/Services/ReleaseService.cs +++ b/src/NzbDrone.Core/Music/Services/ReleaseService.cs @@ -1,6 +1,6 @@ +using System.Collections.Generic; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Music.Events; -using System.Collections.Generic; namespace NzbDrone.Core.Music { @@ -84,6 +84,5 @@ namespace NzbDrone.Core.Music var releases = GetReleasesByAlbum(message.Album.Id); DeleteMany(releases); } - } } diff --git a/src/NzbDrone.Core/Music/Services/TrackService.cs b/src/NzbDrone.Core/Music/Services/TrackService.cs index a7f33384f..50c4d8891 100644 --- a/src/NzbDrone.Core/Music/Services/TrackService.cs +++ b/src/NzbDrone.Core/Music/Services/TrackService.cs @@ -1,9 +1,9 @@ +using System.Collections.Generic; +using System.Linq; using NLog; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Music.Events; -using System.Collections.Generic; -using System.Linq; namespace NzbDrone.Core.Music { diff --git a/src/NzbDrone.Core/Music/Utilities/AddArtistValidator.cs b/src/NzbDrone.Core/Music/Utilities/AddArtistValidator.cs index 75294bf50..745cb7f9d 100644 --- a/src/NzbDrone.Core/Music/Utilities/AddArtistValidator.cs +++ b/src/NzbDrone.Core/Music/Utilities/AddArtistValidator.cs @@ -1,7 +1,7 @@ using FluentValidation; using FluentValidation.Results; -using NzbDrone.Core.Validation.Paths; using NzbDrone.Core.Validation; +using NzbDrone.Core.Validation.Paths; namespace NzbDrone.Core.Music { @@ -27,7 +27,6 @@ namespace NzbDrone.Core.Music RuleFor(c => c.QualityProfileId).SetValidator(profileExistsValidator); RuleFor(c => c.MetadataProfileId).SetValidator(metadataProfileExistsValidator); - } } } diff --git a/src/NzbDrone.Core/Music/Utilities/ShouldRefreshAlbum.cs b/src/NzbDrone.Core/Music/Utilities/ShouldRefreshAlbum.cs index ee8d6383a..5dac303ce 100644 --- a/src/NzbDrone.Core/Music/Utilities/ShouldRefreshAlbum.cs +++ b/src/NzbDrone.Core/Music/Utilities/ShouldRefreshAlbum.cs @@ -1,5 +1,5 @@ -using NLog; using System; +using NLog; namespace NzbDrone.Core.Music { diff --git a/src/NzbDrone.Core/Music/Utilities/ShouldRefreshArtist.cs b/src/NzbDrone.Core/Music/Utilities/ShouldRefreshArtist.cs index 4e8c975e8..dc9fca5c7 100644 --- a/src/NzbDrone.Core/Music/Utilities/ShouldRefreshArtist.cs +++ b/src/NzbDrone.Core/Music/Utilities/ShouldRefreshArtist.cs @@ -1,6 +1,6 @@ -using NLog; using System; using System.Linq; +using NLog; namespace NzbDrone.Core.Music { diff --git a/src/NzbDrone.Core/Notifications/Boxcar/BoxcarException.cs b/src/NzbDrone.Core/Notifications/Boxcar/BoxcarException.cs index 139c3b1ab..6108d4aab 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 75b70c415..9ec8c48dc 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 @@ namespace NzbDrone.Core.Notifications.Boxcar 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/Discord/Discord.cs b/src/NzbDrone.Core/Notifications/Discord/Discord.cs index 42a5a5729..9c02ea444 100644 --- a/src/NzbDrone.Core/Notifications/Discord/Discord.cs +++ b/src/NzbDrone.Core/Notifications/Discord/Discord.cs @@ -2,8 +2,8 @@ using System; using System.Collections.Generic; using FluentValidation.Results; using NzbDrone.Common.Extensions; -using NzbDrone.Core.Notifications.Discord.Payloads; using NzbDrone.Core.Music; +using NzbDrone.Core.Notifications.Discord.Payloads; using NzbDrone.Core.Validation; namespace NzbDrone.Core.Notifications.Discord @@ -153,7 +153,6 @@ namespace NzbDrone.Core.Notifications.Discord 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 1bc0d6294..155277d80 100644 --- a/src/NzbDrone.Core/Notifications/Discord/DiscordException.cs +++ b/src/NzbDrone.Core/Notifications/Discord/DiscordException.cs @@ -3,13 +3,15 @@ using NzbDrone.Common.Exceptions; namespace NzbDrone.Core.Notifications.Discord { - class DiscordException : NzbDroneException + internal 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 425364253..37ecf794d 100644 --- a/src/NzbDrone.Core/Notifications/Discord/DiscordProxy.cs +++ b/src/NzbDrone.Core/Notifications/Discord/DiscordProxy.cs @@ -34,7 +34,7 @@ namespace NzbDrone.Core.Notifications.Discord 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 e4ba51571..d98693824 100644 --- a/src/NzbDrone.Core/Notifications/Discord/DiscordSettings.cs +++ b/src/NzbDrone.Core/Notifications/Discord/DiscordSettings.cs @@ -26,7 +26,6 @@ namespace NzbDrone.Core.Notifications.Discord [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/DownloadFailedMessage.cs b/src/NzbDrone.Core/Notifications/DownloadFailedMessage.cs index 9af4d2577..fac0e8297 100644 --- a/src/NzbDrone.Core/Notifications/DownloadFailedMessage.cs +++ b/src/NzbDrone.Core/Notifications/DownloadFailedMessage.cs @@ -1,6 +1,4 @@ -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Notifications { diff --git a/src/NzbDrone.Core/Notifications/Email/Email.cs b/src/NzbDrone.Core/Notifications/Email/Email.cs index 3ecc2f11a..d967962cd 100644 --- a/src/NzbDrone.Core/Notifications/Email/Email.cs +++ b/src/NzbDrone.Core/Notifications/Email/Email.cs @@ -10,7 +10,6 @@ namespace NzbDrone.Core.Notifications.Email 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 7cd8bf0c5..0585e76f6 100644 --- a/src/NzbDrone.Core/Notifications/Email/EmailService.cs +++ b/src/NzbDrone.Core/Notifications/Email/EmailService.cs @@ -25,7 +25,7 @@ namespace NzbDrone.Core.Notifications.Email { var email = new MailMessage(); email.From = new MailAddress(settings.From); - + email.To.Add(settings.To); email.Subject = subject; @@ -35,13 +35,15 @@ namespace NzbDrone.Core.Notifications.Email 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 8782d4dcd..9a5f9c5dc 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 b14b530d3..a6e711516 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 0a4c20b4d..acdc931f9 100644 --- a/src/NzbDrone.Core/Notifications/Gotify/InvalidResponseException.cs +++ b/src/NzbDrone.Core/Notifications/Gotify/InvalidResponseException.cs @@ -8,7 +8,8 @@ namespace NzbDrone.Core.Notifications.Gotify { } - 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 b9eda36cd..8b0974b9c 100644 --- a/src/NzbDrone.Core/Notifications/GrabMessage.cs +++ b/src/NzbDrone.Core/Notifications/GrabMessage.cs @@ -1,6 +1,6 @@ +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Notifications { diff --git a/src/NzbDrone.Core/Notifications/INotification.cs b/src/NzbDrone.Core/Notifications/INotification.cs index c5ec56f0e..2d08d3316 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.Music; +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 92b977722..12c55b2c3 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 e0ad0e1c3..18ef5e2f2 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 a6463abb4..d79e989ec 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 50ee7b981..43cc73945 100644 --- a/src/NzbDrone.Core/Notifications/Join/JoinProxy.cs +++ b/src/NzbDrone.Core/Notifications/Join/JoinProxy.cs @@ -2,9 +2,9 @@ using System; 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 @@ namespace NzbDrone.Core.Notifications.Join 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 @@ namespace NzbDrone.Core.Notifications.Join 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 @@ namespace NzbDrone.Core.Notifications.Join _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 @@ namespace NzbDrone.Core.Notifications.Join private void SendNotification(string title, string message, RestRequest request, JoinSettings settings) { - var client = RestClientFactory.BuildClient(URL); if (settings.DeviceNames.IsNotNullOrWhiteSpace()) @@ -99,7 +98,10 @@ namespace NzbDrone.Core.Notifications.Join 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 @@ namespace NzbDrone.Core.Notifications.Join { 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 @@ namespace NzbDrone.Core.Notifications.Join { throw new JoinAuthException("Authentication failed."); } + throw new JoinException(res.errorMessage); } diff --git a/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowser.cs b/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowser.cs index ad2ff5bea..8a5117578 100644 --- a/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowser.cs +++ b/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowser.cs @@ -17,7 +17,6 @@ namespace NzbDrone.Core.Notifications.Emby public override string Link => "https://emby.media/"; public override string Name => "Emby (Media Browser)"; - public override void OnGrab(GrabMessage grabMessage) { if (Settings.Notify) diff --git a/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserService.cs b/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserService.cs index 34cae900c..f54c3b1bf 100644 --- a/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserService.cs +++ b/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserService.cs @@ -3,8 +3,8 @@ using System.Linq; using System.Net; using FluentValidation.Results; using NLog; -using NzbDrone.Core.Rest; using NzbDrone.Core.Music; +using NzbDrone.Core.Rest; namespace NzbDrone.Core.Notifications.Emby { diff --git a/src/NzbDrone.Core/Notifications/MediaBrowser/Model/EmbyMediaFolder.cs b/src/NzbDrone.Core/Notifications/MediaBrowser/Model/EmbyMediaFolder.cs index e6a7c3559..68b421ead 100644 --- a/src/NzbDrone.Core/Notifications/MediaBrowser/Model/EmbyMediaFolder.cs +++ b/src/NzbDrone.Core/Notifications/MediaBrowser/Model/EmbyMediaFolder.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; - namespace NzbDrone.Core.Notifications.MediaBrowser.Model { public class EmbyMediaFolder diff --git a/src/NzbDrone.Core/Notifications/MediaBrowser/Model/EmbyMediaUpdateInfo.cs b/src/NzbDrone.Core/Notifications/MediaBrowser/Model/EmbyMediaUpdateInfo.cs index 38cd68694..292ce81a7 100644 --- a/src/NzbDrone.Core/Notifications/MediaBrowser/Model/EmbyMediaUpdateInfo.cs +++ b/src/NzbDrone.Core/Notifications/MediaBrowser/Model/EmbyMediaUpdateInfo.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; - namespace NzbDrone.Core.Notifications.MediaBrowser.Model { public class EmbyMediaUpdateInfo diff --git a/src/NzbDrone.Core/Notifications/NotificationBase.cs b/src/NzbDrone.Core/Notifications/NotificationBase.cs index f7b91b49d..60b89fc67 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.Music; +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 ALBUM_GRABBED_TITLE = "Album Grabbed"; protected const string ALBUM_DOWNLOADED_TITLE = "Album Downloaded"; @@ -37,37 +38,30 @@ namespace NzbDrone.Core.Notifications public virtual void OnGrab(GrabMessage grabMessage) { - } public virtual void OnReleaseImport(AlbumDownloadMessage message) { - } public virtual void OnRename(Artist artist) { - } public virtual void OnHealthIssue(HealthCheck.HealthCheck healthCheck) { - } public virtual void OnDownloadFailure(DownloadFailedMessage message) { - } public virtual void OnImportFailure(AlbumDownloadMessage message) { - } public virtual void OnTrackRetag(TrackRetagMessage message) { - } public bool SupportsOnGrab => HasConcreteImplementation("OnGrab"); @@ -86,8 +80,10 @@ namespace NzbDrone.Core.Notifications 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) { @@ -100,6 +96,5 @@ namespace NzbDrone.Core.Notifications return !method.DeclaringType.IsAbstract; } - } } diff --git a/src/NzbDrone.Core/Notifications/NotificationDefinition.cs b/src/NzbDrone.Core/Notifications/NotificationDefinition.cs index 350ddda61..c3fb84387 100644 --- a/src/NzbDrone.Core/Notifications/NotificationDefinition.cs +++ b/src/NzbDrone.Core/Notifications/NotificationDefinition.cs @@ -4,7 +4,6 @@ namespace NzbDrone.Core.Notifications { public class NotificationDefinition : ProviderDefinition { - public bool OnGrab { get; set; } public bool OnReleaseImport { get; set; } public bool OnUpgrade { get; set; } diff --git a/src/NzbDrone.Core/Notifications/NotificationRepository.cs b/src/NzbDrone.Core/Notifications/NotificationRepository.cs index d163e1946..4a6482177 100644 --- a/src/NzbDrone.Core/Notifications/NotificationRepository.cs +++ b/src/NzbDrone.Core/Notifications/NotificationRepository.cs @@ -2,7 +2,6 @@ using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.ThingiProvider; - namespace NzbDrone.Core.Notifications { public interface INotificationRepository : IProviderRepository<NotificationDefinition> diff --git a/src/NzbDrone.Core/Notifications/NotificationService.cs b/src/NzbDrone.Core/Notifications/NotificationService.cs index 98e57f5e3..adb524355 100644 --- a/src/NzbDrone.Core/Notifications/NotificationService.cs +++ b/src/NzbDrone.Core/Notifications/NotificationService.cs @@ -4,14 +4,13 @@ using System.Linq; using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Core.Download; +using NzbDrone.Core.HealthCheck; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Music; using NzbDrone.Core.Qualities; using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Music; -using NzbDrone.Core.HealthCheck; -using System.IO; namespace NzbDrone.Core.Notifications { @@ -42,7 +41,6 @@ namespace NzbDrone.Core.Notifications qualityString += " Proper"; } - var albumTitles = string.Join(" + ", albums.Select(e => e.Title)); return string.Format("{0} - {1} - [{2}]", @@ -128,10 +126,13 @@ namespace NzbDrone.Core.Notifications { try { - if (!ShouldHandleArtist(notification.Definition, message.Album.Artist)) continue; + if (!ShouldHandleArtist(notification.Definition, message.Album.Artist)) + { + continue; + } + notification.OnGrab(grabMessage); } - catch (Exception ex) { _logger.Error(ex, "Unable to send OnGrab notification to {0}", notification.Definition.Name); @@ -147,7 +148,6 @@ namespace NzbDrone.Core.Notifications } var downloadMessage = new AlbumDownloadMessage - { Message = GetAlbumDownloadMessage(message.Artist, message.Album, message.ImportedTracks), Artist = message.Artist, @@ -171,7 +171,6 @@ namespace NzbDrone.Core.Notifications } } } - catch (Exception ex) { _logger.Warn(ex, "Unable to send OnReleaseImport notification to: " + notification.Definition.Name); @@ -190,7 +189,6 @@ namespace NzbDrone.Core.Notifications notification.OnRename(message.Artist); } } - catch (Exception ex) { _logger.Warn(ex, "Unable to send OnRename notification to: " + notification.Definition.Name); @@ -209,7 +207,6 @@ namespace NzbDrone.Core.Notifications 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/Plex/PlexAuthenticationException.cs b/src/NzbDrone.Core/Notifications/Plex/PlexAuthenticationException.cs index 86a0d15ec..4235168b4 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 789e3fa51..dae85f6d9 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 8866775c6..533f5d866 100644 --- a/src/NzbDrone.Core/Notifications/Plex/PlexTv/PlexTvService.cs +++ b/src/NzbDrone.Core/Notifications/Plex/PlexTv/PlexTvService.cs @@ -1,5 +1,4 @@ using System.Linq; -using System.Text; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; @@ -43,10 +42,10 @@ namespace NzbDrone.Core.Notifications.Plex.PlexTv 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) @@ -68,10 +67,10 @@ namespace NzbDrone.Core.Notifications.Plex.PlexTv 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 439cb57ac..42c7889da 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 636f85997..565b7c99c 100644 --- a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServer.cs +++ b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServer.cs @@ -3,8 +3,8 @@ using System.Collections.Generic; using FluentValidation.Results; using NzbDrone.Common.Extensions; using NzbDrone.Core.Exceptions; -using NzbDrone.Core.Notifications.Plex.PlexTv; using NzbDrone.Core.Music; +using NzbDrone.Core.Notifications.Plex.PlexTv; using NzbDrone.Core.Validation; namespace NzbDrone.Core.Notifications.Plex.Server diff --git a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerProxy.cs b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerProxy.cs index 1fdd63df8..9ae241580 100644 --- a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerProxy.cs +++ b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerProxy.cs @@ -97,6 +97,7 @@ namespace NzbDrone.Core.Notifications.Plex.Server .MediaContainer .Version; } + public List<PlexPreference> Preferences(PlexServerSettings settings) { var request = BuildRequest(":/prefs", HttpMethod.GET, settings); @@ -187,6 +188,7 @@ namespace NzbDrone.Core.Notifications.Plex.Server { throw new PlexAuthenticationException("Unauthorized - AuthToken is invalid"); } + throw new PlexException("Unable to connect to Plex Media Server. Status Code: {0}", ex.Response.StatusCode); } catch (WebException ex) diff --git a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerService.cs b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerService.cs index e29191c46..fb549e89d 100644 --- a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerService.cs +++ b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerService.cs @@ -47,14 +47,12 @@ namespace NzbDrone.Core.Notifications.Plex.Server { UpdatePartialSection(artist, 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; @@ -107,7 +105,7 @@ namespace NzbDrone.Core.Notifications.Plex.Server var rawVersion = _plexServerProxy.Version(settings); var version = new Version(Regex.Match(rawVersion, @"^(\d+[.-]){4}").Value.Trim('.', '-')); - + return version; } @@ -168,7 +166,7 @@ namespace NzbDrone.Core.Notifications.Plex.Server return new ValidationFailure("Host", "At least one Music 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 bede24023..9f7b7ea75 100644 --- a/src/NzbDrone.Core/Notifications/PushBullet/PushBullet.cs +++ b/src/NzbDrone.Core/Notifications/PushBullet/PushBullet.cs @@ -70,15 +70,15 @@ namespace NzbDrone.Core.Notifications.PushBullet 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 + }) + }; } return new { }; diff --git a/src/NzbDrone.Core/Notifications/PushBullet/PushBulletException.cs b/src/NzbDrone.Core/Notifications/PushBullet/PushBulletException.cs index ce8b8417d..f8207ef01 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 8bc8a04a9..0bce61c61 100644 --- a/src/NzbDrone.Core/Notifications/PushBullet/PushBulletProxy.cs +++ b/src/NzbDrone.Core/Notifications/PushBullet/PushBulletProxy.cs @@ -4,10 +4,10 @@ using System.Linq; 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 @@ namespace NzbDrone.Core.Notifications.PushBullet 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 @@ namespace NzbDrone.Core.Notifications.PushBullet { request.AddParameter("device_id", integerId); } - else { request.AddParameter("device_iden", deviceId); diff --git a/src/NzbDrone.Core/Notifications/Pushover/InvalidResponseException.cs b/src/NzbDrone.Core/Notifications/Pushover/InvalidResponseException.cs index 7e6fc1f4a..6f9c139a2 100644 --- a/src/NzbDrone.Core/Notifications/Pushover/InvalidResponseException.cs +++ b/src/NzbDrone.Core/Notifications/Pushover/InvalidResponseException.cs @@ -8,7 +8,8 @@ namespace NzbDrone.Core.Notifications.Pushover { } - public InvalidResponseException(string message) : base(message) + public InvalidResponseException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Notifications/Pushover/Pushover.cs b/src/NzbDrone.Core/Notifications/Pushover/Pushover.cs index f9d7e662e..d1a841332 100644 --- a/src/NzbDrone.Core/Notifications/Pushover/Pushover.cs +++ b/src/NzbDrone.Core/Notifications/Pushover/Pushover.cs @@ -7,7 +7,7 @@ namespace NzbDrone.Core.Notifications.Pushover public class Pushover : NotificationBase<PushoverSettings> { private readonly IPushoverProxy _proxy; - + public Pushover(IPushoverProxy proxy) { _proxy = proxy; diff --git a/src/NzbDrone.Core/Notifications/Pushover/PushoverProxy.cs b/src/NzbDrone.Core/Notifications/Pushover/PushoverProxy.cs index 2dd303c10..8fcfc45bf 100644 --- a/src/NzbDrone.Core/Notifications/Pushover/PushoverProxy.cs +++ b/src/NzbDrone.Core/Notifications/Pushover/PushoverProxy.cs @@ -2,8 +2,8 @@ using System; 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 @@ namespace NzbDrone.Core.Notifications.Pushover 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) { @@ -45,7 +45,6 @@ namespace NzbDrone.Core.Notifications.Pushover 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 29ac22032..1273fdc01 100644 --- a/src/NzbDrone.Core/Notifications/Pushover/PushoverSettings.cs +++ b/src/NzbDrone.Core/Notifications/Pushover/PushoverSettings.cs @@ -1,8 +1,8 @@ +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 { diff --git a/src/NzbDrone.Core/Notifications/Slack/Slack.cs b/src/NzbDrone.Core/Notifications/Slack/Slack.cs index d77313e36..6040daa64 100644 --- a/src/NzbDrone.Core/Notifications/Slack/Slack.cs +++ b/src/NzbDrone.Core/Notifications/Slack/Slack.cs @@ -2,12 +2,10 @@ using System; using System.Collections.Generic; using FluentValidation.Results; using NzbDrone.Common.Extensions; -using NzbDrone.Core.Notifications.Slack.Payloads; -using NzbDrone.Core.Rest; using NzbDrone.Core.Music; +using NzbDrone.Core.Notifications.Slack.Payloads; using NzbDrone.Core.Validation; - namespace NzbDrone.Core.Notifications.Slack { public class Slack : NotificationBase<SlackSettings> @@ -154,7 +152,6 @@ namespace NzbDrone.Core.Notifications.Slack 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 1d7fd9b85..6be666f82 100644 --- a/src/NzbDrone.Core/Notifications/Slack/SlackExeption.cs +++ b/src/NzbDrone.Core/Notifications/Slack/SlackExeption.cs @@ -3,13 +3,15 @@ using NzbDrone.Common.Exceptions; namespace NzbDrone.Core.Notifications.Slack { - class SlackExeption : NzbDroneException + internal 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/Subsonic/Subsonic.cs b/src/NzbDrone.Core/Notifications/Subsonic/Subsonic.cs index f65864e20..990e2e6cf 100644 --- a/src/NzbDrone.Core/Notifications/Subsonic/Subsonic.cs +++ b/src/NzbDrone.Core/Notifications/Subsonic/Subsonic.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; -using System.Linq; using System.Net.Sockets; using FluentValidation.Results; using NLog; diff --git a/src/NzbDrone.Core/Notifications/Subsonic/SubsonicAuthenticationException.cs b/src/NzbDrone.Core/Notifications/Subsonic/SubsonicAuthenticationException.cs index 8b72513e6..106c6980c 100644 --- a/src/NzbDrone.Core/Notifications/Subsonic/SubsonicAuthenticationException.cs +++ b/src/NzbDrone.Core/Notifications/Subsonic/SubsonicAuthenticationException.cs @@ -2,7 +2,8 @@ namespace NzbDrone.Core.Notifications.Subsonic { public class SubsonicAuthenticationException : SubsonicException { - public SubsonicAuthenticationException(string message) : base(message) + public SubsonicAuthenticationException(string message) + : base(message) { } diff --git a/src/NzbDrone.Core/Notifications/Subsonic/SubsonicException.cs b/src/NzbDrone.Core/Notifications/Subsonic/SubsonicException.cs index 8f94df21a..37543d8e9 100644 --- a/src/NzbDrone.Core/Notifications/Subsonic/SubsonicException.cs +++ b/src/NzbDrone.Core/Notifications/Subsonic/SubsonicException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Notifications.Subsonic { public class SubsonicException : NzbDroneException { - public SubsonicException(string message) : base(message) + public SubsonicException(string message) + : base(message) { } - public SubsonicException(string message, params object[] args) : base(message, args) + public SubsonicException(string message, params object[] args) + : base(message, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Subsonic/SubsonicServerProxy.cs b/src/NzbDrone.Core/Notifications/Subsonic/SubsonicServerProxy.cs index 741701fd1..7b0a71632 100644 --- a/src/NzbDrone.Core/Notifications/Subsonic/SubsonicServerProxy.cs +++ b/src/NzbDrone.Core/Notifications/Subsonic/SubsonicServerProxy.cs @@ -1,10 +1,10 @@ +using System.IO; +using System.Xml.Linq; using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Rest; using RestSharp; -using System.IO; -using System.Xml.Linq; namespace NzbDrone.Core.Notifications.Subsonic { @@ -64,7 +64,7 @@ namespace NzbDrone.Core.Notifications.Subsonic _logger.Trace("Version response: {0}", response.Content); CheckForError(response, settings); - + var xDoc = XDocument.Load(new StringReader(response.Content.Replace("&", "&"))); var version = xDoc.Root?.Attribute("version")?.Value; @@ -126,7 +126,6 @@ namespace NzbDrone.Core.Notifications.Subsonic } throw new SubsonicException(errorMessage); - } if (response.Content.IsNullOrWhiteSpace()) diff --git a/src/NzbDrone.Core/Notifications/Subsonic/SubsonicService.cs b/src/NzbDrone.Core/Notifications/Subsonic/SubsonicService.cs index 523b3c77d..6e25be122 100644 --- a/src/NzbDrone.Core/Notifications/Subsonic/SubsonicService.cs +++ b/src/NzbDrone.Core/Notifications/Subsonic/SubsonicService.cs @@ -1,8 +1,6 @@ +using System; using FluentValidation.Results; using NLog; -using NzbDrone.Common.Cache; -using NzbDrone.Core.Music; -using System; namespace NzbDrone.Core.Notifications.Subsonic { @@ -23,7 +21,6 @@ namespace NzbDrone.Core.Notifications.Subsonic { _proxy = proxy; _logger = logger; - } public void Notify(SubsonicSettings settings, string message) diff --git a/src/NzbDrone.Core/Notifications/Subsonic/SubsonicSettings.cs b/src/NzbDrone.Core/Notifications/Subsonic/SubsonicSettings.cs index 4fbae8f33..bb4721e2d 100644 --- a/src/NzbDrone.Core/Notifications/Subsonic/SubsonicSettings.cs +++ b/src/NzbDrone.Core/Notifications/Subsonic/SubsonicSettings.cs @@ -1,5 +1,4 @@ using FluentValidation; -using Newtonsoft.Json; using NzbDrone.Common.Extensions; using NzbDrone.Core.Annotations; using NzbDrone.Core.ThingiProvider; @@ -28,7 +27,7 @@ namespace NzbDrone.Core.Notifications.Subsonic [FieldDefinition(0, Label = "Host")] public string Host { get; set; } - + [FieldDefinition(1, Label = "Port")] public int Port { get; set; } diff --git a/src/NzbDrone.Core/Notifications/Synology/SynologyException.cs b/src/NzbDrone.Core/Notifications/Synology/SynologyException.cs index f7534671b..4c70e61b1 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 e412d77af..d4f8a6581 100644 --- a/src/NzbDrone.Core/Notifications/Synology/SynologyIndexer.cs +++ b/src/NzbDrone.Core/Notifications/Synology/SynologyIndexer.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.IO; using FluentValidation.Results; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Common.Extensions; diff --git a/src/NzbDrone.Core/Notifications/Synology/SynologyIndexerSettings.cs b/src/NzbDrone.Core/Notifications/Synology/SynologyIndexerSettings.cs index 5f9be1a2f..7b1084570 100644 --- a/src/NzbDrone.Core/Notifications/Synology/SynologyIndexerSettings.cs +++ b/src/NzbDrone.Core/Notifications/Synology/SynologyIndexerSettings.cs @@ -9,7 +9,6 @@ namespace NzbDrone.Core.Notifications.Synology { public SynologyIndexerSettingsValidator() { - } } diff --git a/src/NzbDrone.Core/Notifications/Telegram/InvalidResponseException.cs b/src/NzbDrone.Core/Notifications/Telegram/InvalidResponseException.cs index 137e7322b..8ad8de02a 100644 --- a/src/NzbDrone.Core/Notifications/Telegram/InvalidResponseException.cs +++ b/src/NzbDrone.Core/Notifications/Telegram/InvalidResponseException.cs @@ -8,7 +8,8 @@ namespace NzbDrone.Core.Notifications.Telegram { } - 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 8ab78ff36..85de9f332 100644 --- a/src/NzbDrone.Core/Notifications/Telegram/TelegramService.cs +++ b/src/NzbDrone.Core/Notifications/Telegram/TelegramService.cs @@ -5,8 +5,8 @@ using FluentValidation.Results; using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Common.Serializer; -using RestSharp; using NzbDrone.Core.Rest; +using RestSharp; namespace NzbDrone.Core.Notifications.Telegram { @@ -18,8 +18,8 @@ namespace NzbDrone.Core.Notifications.Telegram 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 dde4bc1aa..8992ca0f8 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 a8f5e06c2..0f6c375aa 100644 --- a/src/NzbDrone.Core/Notifications/Twitter/Twitter.cs +++ b/src/NzbDrone.Core/Notifications/Twitter/Twitter.cs @@ -6,9 +6,8 @@ using NzbDrone.Core.Validation; namespace NzbDrone.Core.Notifications.Twitter { - class Twitter : NotificationBase<TwitterSettings> + internal class Twitter : NotificationBase<TwitterSettings> { - private readonly ITwitterService _twitterService; public Twitter(ITwitterService twitterService) @@ -82,6 +81,7 @@ namespace NzbDrone.Core.Notifications.Twitter accessTokenSecret = oauthToken.AccessTokenSecret }; } + return new { }; } @@ -94,5 +94,4 @@ namespace NzbDrone.Core.Notifications.Twitter return new ValidationResult(failures); } } - } diff --git a/src/NzbDrone.Core/Notifications/Twitter/TwitterException.cs b/src/NzbDrone.Core/Notifications/Twitter/TwitterException.cs index 99146fa71..77676fbf2 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 ae23e2d8c..261c194d1 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; @@ -46,7 +46,7 @@ namespace NzbDrone.Core.Notifications.Twitter var oAuthRequest = OAuthRequest.ForAccessToken(consumerKey, consumerSecret, oauthToken, "", oauthVerifier); oAuthRequest.RequestUrl = "https://api.twitter.com/oauth/access_token"; var qscoll = OAuthQuery(oAuthRequest); - + return new OAuthToken { AccessToken = qscoll["oauth_token"], @@ -82,7 +82,6 @@ namespace NzbDrone.Core.Notifications.Twitter { twitter.DirectMessage(message, settings.Mention); } - else { if (settings.Mention.IsNotNullOrWhiteSpace()) @@ -90,7 +89,7 @@ namespace NzbDrone.Core.Notifications.Twitter message += string.Format(" @{0}", settings.Mention); } - twitter.UpdateStatus(message); + twitter.UpdateStatus(message); } } catch (WebException ex) @@ -131,6 +130,7 @@ namespace NzbDrone.Core.Notifications.Twitter _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 44d176675..eaa373d76 100644 --- a/src/NzbDrone.Core/Notifications/Twitter/TwitterSettings.cs +++ b/src/NzbDrone.Core/Notifications/Twitter/TwitterSettings.cs @@ -14,6 +14,7 @@ namespace NzbDrone.Core.Notifications.Twitter 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 595d2d348..40e062b93 100644 --- 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.Music; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Music; using NzbDrone.Core.Validation; namespace NzbDrone.Core.Notifications.Webhook @@ -24,7 +24,6 @@ namespace NzbDrone.Core.Notifications.Webhook var quality = message.Quality; var payload = new WebhookGrabPayload - { EventType = "Grab", Artist = new WebhookArtist(message.Artist), @@ -46,7 +45,6 @@ namespace NzbDrone.Core.Notifications.Webhook var trackFiles = message.TrackFiles; var payload = new WebhookImportPayload - { EventType = "Download", Artist = new WebhookArtist(message.Artist), @@ -102,23 +100,24 @@ namespace NzbDrone.Core.Notifications.Webhook try { var payload = new WebhookGrabPayload + { + EventType = "Test", + Artist = new WebhookArtist() + { + Id = 1, + Name = "Test Name", + Path = "C:\\testpath", + MBId = "aaaaa-aaa-aaaa-aaaaaa" + }, + Albums = new List<WebhookAlbum>() { - EventType = "Test", - Artist = new WebhookArtist() - { - Id = 1, - Name = "Test Name", - Path = "C:\\testpath", - MBId = "aaaaa-aaa-aaaa-aaaaaa" - }, - Albums = new List<WebhookAlbum>() { new WebhookAlbum() { Id = 123, Title = "Test title" } - } - }; + } + }; _proxy.SendWebhook(payload, Settings); } diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookAlbum.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookAlbum.cs index 433bb7370..5b82e4eef 100644 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookAlbum.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookAlbum.cs @@ -1,11 +1,13 @@ -using NzbDrone.Core.Music; using System; +using NzbDrone.Core.Music; namespace NzbDrone.Core.Notifications.Webhook { public class WebhookAlbum { - public WebhookAlbum() { } + public WebhookAlbum() + { + } public WebhookAlbum(Album album) { diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookArtist.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookArtist.cs index 7e291dc9d..11e9199bd 100644 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookArtist.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookArtist.cs @@ -9,7 +9,9 @@ namespace NzbDrone.Core.Notifications.Webhook public string Path { get; set; } public string MBId { get; set; } - public WebhookArtist() { } + public WebhookArtist() + { + } public WebhookArtist(Artist artist) { diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookException.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookException.cs index b422d8621..07d4c4666 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/WebhookProxy.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookProxy.cs index db33d5f28..f7eedec69 100644 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookProxy.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookProxy.cs @@ -1,7 +1,7 @@ +using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; using NzbDrone.Core.Rest; -using NzbDrone.Common.Extensions; namespace NzbDrone.Core.Notifications.Webhook { diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookRelease.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookRelease.cs index 60ff931da..a3fa1823e 100644 --- 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, RemoteAlbum remoteAlbum) { diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookTrack.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookTrack.cs index 098fd0078..9cef65c2a 100644 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookTrack.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookTrack.cs @@ -1,18 +1,18 @@ using NzbDrone.Core.Music; -using System; namespace NzbDrone.Core.Notifications.Webhook { public class WebhookTrack { - public WebhookTrack() { } + public WebhookTrack() + { + } public WebhookTrack(Track track) { Id = track.Id; Title = track.Title; TrackNumber = track.TrackNumber; - } public int Id { get; set; } diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookTrackFile.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookTrackFile.cs index eeefbaf09..60a6fe799 100644 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookTrackFile.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookTrackFile.cs @@ -4,7 +4,9 @@ namespace NzbDrone.Core.Notifications.Webhook { public class WebhookTrackFile { - public WebhookTrackFile() { } + public WebhookTrackFile() + { + } public WebhookTrackFile(TrackFile trackFile) { diff --git a/src/NzbDrone.Core/Notifications/Xbmc/XbmcService.cs b/src/NzbDrone.Core/Notifications/Xbmc/XbmcService.cs index 4badaacf7..334837b95 100644 --- a/src/NzbDrone.Core/Notifications/Xbmc/XbmcService.cs +++ b/src/NzbDrone.Core/Notifications/Xbmc/XbmcService.cs @@ -83,11 +83,11 @@ namespace NzbDrone.Core.Notifications.Xbmc { _logger.Debug("Updating artist {0} (Path: {1}) on XBMC host: {2}", artist, artistPath, settings.Address); } - else { - _logger.Debug("Artist {0} doesn't exist on XBMC host: {1}, Updating Entire Library", artist, - settings.Address); + _logger.Debug("Artist {0} doesn't exist on XBMC host: {1}, Updating Entire Library", + artist, + settings.Address); } var response = _proxy.UpdateLibrary(settings, artistPath); @@ -97,7 +97,6 @@ namespace NzbDrone.Core.Notifications.Xbmc _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 c4e80b17d..18efe94cc 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 711d5d429..38aa8a2e9 100644 --- a/src/NzbDrone.Core/Organizer/FileNameBuilder.cs +++ b/src/NzbDrone.Core/Organizer/FileNameBuilder.cs @@ -6,12 +6,12 @@ using System.Linq; using System.Text.RegularExpressions; using NLog; using NzbDrone.Common.Cache; -using NzbDrone.Common.Extensions; using NzbDrone.Common.EnsureThat; +using NzbDrone.Common.Extensions; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Music; using NzbDrone.Core.Profiles.Releases; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Organizer { @@ -109,7 +109,7 @@ namespace NzbDrone.Core.Organizer } var subFolders = pattern.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries); - var safePattern = subFolders.Aggregate("", (current, folderLevel) => Path.Combine(current, (folderLevel))); + var safePattern = subFolders.Aggregate("", (current, folderLevel) => Path.Combine(current, folderLevel)); var tokenHandlers = new Dictionary<string, Func<TokenMatch, string>>(FileNameBuilderTokenEqualityComparer.Instance); @@ -149,13 +149,11 @@ namespace NzbDrone.Core.Organizer if (artist.AlbumFolder) { - var albumFolder = GetAlbumFolder(artist, album); albumFolder = CleanFileName(albumFolder); path = Path.Combine(path, albumFolder); - } return path; @@ -292,7 +290,7 @@ namespace NzbDrone.Core.Organizer { tokenHandlers["{Album Disambiguation}"] = m => album.Disambiguation; } - + if (album.ReleaseDate.HasValue) { tokenHandlers["{Release Year}"] = m => album.ReleaseDate.Value.Year.ToString(); @@ -325,11 +323,12 @@ namespace NzbDrone.Core.Organizer { var qualityTitle = _qualityDefinitionService.Get(trackFile.Quality.Quality).Title; var qualityProper = GetQualityProper(trackFile.Quality); - //var qualityReal = GetQualityReal(artist, trackFile.Quality); - tokenHandlers["{Quality Full}"] = m => String.Format("{0}", qualityTitle); + //var qualityReal = GetQualityReal(artist, trackFile.Quality); + tokenHandlers["{Quality Full}"] = m => string.Format("{0}", qualityTitle); tokenHandlers["{Quality Title}"] = m => qualityTitle; tokenHandlers["{Quality Proper}"] = m => qualityProper; + //tokenHandlers["{Quality Real}"] = m => qualityReal; } @@ -446,7 +445,10 @@ namespace NzbDrone.Core.Organizer 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]); } @@ -504,7 +506,7 @@ namespace NzbDrone.Core.Organizer return "Proper"; } - return String.Empty; + return string.Empty; } //private string GetQualityReal(Series series, QualityModel quality) @@ -516,7 +518,6 @@ namespace NzbDrone.Core.Organizer // return string.Empty; //} - private string GetOriginalTitle(TrackFile trackFile) { if (trackFile.SceneName.IsNullOrWhiteSpace()) @@ -531,7 +532,6 @@ namespace NzbDrone.Core.Organizer { return Path.GetFileNameWithoutExtension(trackFile.Path); } - } internal sealed class TokenMatch diff --git a/src/NzbDrone.Core/Organizer/FileNameBuilderTokenEqualityComparer.cs b/src/NzbDrone.Core/Organizer/FileNameBuilderTokenEqualityComparer.cs index fde022c10..e5ffe79f5 100644 --- a/src/NzbDrone.Core/Organizer/FileNameBuilderTokenEqualityComparer.cs +++ b/src/NzbDrone.Core/Organizer/FileNameBuilderTokenEqualityComparer.cs @@ -11,7 +11,6 @@ namespace NzbDrone.Core.Organizer 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 5ded480da..d2a1b8ce0 100644 --- a/src/NzbDrone.Core/Organizer/FileNameSampleService.cs +++ b/src/NzbDrone.Core/Organizer/FileNameSampleService.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Organizer { @@ -37,7 +37,6 @@ namespace NzbDrone.Core.Organizer { Name = "The Artist Name", Disambiguation = "US Rock Band" - } }; @@ -90,9 +89,8 @@ namespace NzbDrone.Core.Organizer AlbumRelease = _singleRelease, AbsoluteTrackNumber = 3, MediumNumber = 1, - + Title = "Track Title (1)", - }; _singleTrack = new List<Track> { _track1 }; @@ -119,8 +117,6 @@ namespace NzbDrone.Core.Organizer { "iNTERNAL" }; - - } public SampleResult GetStandardTrackSample(NamingConfig nameSpec) diff --git a/src/NzbDrone.Core/Organizer/FileNameValidation.cs b/src/NzbDrone.Core/Organizer/FileNameValidation.cs index 0f9744211..e7d7235b9 100644 --- a/src/NzbDrone.Core/Organizer/FileNameValidation.cs +++ b/src/NzbDrone.Core/Organizer/FileNameValidation.cs @@ -25,7 +25,8 @@ namespace NzbDrone.Core.Organizer { ruleBuilder.SetValidator(new NotEmptyValidator(null)); return ruleBuilder.SetValidator(new RegularExpressionValidator(FileNameBuilder.AlbumTitleRegex)).WithMessage("Must contain Album title"); - //.SetValidator(new RegularExpressionValidator(FileNameBuilder.ReleaseDateRegex)).WithMessage("Must contain Release year"); + + //.SetValidator(new RegularExpressionValidator(FileNameBuilder.ReleaseDateRegex)).WithMessage("Must contain Release year"); } } @@ -34,7 +35,6 @@ namespace NzbDrone.Core.Organizer public ValidStandardTrackFormatValidator() : base("Must contain Track Title and Track numbers OR Original Title") { - } protected override bool IsValid(PropertyValidatorContext context) diff --git a/src/NzbDrone.Core/Organizer/FileNameValidationService.cs b/src/NzbDrone.Core/Organizer/FileNameValidationService.cs index 324940453..606b445aa 100644 --- a/src/NzbDrone.Core/Organizer/FileNameValidationService.cs +++ b/src/NzbDrone.Core/Organizer/FileNameValidationService.cs @@ -1,7 +1,4 @@ -using System.Collections.Generic; -using System.Linq; using FluentValidation.Results; -using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.Organizer { @@ -21,7 +18,6 @@ namespace NzbDrone.Core.Organizer //TODO Add Validation for TrackFilename //var parsedEpisodeInfo = Parser.Parser.ParseTitle(sampleResult.FileName); - //if (parsedEpisodeInfo == null) //{ // return validationFailure; @@ -31,9 +27,7 @@ namespace NzbDrone.Core.Organizer //{ // return validationFailure; //} - return null; } - } } diff --git a/src/NzbDrone.Core/Organizer/NamingConfigRepository.cs b/src/NzbDrone.Core/Organizer/NamingConfigRepository.cs index 6c32eee62..ca0138b67 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 @@ namespace NzbDrone.Core.Organizer : base(database, eventAggregator) { } - } } diff --git a/src/NzbDrone.Core/Organizer/NamingConfigService.cs b/src/NzbDrone.Core/Organizer/NamingConfigService.cs index ec802bc00..8cd9d3234 100644 --- a/src/NzbDrone.Core/Organizer/NamingConfigService.cs +++ b/src/NzbDrone.Core/Organizer/NamingConfigService.cs @@ -22,7 +22,7 @@ namespace NzbDrone.Core.Organizer if (config == null) { lock (_repository) - { + { config = _repository.SingleOrDefault(); if (config == null) diff --git a/src/NzbDrone.Core/Parser/FingerprintingService.cs b/src/NzbDrone.Core/Parser/FingerprintingService.cs index 33d7ca048..e6e89ff89 100644 --- a/src/NzbDrone.Core/Parser/FingerprintingService.cs +++ b/src/NzbDrone.Core/Parser/FingerprintingService.cs @@ -35,12 +35,12 @@ namespace NzbDrone.Core.Parser private const string _acoustIdUrl = "https://api.acoustid.org/v2/lookup"; private const string _acoustIdApiKey = "QANd68ji1L"; private const int _fingerprintingTimeout = 10000; - + private readonly Logger _logger; private readonly IHttpClient _httpClient; private readonly IHttpRequestBuilderFactory _customerRequestBuilder; private readonly ICached<AcoustId> _cache; - + private readonly string _fpcalcPath; private readonly Version _fpcalcVersion; private readonly string _fpcalcArgs; @@ -108,6 +108,7 @@ namespace NzbDrone.Core.Parser try { p.Start(); + // To avoid deadlocks, always read the output stream first and then wait. string output = p.StandardOutput.ReadToEnd(); p.WaitForExit(1000); @@ -143,6 +144,7 @@ namespace NzbDrone.Core.Parser p.StartInfo.RedirectStandardOutput = true; p.Start(); + // To avoid deadlocks, always read the output stream first and then wait. string output = p.StandardOutput.ReadToEnd(); p.WaitForExit(1000); @@ -178,7 +180,7 @@ namespace NzbDrone.Core.Parser { args = "-json"; } - + if (_fpcalcVersion >= new Version("1.4.3")) { args += " -ignore-errors"; @@ -189,28 +191,29 @@ namespace NzbDrone.Core.Parser public AcoustId ParseFpcalcJsonOutput(string output) { - return Json.Deserialize<AcoustId>(output); + return Json.Deserialize<AcoustId>(output); } public AcoustId ParseFpcalcTextOutput(string output) { - var durationstring = Regex.Match(output, @"(?<=DURATION=)[\d\.]+(?=\s)").Value; - double duration; - if (durationstring.IsNullOrWhiteSpace() || !double.TryParse(durationstring, out duration)) - { - return null; - } + var durationstring = Regex.Match(output, @"(?<=DURATION=)[\d\.]+(?=\s)").Value; + double duration; + if (durationstring.IsNullOrWhiteSpace() || !double.TryParse(durationstring, out duration)) + { + return null; + } - var fingerprint = Regex.Match(output, @"(?<=FINGERPRINT=)[^\s]+").Value; - if (fingerprint.IsNullOrWhiteSpace()) - { - return null; - } + var fingerprint = Regex.Match(output, @"(?<=FINGERPRINT=)[^\s]+").Value; + if (fingerprint.IsNullOrWhiteSpace()) + { + return null; + } - return new AcoustId { - Duration = duration, - Fingerprint = fingerprint - }; + return new AcoustId + { + Duration = duration, + Fingerprint = fingerprint + }; } public AcoustId ParseFpcalcOutput(string output) @@ -219,7 +222,7 @@ namespace NzbDrone.Core.Parser { return null; } - + if (_fpcalcArgs.Contains("-json")) { return ParseFpcalcJsonOutput(output); @@ -255,67 +258,67 @@ namespace NzbDrone.Core.Parser // see https://stackoverflow.com/questions/139593/processstartinfo-hanging-on-waitforexit-why?lq=1 // this is most likely overkill... using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false)) - { - using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false)) - { - DataReceivedEventHandler outputHandler = delegate(object sender, DataReceivedEventArgs e) - { - if (e.Data == null) - { - outputWaitHandle.Set(); - } - else - { - output.AppendLine(e.Data); - } - }; + { + using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false)) + { + DataReceivedEventHandler outputHandler = (sender, e) => + { + if (e.Data == null) + { + outputWaitHandle.Set(); + } + else + { + output.AppendLine(e.Data); + } + }; - DataReceivedEventHandler errorHandler = delegate(object sender, DataReceivedEventArgs e) - { - if (e.Data == null) - { - errorWaitHandle.Set(); - } - else - { - error.AppendLine(e.Data); - } - }; - - p.OutputDataReceived += outputHandler; - p.ErrorDataReceived += errorHandler; + DataReceivedEventHandler errorHandler = (sender, e) => + { + if (e.Data == null) + { + errorWaitHandle.Set(); + } + else + { + error.AppendLine(e.Data); + } + }; - p.Start(); + p.OutputDataReceived += outputHandler; + p.ErrorDataReceived += errorHandler; - p.BeginOutputReadLine(); - p.BeginErrorReadLine(); + p.Start(); - if (p.WaitForExit(_fingerprintingTimeout) && - outputWaitHandle.WaitOne(_fingerprintingTimeout) && - errorWaitHandle.WaitOne(_fingerprintingTimeout)) - { - // Process completed. - if (p.ExitCode != 0) - { - _logger.Warn($"fpcalc error: {error}"); - return null; - } - else - { - return ParseFpcalcOutput(output.ToString()); - } - } - else - { - // Timed out. Remove handlers to avoid object disposed error - p.OutputDataReceived -= outputHandler; - p.ErrorDataReceived -= errorHandler; - - _logger.Warn($"fpcalc timed out. {error}"); - return null; - } - } - } + p.BeginOutputReadLine(); + p.BeginErrorReadLine(); + + if (p.WaitForExit(_fingerprintingTimeout) && + outputWaitHandle.WaitOne(_fingerprintingTimeout) && + errorWaitHandle.WaitOne(_fingerprintingTimeout)) + { + // Process completed. + if (p.ExitCode != 0) + { + _logger.Warn($"fpcalc error: {error}"); + return null; + } + else + { + return ParseFpcalcOutput(output.ToString()); + } + } + else + { + // Timed out. Remove handlers to avoid object disposed error + p.OutputDataReceived -= outputHandler; + p.ErrorDataReceived -= errorHandler; + + _logger.Warn($"fpcalc timed out. {error}"); + return null; + } + } + } } return null; @@ -327,7 +330,7 @@ namespace NzbDrone.Core.Parser { return; } - + Lookup(tracks.Select(x => Tuple.Create(x, GetFingerprint(x.Path))).ToList(), threshold); } @@ -355,7 +358,7 @@ namespace NzbDrone.Core.Parser { sb.Append($"&duration.{i}={toLookup[i].Item2.Duration:F0}&fingerprint.{i}={toLookup[i].Item2.Fingerprint}"); } - + // they prefer a gzipped body httpRequest.SetContent(Encoding.UTF8.GetBytes(sb.ToString()).Compress()); httpRequest.Headers.Add("Content-Encoding", "gzip"); @@ -442,10 +445,10 @@ namespace NzbDrone.Core.Parser _logger.Debug("Fingerprinting complete."); - var SerializerSettings = Json.GetSerializerSettings(); - SerializerSettings.Formatting = Formatting.None; + var serializerSettings = Json.GetSerializerSettings(); + serializerSettings.Formatting = Formatting.None; var output = new { Fingerprints = toLookup.Select(x => new { Path = x.Item1.Path, AcoustIdResults = x.Item1.AcoustIdResults }) }; - _logger.Debug($"*** FingerprintingService TestCaseGenerator ***\n{JsonConvert.SerializeObject(output, SerializerSettings)}"); + _logger.Debug($"*** FingerprintingService TestCaseGenerator ***\n{JsonConvert.SerializeObject(output, serializerSettings)}"); } public class LookupResponse diff --git a/src/NzbDrone.Core/Parser/InvalidDateException.cs b/src/NzbDrone.Core/Parser/InvalidDateException.cs index 722517d0e..97c5da581 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/IsoCountries.cs b/src/NzbDrone.Core/Parser/IsoCountries.cs index 2f207be28..eeacb5a69 100644 --- a/src/NzbDrone.Core/Parser/IsoCountries.cs +++ b/src/NzbDrone.Core/Parser/IsoCountries.cs @@ -10,7 +10,7 @@ namespace NzbDrone.Core.Parser // see https://wiki.musicbrainz.org/Release_Country private static readonly HashSet<IsoCountry> All = new HashSet<IsoCountry> { - new IsoCountry("AF", "Afghanistan" ), + new IsoCountry("AF", "Afghanistan"), new IsoCountry("AX", "Åland Islands"), new IsoCountry("AL", "Albania"), new IsoCountry("DZ", "Algeria"), diff --git a/src/NzbDrone.Core/Parser/IsoLanguage.cs b/src/NzbDrone.Core/Parser/IsoLanguage.cs index 3a4bbd502..2b2dc7198 100644 --- a/src/NzbDrone.Core/Parser/IsoLanguage.cs +++ b/src/NzbDrone.Core/Parser/IsoLanguage.cs @@ -1,4 +1,3 @@ - namespace NzbDrone.Core.Parser { public class IsoLanguage diff --git a/src/NzbDrone.Core/Parser/IsoLanguages.cs b/src/NzbDrone.Core/Parser/IsoLanguages.cs index b961b5ecb..c0c5782f0 100644 --- a/src/NzbDrone.Core/Parser/IsoLanguages.cs +++ b/src/NzbDrone.Core/Parser/IsoLanguages.cs @@ -15,6 +15,7 @@ namespace NzbDrone.Core.Parser new IsoLanguage("da", "dan"), new IsoLanguage("nl", "nld"), new IsoLanguage("ja", "jpn"), + // new IsoLanguage("", ""), // new IsoLanguage("", ""), new IsoLanguage("ru", "rus"), @@ -25,6 +26,7 @@ namespace NzbDrone.Core.Parser new IsoLanguage("fi", "fin"), new IsoLanguage("tr", "tur"), new IsoLanguage("pt", "por"), + // new IsoLanguage("nl", "nld"), new IsoLanguage("el", "ell"), new IsoLanguage("ko", "kor"), diff --git a/src/NzbDrone.Core/Parser/Model/ArtistTitleInfo.cs b/src/NzbDrone.Core/Parser/Model/ArtistTitleInfo.cs index 0d1938d24..edae3cf1f 100644 --- a/src/NzbDrone.Core/Parser/Model/ArtistTitleInfo.cs +++ b/src/NzbDrone.Core/Parser/Model/ArtistTitleInfo.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace NzbDrone.Core.Parser.Model +namespace NzbDrone.Core.Parser.Model { public class ArtistTitleInfo { diff --git a/src/NzbDrone.Core/Parser/Model/ImportListItemInfo.cs b/src/NzbDrone.Core/Parser/Model/ImportListItemInfo.cs index 97353c564..fa61ba218 100644 --- a/src/NzbDrone.Core/Parser/Model/ImportListItemInfo.cs +++ b/src/NzbDrone.Core/Parser/Model/ImportListItemInfo.cs @@ -1,5 +1,4 @@ using System; -using System.Text; namespace NzbDrone.Core.Parser.Model { diff --git a/src/NzbDrone.Core/Parser/Model/LocalAlbumRelease.cs b/src/NzbDrone.Core/Parser/Model/LocalAlbumRelease.cs index 184ab3e6e..df82059a0 100644 --- a/src/NzbDrone.Core/Parser/Model/LocalAlbumRelease.cs +++ b/src/NzbDrone.Core/Parser/Model/LocalAlbumRelease.cs @@ -1,11 +1,10 @@ -using NzbDrone.Core.Music; -using System.Collections.Generic; -using System.Linq; -using NzbDrone.Core.MediaFiles.TrackImport.Identification; -using System.IO; using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; using NzbDrone.Common.Extensions; -using NzbDrone.Common; +using NzbDrone.Core.MediaFiles.TrackImport.Identification; +using NzbDrone.Core.Music; namespace NzbDrone.Core.Parser.Model { @@ -48,7 +47,7 @@ namespace NzbDrone.Core.Parser.Model localTrack.Release = AlbumRelease; localTrack.Album = AlbumRelease.Album.Value; localTrack.Artist = localTrack.Album.Artist.Value; - + if (TrackMapping.Mapping.ContainsKey(localTrack)) { var track = TrackMapping.Mapping[localTrack].Item1; @@ -71,7 +70,7 @@ namespace NzbDrone.Core.Parser.Model { Mapping = new Dictionary<LocalTrack, Tuple<Track, Distance>>(); } - + public Dictionary<LocalTrack, Tuple<Track, Distance>> Mapping { get; set; } public List<LocalTrack> LocalExtra { get; set; } public List<Track> MBExtra { get; set; } diff --git a/src/NzbDrone.Core/Parser/Model/LocalTrack.cs b/src/NzbDrone.Core/Parser/Model/LocalTrack.cs index edc7ff3dc..0c89f196c 100644 --- a/src/NzbDrone.Core/Parser/Model/LocalTrack.cs +++ b/src/NzbDrone.Core/Parser/Model/LocalTrack.cs @@ -1,8 +1,8 @@ -using NzbDrone.Core.Music; -using NzbDrone.Core.Qualities; +using System; using System.Collections.Generic; using NzbDrone.Core.MediaFiles.TrackImport.Identification; -using System; +using NzbDrone.Core.Music; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Parser.Model { diff --git a/src/NzbDrone.Core/Parser/Model/ParsedAlbumInfo.cs b/src/NzbDrone.Core/Parser/Model/ParsedAlbumInfo.cs index d54705e79..8a783baf2 100644 --- a/src/NzbDrone.Core/Parser/Model/ParsedAlbumInfo.cs +++ b/src/NzbDrone.Core/Parser/Model/ParsedAlbumInfo.cs @@ -1,9 +1,4 @@ -using NzbDrone.Common.Extensions; using NzbDrone.Core.Qualities; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace NzbDrone.Core.Parser.Model { @@ -25,12 +20,10 @@ namespace NzbDrone.Core.Parser.Model { string albumString = "[Unknown Album]"; - - if (AlbumTitle != null ) + if (AlbumTitle != null) { albumString = string.Format("{0}", AlbumTitle); } - return string.Format("{0} - {1} {2}", ArtistName, albumString, Quality); } diff --git a/src/NzbDrone.Core/Parser/Model/ParsedTrackInfo.cs b/src/NzbDrone.Core/Parser/Model/ParsedTrackInfo.cs index 86819329f..567564695 100644 --- a/src/NzbDrone.Core/Parser/Model/ParsedTrackInfo.cs +++ b/src/NzbDrone.Core/Parser/Model/ParsedTrackInfo.cs @@ -1,6 +1,6 @@ -using NzbDrone.Core.Qualities; using System; using System.Linq; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Parser.Model { @@ -40,7 +40,6 @@ namespace NzbDrone.Core.Parser.Model { string trackString = "[Unknown Track]"; - if (TrackNumbers != null && TrackNumbers.Any()) { trackString = string.Format("{0}", string.Join("-", TrackNumbers.Select(c => c.ToString("00")))); diff --git a/src/NzbDrone.Core/Parser/Model/ReleaseInfo.cs b/src/NzbDrone.Core/Parser/Model/ReleaseInfo.cs index 1bd53ae1f..c320ab82a 100644 --- a/src/NzbDrone.Core/Parser/Model/ReleaseInfo.cs +++ b/src/NzbDrone.Core/Parser/Model/ReleaseInfo.cs @@ -28,37 +28,19 @@ namespace NzbDrone.Core.Parser.Model public int Age { - get - { - return DateTime.UtcNow.Subtract(PublishDate).Days; - } - - //This prevents manually downloading a release from blowing up in mono - //TODO: Is there a better way? + get { return DateTime.UtcNow.Subtract(PublishDate).Days; } private set { } } public double AgeHours { - get - { - return DateTime.UtcNow.Subtract(PublishDate).TotalHours; - } - - //This prevents manually downloading a release from blowing up in mono - //TODO: Is there a better way? + get { return DateTime.UtcNow.Subtract(PublishDate).TotalHours; } private set { } } public double AgeMinutes { - get - { - return DateTime.UtcNow.Subtract(PublishDate).TotalMinutes; - } - - //This prevents manually downloading a release from blowing up in mono - //TODO: Is there a better way? + get { return DateTime.UtcNow.Subtract(PublishDate).TotalMinutes; } private set { } } diff --git a/src/NzbDrone.Core/Parser/Model/TorrentInfo.cs b/src/NzbDrone.Core/Parser/Model/TorrentInfo.cs index 59aab44a0..7a3909f37 100644 --- a/src/NzbDrone.Core/Parser/Model/TorrentInfo.cs +++ b/src/NzbDrone.Core/Parser/Model/TorrentInfo.cs @@ -49,4 +49,4 @@ namespace NzbDrone.Core.Parser.Model return stringBuilder.ToString(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Parser/Parser.cs b/src/NzbDrone.Core/Parser/Parser.cs index aa72739cb..93115a1ef 100644 --- a/src/NzbDrone.Core/Parser/Parser.cs +++ b/src/NzbDrone.Core/Parser/Parser.cs @@ -126,7 +126,6 @@ namespace NzbDrone.Core.Parser // Hypen with no or more spaces between artist/album/year new Regex(@"^(?:(?<artist>.+?)(?:-))(?<releaseyear>\d{4})(?:-)(?<album>[^-]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled), - }; private static readonly Regex[] RejectHashedReleasesRegex = new Regex[] @@ -170,7 +169,7 @@ namespace NzbDrone.Core.Parser RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly RegexReplace WebsitePrefixRegex = new RegexReplace(@"^\[\s*[a-z]+(\.[a-z]+)+\s*\][- ]*|^www\.[a-z]+\.(?:com|net)[ -]*", - string.Empty, + string.Empty, RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly Regex AirDateRegex = new Regex(@"^(.*?)(?<!\d)((?<airyear>\d{4})[_.-](?<airmonth>[0-1][0-9])[_.-](?<airday>[0-3][0-9])|(?<airmonth>[0-1][0-9])[_.-](?<airday>[0-3][0-9])[_.-](?<airyear>\d{4}))(?!\d)", @@ -206,7 +205,8 @@ namespace NzbDrone.Core.Parser private static readonly string[] Numbers = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; - private static readonly Regex[] CommonTagRegex = new Regex[] { + private static readonly Regex[] CommonTagRegex = new Regex[] + { new Regex(@"(\[|\()*\b((featuring|feat.|feat|ft|ft.)\s{1}){1}\s*.*(\]|\))*", RegexOptions.IgnoreCase | RegexOptions.Compiled), new Regex(@"(?:\(|\[)(?:[^\(\[]*)(?:version|limited|deluxe|single|clean|album|special|bonus|promo|remastered)(?:[^\)\]]*)(?:\)|\])", RegexOptions.IgnoreCase | RegexOptions.Compiled) }; @@ -218,7 +218,7 @@ namespace NzbDrone.Core.Parser }; private static readonly Regex AfterDashRegex = new Regex(@"[-:].*", RegexOptions.Compiled); - + public static ParsedTrackInfo ParseMusicPath(string path) { var fileInfo = new FileInfo(path); @@ -241,7 +241,10 @@ namespace NzbDrone.Core.Parser { try { - if (!ValidateBeforeParsing(title)) return null; + if (!ValidateBeforeParsing(title)) + { + return null; + } Logger.Debug("Parsing string '{0}'", title); @@ -305,7 +308,9 @@ namespace NzbDrone.Core.Parser 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); @@ -316,10 +321,15 @@ namespace NzbDrone.Core.Parser { try { - if (!ValidateBeforeParsing(title)) return null; + if (!ValidateBeforeParsing(title)) + { + return null; + } Logger.Debug("Parsing string '{0}' using search criteria artist: '{1}' album: '{2}'", - title, artist.Name.RemoveAccent(), string.Join(", ", album.Select(a => a.Title.RemoveAccent()))); + title, + artist.Name.RemoveAccent(), + string.Join(", ", album.Select(a => a.Title.RemoveAccent()))); var releaseTitle = RemoveFileExtension(title); @@ -375,7 +385,9 @@ namespace NzbDrone.Core.Parser 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); @@ -386,7 +398,10 @@ namespace NzbDrone.Core.Parser { try { - if (!ValidateBeforeParsing(title)) return null; + if (!ValidateBeforeParsing(title)) + { + return null; + } Logger.Debug("Parsing string '{0}'", title); @@ -466,7 +481,9 @@ namespace NzbDrone.Core.Parser 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); @@ -479,7 +496,9 @@ namespace NzbDrone.Core.Parser //If Title only contains numbers return it as is. if (long.TryParse(name, out number)) + { return name; + } name = PercentRegex.Replace(name, "percent"); @@ -547,6 +566,7 @@ namespace NzbDrone.Core.Parser { return string.Empty; } + return m.Value; }); @@ -565,7 +585,7 @@ namespace NzbDrone.Core.Parser { intermediate = regex.Replace(intermediate, string.Empty).Trim(); } - + return intermediate; } @@ -591,7 +611,7 @@ namespace NzbDrone.Core.Parser artistName = RequestInfoRegex.Replace(artistName, "").Trim(' '); // Coppied from Radarr (https://github.com/Radarr/Radarr/blob/develop/src/NzbDrone.Core/Parser/Parser.cs) - // TODO: Split into separate method and write unit tests for. + // TODO: Split into separate method and write unit tests for. var parts = artistName.Split('.'); artistName = ""; int n = 0; @@ -603,6 +623,7 @@ namespace NzbDrone.Core.Parser { nextPart = parts[n + 1]; } + if (part.Length == 1 && part.ToLower() != "a" && !int.TryParse(part, out n)) { artistName += part + "."; @@ -620,8 +641,10 @@ namespace NzbDrone.Core.Parser artistName += " "; previousAcronym = false; } + artistName += part + " "; } + n++; } diff --git a/src/NzbDrone.Core/Parser/ParsingService.cs b/src/NzbDrone.Core/Parser/ParsingService.cs index 8dd21b942..e95d2ef32 100644 --- a/src/NzbDrone.Core/Parser/ParsingService.cs +++ b/src/NzbDrone.Core/Parser/ParsingService.cs @@ -1,13 +1,13 @@ +using System; using System.Collections.Generic; +using System.IO; using System.Linq; using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Music; -using System; -using System.IO; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.Parser { @@ -52,7 +52,7 @@ namespace NzbDrone.Core.Parser { title = parsedAlbumInfo.ArtistName; } - + var artistInfo = _artistService.FindByName(title); if (artistInfo == null) @@ -134,14 +134,16 @@ namespace NzbDrone.Core.Parser { return _albumService.ArtistAlbumsBetweenDates(artist, new DateTime(parsedAlbumInfo.DiscographyStart, 1, 1), - new DateTime(parsedAlbumInfo.DiscographyEnd, 12, 31), false); + new DateTime(parsedAlbumInfo.DiscographyEnd, 12, 31), + false); } if (parsedAlbumInfo.DiscographyEnd > 0) { return _albumService.ArtistAlbumsBetweenDates(artist, new DateTime(1800, 1, 1), - new DateTime(parsedAlbumInfo.DiscographyEnd, 12, 31), false); + new DateTime(parsedAlbumInfo.DiscographyEnd, 12, 31), + false); } return _albumService.GetAlbumsByArtist(artist.Id); @@ -168,15 +170,12 @@ namespace NzbDrone.Core.Parser { result.Add(albumInfo); } - else { _logger.Debug("Unable to find {0}", parsedAlbumInfo); } - return result; - } public RemoteAlbum Map(ParsedAlbumInfo parsedAlbumInfo, int artistId, IEnumerable<int> albumIds) diff --git a/src/NzbDrone.Core/Parser/QualityParser.cs b/src/NzbDrone.Core/Parser/QualityParser.cs index 19a30710c..4125c8c6a 100644 --- a/src/NzbDrone.Core/Parser/QualityParser.cs +++ b/src/NzbDrone.Core/Parser/QualityParser.cs @@ -63,33 +63,72 @@ namespace NzbDrone.Core.Parser } } - var codec = ParseCodec(normalizedName,name); + var codec = ParseCodec(normalizedName, name); var bitrate = ParseBitRate(normalizedName); var sampleSize = ParseSampleSize(normalizedName); - switch(codec) + switch (codec) { case Codec.MP1: case Codec.MP2: result.Quality = Quality.Unknown; break; case Codec.MP3VBR: - if (bitrate == BitRate.VBRV0) { result.Quality = Quality.MP3_VBR; } - else if (bitrate == BitRate.VBRV2) { result.Quality = Quality.MP3_VBR_V2; } - else { result.Quality = Quality.Unknown; } + if (bitrate == BitRate.VBRV0) + { + result.Quality = Quality.MP3_VBR; + } + else if (bitrate == BitRate.VBRV2) + { + result.Quality = Quality.MP3_VBR_V2; + } + else + { + result.Quality = Quality.Unknown; + } + break; case Codec.MP3CBR: - if (bitrate == BitRate.B096) { result.Quality = Quality.MP3_096; } - else if (bitrate == BitRate.B128) { result.Quality = Quality.MP3_128; } - else if (bitrate == BitRate.B160) { result.Quality = Quality.MP3_160; } - else if (bitrate == BitRate.B192) { result.Quality = Quality.MP3_192; } - else if (bitrate == BitRate.B256) { result.Quality = Quality.MP3_256; } - else if (bitrate == BitRate.B320) { result.Quality = Quality.MP3_320; } - else { result.Quality = Quality.Unknown; } + if (bitrate == BitRate.B096) + { + result.Quality = Quality.MP3_096; + } + else if (bitrate == BitRate.B128) + { + result.Quality = Quality.MP3_128; + } + else if (bitrate == BitRate.B160) + { + result.Quality = Quality.MP3_160; + } + else if (bitrate == BitRate.B192) + { + result.Quality = Quality.MP3_192; + } + else if (bitrate == BitRate.B256) + { + result.Quality = Quality.MP3_256; + } + else if (bitrate == BitRate.B320) + { + result.Quality = Quality.MP3_320; + } + else + { + result.Quality = Quality.Unknown; + } + break; case Codec.FLAC: - if (sampleSize == SampleSize.S24) {result.Quality = Quality.FLAC_24;} - else {result.Quality = Quality.FLAC;} + if (sampleSize == SampleSize.S24) + { + result.Quality = Quality.FLAC_24; + } + else + { + result.Quality = Quality.FLAC; + } + break; case Codec.ALAC: result.Quality = Quality.ALAC; @@ -107,30 +146,81 @@ namespace NzbDrone.Core.Parser result.Quality = Quality.WAV; break; case Codec.AAC: - if (bitrate == BitRate.B192) { result.Quality = Quality.AAC_192; } - else if (bitrate == BitRate.B256) { result.Quality = Quality.AAC_256; } - else if (bitrate == BitRate.B320) { result.Quality = Quality.AAC_320; } - else { result.Quality = Quality.AAC_VBR; } + if (bitrate == BitRate.B192) + { + result.Quality = Quality.AAC_192; + } + else if (bitrate == BitRate.B256) + { + result.Quality = Quality.AAC_256; + } + else if (bitrate == BitRate.B320) + { + result.Quality = Quality.AAC_320; + } + else + { + result.Quality = Quality.AAC_VBR; + } + break; case Codec.AACVBR: result.Quality = Quality.AAC_VBR; break; case Codec.OGG: case Codec.OPUS: - if (bitrate == BitRate.B160) { result.Quality = Quality.VORBIS_Q5; } - else if (bitrate == BitRate.B192) { result.Quality = Quality.VORBIS_Q6; } - else if (bitrate == BitRate.B224) { result.Quality = Quality.VORBIS_Q7; } - else if (bitrate == BitRate.B256) { result.Quality = Quality.VORBIS_Q8; } - else if (bitrate == BitRate.B320) { result.Quality = Quality.VORBIS_Q9; } - else if (bitrate == BitRate.B500) { result.Quality = Quality.VORBIS_Q10; } - else { result.Quality = Quality.Unknown; } + if (bitrate == BitRate.B160) + { + result.Quality = Quality.VORBIS_Q5; + } + else if (bitrate == BitRate.B192) + { + result.Quality = Quality.VORBIS_Q6; + } + else if (bitrate == BitRate.B224) + { + result.Quality = Quality.VORBIS_Q7; + } + else if (bitrate == BitRate.B256) + { + result.Quality = Quality.VORBIS_Q8; + } + else if (bitrate == BitRate.B320) + { + result.Quality = Quality.VORBIS_Q9; + } + else if (bitrate == BitRate.B500) + { + result.Quality = Quality.VORBIS_Q10; + } + else + { + result.Quality = Quality.Unknown; + } + break; case Codec.Unknown: - if (bitrate == BitRate.B192) { result.Quality = Quality.MP3_192; } - else if (bitrate == BitRate.B256) { result.Quality = Quality.MP3_256; } - else if (bitrate == BitRate.B320) { result.Quality = Quality.MP3_320; } - else if (bitrate == BitRate.VBR) { result.Quality = Quality.MP3_VBR_V2; } - else { result.Quality = Quality.Unknown; } + if (bitrate == BitRate.B192) + { + result.Quality = Quality.MP3_192; + } + else if (bitrate == BitRate.B256) + { + result.Quality = Quality.MP3_256; + } + else if (bitrate == BitRate.B320) + { + result.Quality = Quality.MP3_320; + } + else if (bitrate == BitRate.VBR) + { + result.Quality = Quality.MP3_VBR_V2; + } + else + { + result.Quality = Quality.Unknown; + } + break; default: result.Quality = Quality.Unknown; @@ -164,20 +254,75 @@ namespace NzbDrone.Core.Parser var match = CodecRegex.Match(name); - if (!match.Success) { return Codec.Unknown; } - if (match.Groups["FLAC"].Success) { return Codec.FLAC; } - if (match.Groups["ALAC"].Success) { return Codec.ALAC; } - if (match.Groups["WMA"].Success) { return Codec.WMA; } - if (match.Groups["WAV"].Success) { return Codec.WAV; } - if (match.Groups["AAC"].Success) { return Codec.AAC; } - if (match.Groups["OGG"].Success) { return Codec.OGG; } - if (match.Groups["OPUS"].Success) { return Codec.OPUS; } - if (match.Groups["MP1"].Success) { return Codec.MP1; } - if (match.Groups["MP2"].Success) { return Codec.MP2; } - if (match.Groups["MP3VBR"].Success) { return Codec.MP3VBR; } - if (match.Groups["MP3CBR"].Success) { return Codec.MP3CBR; } - if (match.Groups["WAVPACK"].Success) { return Codec.WAVPACK; } - if (match.Groups["APE"].Success) { return Codec.APE; } + if (!match.Success) + { + return Codec.Unknown; + } + + if (match.Groups["FLAC"].Success) + { + return Codec.FLAC; + } + + if (match.Groups["ALAC"].Success) + { + return Codec.ALAC; + } + + if (match.Groups["WMA"].Success) + { + return Codec.WMA; + } + + if (match.Groups["WAV"].Success) + { + return Codec.WAV; + } + + if (match.Groups["AAC"].Success) + { + return Codec.AAC; + } + + if (match.Groups["OGG"].Success) + { + return Codec.OGG; + } + + if (match.Groups["OPUS"].Success) + { + return Codec.OPUS; + } + + if (match.Groups["MP1"].Success) + { + return Codec.MP1; + } + + if (match.Groups["MP2"].Success) + { + return Codec.MP2; + } + + if (match.Groups["MP3VBR"].Success) + { + return Codec.MP3VBR; + } + + if (match.Groups["MP3CBR"].Success) + { + return Codec.MP3CBR; + } + + if (match.Groups["WAVPACK"].Success) + { + return Codec.WAVPACK; + } + + if (match.Groups["APE"].Success) + { + return Codec.APE; + } return Codec.Unknown; } @@ -187,18 +332,65 @@ namespace NzbDrone.Core.Parser //var nameWithNoSpaces = Regex.Replace(name, @"\s+", ""); var match = BitRateRegex.Match(name); - if (!match.Success) return BitRate.Unknown; - if (match.Groups["B096"].Success) { return BitRate.B096; } - if (match.Groups["B128"].Success) { return BitRate.B128; } - if (match.Groups["B160"].Success) { return BitRate.B160; } - if (match.Groups["B192"].Success) { return BitRate.B192; } - if (match.Groups["B224"].Success) { return BitRate.B224; } - if (match.Groups["B256"].Success) { return BitRate.B256; } - if (match.Groups["B320"].Success) { return BitRate.B320; } - if (match.Groups["B500"].Success) { return BitRate.B500; } - if (match.Groups["VBR"].Success) { return BitRate.VBR; } - if (match.Groups["VBRV0"].Success) { return BitRate.VBRV0; } - if (match.Groups["VBRV2"].Success) { return BitRate.VBRV2; } + if (!match.Success) + { + return BitRate.Unknown; + } + + if (match.Groups["B096"].Success) + { + return BitRate.B096; + } + + if (match.Groups["B128"].Success) + { + return BitRate.B128; + } + + if (match.Groups["B160"].Success) + { + return BitRate.B160; + } + + if (match.Groups["B192"].Success) + { + return BitRate.B192; + } + + if (match.Groups["B224"].Success) + { + return BitRate.B224; + } + + if (match.Groups["B256"].Success) + { + return BitRate.B256; + } + + if (match.Groups["B320"].Success) + { + return BitRate.B320; + } + + if (match.Groups["B500"].Success) + { + return BitRate.B500; + } + + if (match.Groups["VBR"].Success) + { + return BitRate.VBR; + } + + if (match.Groups["VBRV0"].Success) + { + return BitRate.VBRV0; + } + + if (match.Groups["VBRV2"].Success) + { + return BitRate.VBRV2; + } return BitRate.Unknown; } @@ -207,8 +399,15 @@ namespace NzbDrone.Core.Parser { var match = SampleSizeRegex.Match(name); - if (!match.Success) { return SampleSize.Unknown; } - if (match.Groups["S24"].Success) { return SampleSize.S24; } + if (!match.Success) + { + return SampleSize.Unknown; + } + + if (match.Groups["S24"].Success) + { + return SampleSize.S24; + } return SampleSize.Unknown; } @@ -223,26 +422,98 @@ namespace NzbDrone.Core.Parser case Codec.MP3VBR: return Quality.MP3_VBR; case Codec.MP3CBR: - if (bitrate == 8) { return Quality.MP3_008; } - if (bitrate == 16) { return Quality.MP3_016; } - if (bitrate == 24) { return Quality.MP3_024; } - if (bitrate == 32) { return Quality.MP3_032; } - if (bitrate == 40) { return Quality.MP3_040; } - if (bitrate == 48) { return Quality.MP3_048; } - if (bitrate == 56) { return Quality.MP3_056; } - if (bitrate == 64) { return Quality.MP3_064; } - if (bitrate == 80) { return Quality.MP3_080; } - if (bitrate == 96) { return Quality.MP3_096; } - if (bitrate == 112) { return Quality.MP3_112; } - if (bitrate == 128) { return Quality.MP3_128; } - if (bitrate == 160) { return Quality.MP3_160; } - if (bitrate == 192) { return Quality.MP3_192; } - if (bitrate == 224) { return Quality.MP3_224; } - if (bitrate == 256) { return Quality.MP3_256; } - if (bitrate == 320) { return Quality.MP3_320; } + if (bitrate == 8) + { + return Quality.MP3_008; + } + + if (bitrate == 16) + { + return Quality.MP3_016; + } + + if (bitrate == 24) + { + return Quality.MP3_024; + } + + if (bitrate == 32) + { + return Quality.MP3_032; + } + + if (bitrate == 40) + { + return Quality.MP3_040; + } + + if (bitrate == 48) + { + return Quality.MP3_048; + } + + if (bitrate == 56) + { + return Quality.MP3_056; + } + + if (bitrate == 64) + { + return Quality.MP3_064; + } + + if (bitrate == 80) + { + return Quality.MP3_080; + } + + if (bitrate == 96) + { + return Quality.MP3_096; + } + + if (bitrate == 112) + { + return Quality.MP3_112; + } + + if (bitrate == 128) + { + return Quality.MP3_128; + } + + if (bitrate == 160) + { + return Quality.MP3_160; + } + + if (bitrate == 192) + { + return Quality.MP3_192; + } + + if (bitrate == 224) + { + return Quality.MP3_224; + } + + if (bitrate == 256) + { + return Quality.MP3_256; + } + + if (bitrate == 320) + { + return Quality.MP3_320; + } + return Quality.Unknown; case Codec.FLAC: - if (sampleSize == 24) {return Quality.FLAC_24;} + if (sampleSize == 24) + { + return Quality.FLAC_24; + } + return Quality.FLAC; case Codec.ALAC: return Quality.ALAC; @@ -255,25 +526,85 @@ namespace NzbDrone.Core.Parser case Codec.WAV: return Quality.WAV; case Codec.AAC: - if (bitrate == 192) { return Quality.AAC_192; } - if (bitrate == 256) { return Quality.AAC_256; } - if (bitrate == 320) { return Quality.AAC_320; } + if (bitrate == 192) + { + return Quality.AAC_192; + } + + if (bitrate == 256) + { + return Quality.AAC_256; + } + + if (bitrate == 320) + { + return Quality.AAC_320; + } + return Quality.AAC_VBR; case Codec.OGG: - if (bitrate == 160) { return Quality.VORBIS_Q5; } - if (bitrate == 192) { return Quality.VORBIS_Q6; } - if (bitrate == 224) { return Quality.VORBIS_Q7; } - if (bitrate == 256) { return Quality.VORBIS_Q8; } - if (bitrate == 320) { return Quality.VORBIS_Q9; } - if (bitrate == 500) { return Quality.VORBIS_Q10; } - return Quality.Unknown; + if (bitrate == 160) + { + return Quality.VORBIS_Q5; + } + + if (bitrate == 192) + { + return Quality.VORBIS_Q6; + } + + if (bitrate == 224) + { + return Quality.VORBIS_Q7; + } + + if (bitrate == 256) + { + return Quality.VORBIS_Q8; + } + + if (bitrate == 320) + { + return Quality.VORBIS_Q9; + } + + if (bitrate == 500) + { + return Quality.VORBIS_Q10; + } + + return Quality.Unknown; case Codec.OPUS: - if (bitrate < 130) { return Quality.Unknown; } - if (bitrate < 180) { return Quality.VORBIS_Q5; } - if (bitrate < 205) { return Quality.VORBIS_Q6; } - if (bitrate < 240) { return Quality.VORBIS_Q7; } - if (bitrate < 290) { return Quality.VORBIS_Q8; } - if (bitrate < 410) { return Quality.VORBIS_Q9; } + if (bitrate < 130) + { + return Quality.Unknown; + } + + if (bitrate < 180) + { + return Quality.VORBIS_Q5; + } + + if (bitrate < 205) + { + return Quality.VORBIS_Q6; + } + + if (bitrate < 240) + { + return Quality.VORBIS_Q7; + } + + if (bitrate < 290) + { + return Quality.VORBIS_Q8; + } + + if (bitrate < 410) + { + return Quality.VORBIS_Q9; + } + return Quality.VORBIS_Q10; default: return Quality.Unknown; diff --git a/src/NzbDrone.Core/Parser/RegexReplace.cs b/src/NzbDrone.Core/Parser/RegexReplace.cs index 11fdf579f..40ff075ce 100644 --- a/src/NzbDrone.Core/Parser/RegexReplace.cs +++ b/src/NzbDrone.Core/Parser/RegexReplace.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading.Tasks; +using System.Text.RegularExpressions; namespace NzbDrone.Core.Parser { @@ -28,19 +23,28 @@ namespace NzbDrone.Core.Parser 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; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Parser/SceneChecker.cs b/src/NzbDrone.Core/Parser/SceneChecker.cs index 36dcb78ca..24220d1bd 100644 --- a/src/NzbDrone.Core/Parser/SceneChecker.cs +++ b/src/NzbDrone.Core/Parser/SceneChecker.cs @@ -6,8 +6,15 @@ namespace NzbDrone.Core.Parser //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.ParseMusicTitle(title); diff --git a/src/NzbDrone.Core/Profiles/Delay/DelayProfileRepository.cs b/src/NzbDrone.Core/Profiles/Delay/DelayProfileRepository.cs index 8ad771ff3..d268fbb6c 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 cb0b19201..1e119b760 100644 --- a/src/NzbDrone.Core/Profiles/Delay/DelayProfileService.cs +++ b/src/NzbDrone.Core/Profiles/Delay/DelayProfileService.cs @@ -55,7 +55,10 @@ namespace NzbDrone.Core.Profiles.Delay 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 @@ namespace NzbDrone.Core.Profiles.Delay { 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 4e7ad94fb..cfd08a2f4 100644 --- a/src/NzbDrone.Core/Profiles/Delay/DelayProfileTagInUseValidator.cs +++ b/src/NzbDrone.Core/Profiles/Delay/DelayProfileTagInUseValidator.cs @@ -17,14 +17,20 @@ namespace NzbDrone.Core.Profiles.Delay 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/Metadata/MetadataProfile.cs b/src/NzbDrone.Core/Profiles/Metadata/MetadataProfile.cs index ffca2131f..40dee15fe 100644 --- a/src/NzbDrone.Core/Profiles/Metadata/MetadataProfile.cs +++ b/src/NzbDrone.Core/Profiles/Metadata/MetadataProfile.cs @@ -9,6 +9,5 @@ namespace NzbDrone.Core.Profiles.Metadata public List<ProfilePrimaryAlbumTypeItem> PrimaryAlbumTypes { get; set; } public List<ProfileSecondaryAlbumTypeItem> SecondaryAlbumTypes { get; set; } public List<ProfileReleaseStatusItem> ReleaseStatuses { get; set; } - } } diff --git a/src/NzbDrone.Core/Profiles/Metadata/MetadataProfileInUseException.cs b/src/NzbDrone.Core/Profiles/Metadata/MetadataProfileInUseException.cs index 7f215f8dc..973fdce92 100644 --- a/src/NzbDrone.Core/Profiles/Metadata/MetadataProfileInUseException.cs +++ b/src/NzbDrone.Core/Profiles/Metadata/MetadataProfileInUseException.cs @@ -8,7 +8,6 @@ namespace NzbDrone.Core.Profiles.Metadata public MetadataProfileInUseException(string name) : base(HttpStatusCode.BadRequest, "Metadata profile [{0}] is in use.", name) { - } } } diff --git a/src/NzbDrone.Core/Profiles/Metadata/MetadataProfileService.cs b/src/NzbDrone.Core/Profiles/Metadata/MetadataProfileService.cs index abddf9f8a..cf42814b4 100644 --- a/src/NzbDrone.Core/Profiles/Metadata/MetadataProfileService.cs +++ b/src/NzbDrone.Core/Profiles/Metadata/MetadataProfileService.cs @@ -1,12 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Linq; using NLog; +using NzbDrone.Core.ImportLists; using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Music; -using System.Collections.Generic; -using System.Linq; -using NzbDrone.Core.ImportLists; -using NzbDrone.Common.Extensions; -using System; namespace NzbDrone.Core.Profiles.Metadata { @@ -87,17 +86,17 @@ namespace NzbDrone.Core.Profiles.Metadata { var primaryTypes = PrimaryAlbumType.All .OrderByDescending(l => l.Name) - .Select(v => new ProfilePrimaryAlbumTypeItem {PrimaryAlbumType = v, Allowed = primAllowed.Contains(v)}) + .Select(v => new ProfilePrimaryAlbumTypeItem { PrimaryAlbumType = v, Allowed = primAllowed.Contains(v) }) .ToList(); var secondaryTypes = SecondaryAlbumType.All .OrderByDescending(l => l.Name) - .Select(v => new ProfileSecondaryAlbumTypeItem {SecondaryAlbumType = v, Allowed = secAllowed.Contains(v)}) + .Select(v => new ProfileSecondaryAlbumTypeItem { SecondaryAlbumType = v, Allowed = secAllowed.Contains(v) }) .ToList(); var releaseStatues = ReleaseStatus.All .OrderByDescending(l => l.Name) - .Select(v => new ProfileReleaseStatusItem {ReleaseStatus = v, Allowed = relAllowed.Contains(v)}) + .Select(v => new ProfileReleaseStatusItem { ReleaseStatus = v, Allowed = relAllowed.Contains(v) }) .ToList(); var profile = new MetadataProfile @@ -131,7 +130,7 @@ namespace NzbDrone.Core.Profiles.Metadata { _logger.Info("Setting up standard metadata profile"); - AddDefaultProfile("Standard", new List<PrimaryAlbumType>{PrimaryAlbumType.Album}, new List<SecondaryAlbumType>{ SecondaryAlbumType.Studio }, new List<ReleaseStatus>{ReleaseStatus.Official}); + AddDefaultProfile("Standard", new List<PrimaryAlbumType> { PrimaryAlbumType.Album }, new List<SecondaryAlbumType> { SecondaryAlbumType.Studio }, new List<ReleaseStatus> { ReleaseStatus.Official }); } if (emptyProfile != null) diff --git a/src/NzbDrone.Core/Profiles/Qualities/QualityProfileInUseException.cs b/src/NzbDrone.Core/Profiles/Qualities/QualityProfileInUseException.cs index cf64e2dbe..eebefd67f 100644 --- a/src/NzbDrone.Core/Profiles/Qualities/QualityProfileInUseException.cs +++ b/src/NzbDrone.Core/Profiles/Qualities/QualityProfileInUseException.cs @@ -8,7 +8,6 @@ namespace NzbDrone.Core.Profiles.Qualities public QualityProfileInUseException(string name) : base(HttpStatusCode.BadRequest, "Profile [{0}] is in use.", name) { - } } } diff --git a/src/NzbDrone.Core/Profiles/Qualities/QualityProfileService.cs b/src/NzbDrone.Core/Profiles/Qualities/QualityProfileService.cs index 74012bed2..18e0c87d6 100644 --- a/src/NzbDrone.Core/Profiles/Qualities/QualityProfileService.cs +++ b/src/NzbDrone.Core/Profiles/Qualities/QualityProfileService.cs @@ -1,13 +1,11 @@ using System.Collections.Generic; using System.Linq; using NLog; -using NzbDrone.Common.Extensions; -using NzbDrone.Common.Http.Dispatchers; using NzbDrone.Core.ImportLists; using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Music; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Profiles.Qualities { @@ -20,7 +18,6 @@ namespace NzbDrone.Core.Profiles.Qualities QualityProfile Get(int id); bool Exists(int id); QualityProfile GetDefaultProfile(string name, Quality cutoff = null, params Quality[] allowed); - } public class QualityProfileService : IProfileService, IHandle<ApplicationStartedEvent> @@ -76,11 +73,15 @@ namespace NzbDrone.Core.Profiles.Qualities public void Handle(ApplicationStartedEvent message) { - if (All().Any()) return; + if (All().Any()) + { + return; + } _logger.Info("Setting up default quality profiles"); - AddDefaultProfile("Any", Quality.Unknown, + AddDefaultProfile("Any", + Quality.Unknown, Quality.Unknown, Quality.MP3_008, Quality.MP3_016, @@ -116,12 +117,14 @@ namespace NzbDrone.Core.Profiles.Qualities Quality.FLAC, Quality.FLAC_24); - AddDefaultProfile("Lossless", Quality.FLAC, + AddDefaultProfile("Lossless", + Quality.FLAC, Quality.FLAC, Quality.ALAC, Quality.FLAC_24); - AddDefaultProfile("Standard", Quality.MP3_192, + AddDefaultProfile("Standard", + Quality.MP3_192, Quality.MP3_192, Quality.MP3_256, Quality.MP3_320); diff --git a/src/NzbDrone.Core/Profiles/Releases/PreferredWordService.cs b/src/NzbDrone.Core/Profiles/Releases/PreferredWordService.cs index d94d2d000..9a60d5eb9 100644 --- a/src/NzbDrone.Core/Profiles/Releases/PreferredWordService.cs +++ b/src/NzbDrone.Core/Profiles/Releases/PreferredWordService.cs @@ -1,8 +1,8 @@ -using NLog; -using NzbDrone.Core.Music; using System.Collections.Generic; using System.Linq; +using NLog; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Music; namespace NzbDrone.Core.Profiles.Releases { diff --git a/src/NzbDrone.Core/Profiles/Releases/TermMatcherService.cs b/src/NzbDrone.Core/Profiles/Releases/TermMatcherService.cs index 6c1b52d41..70edccdc9 100644 --- a/src/NzbDrone.Core/Profiles/Releases/TermMatcherService.cs +++ b/src/NzbDrone.Core/Profiles/Releases/TermMatcherService.cs @@ -45,7 +45,6 @@ namespace NzbDrone.Core.Profiles.Releases else { return new CaseInsensitiveTermMatcher(term); - } } } diff --git a/src/NzbDrone.Core/ProgressMessaging/ProgressMessageContext.cs b/src/NzbDrone.Core/ProgressMessaging/ProgressMessageContext.cs index a87ec5586..fba9ca3f3 100644 --- a/src/NzbDrone.Core/ProgressMessaging/ProgressMessageContext.cs +++ b/src/NzbDrone.Core/ProgressMessaging/ProgressMessageContext.cs @@ -10,7 +10,7 @@ namespace NzbDrone.Core.ProgressMessaging [ThreadStatic] private static bool _reentrancyLock; - + public static CommandModel CommandModel { get { return _commandModel; } @@ -20,7 +20,9 @@ namespace NzbDrone.Core.ProgressMessaging 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 6b69d3046..37885c47d 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 @@ namespace NzbDrone.Core.ProgressMessaging { var command = ProgressMessageContext.CommandModel; - if (!IsClientMessage(logEvent, command)) return; - - if (!ProgressMessageContext.LockReentrancy()) return; + if (!IsClientMessage(logEvent, command)) + { + 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 5aae603f6..0085b0683 100644 --- a/src/NzbDrone.Core/Qualities/Quality.cs +++ b/src/NzbDrone.Core/Qualities/Quality.cs @@ -32,15 +32,30 @@ namespace NzbDrone.Core.Qualities 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); } @@ -55,7 +70,7 @@ namespace NzbDrone.Core.Qualities return !Equals(left, right); } - public static Quality Unknown => new Quality(0, "Unknown"); + public static Quality Unknown => new Quality(0, "Unknown"); public static Quality MP3_192 => new Quality(1, "MP3-192"); public static Quality MP3_VBR => new Quality(2, "MP3-VBR-V0"); public static Quality MP3_256 => new Quality(3, "MP3-256"); @@ -144,7 +159,7 @@ namespace NzbDrone.Core.Qualities DefaultQualityDefinitions = new HashSet<QualityDefinition> { - new QualityDefinition(Quality.Unknown) { Weight = 1, MinSize = 0, MaxSize = 350, GroupWeight = 1}, + new QualityDefinition(Quality.Unknown) { Weight = 1, MinSize = 0, MaxSize = 350, GroupWeight = 1 }, new QualityDefinition(Quality.MP3_008) { Weight = 2, MinSize = 0, MaxSize = 10, GroupName = "Trash Quality Lossy", GroupWeight = 2 }, new QualityDefinition(Quality.MP3_016) { Weight = 3, MinSize = 0, MaxSize = 20, GroupName = "Trash Quality Lossy", GroupWeight = 2 }, new QualityDefinition(Quality.MP3_024) { Weight = 4, MinSize = 0, MaxSize = 30, GroupName = "Trash Quality Lossy", GroupWeight = 2 }, @@ -180,7 +195,7 @@ namespace NzbDrone.Core.Qualities new QualityDefinition(Quality.APE) { Weight = 22, MinSize = 0, MaxSize = null, GroupName = "Lossless", GroupWeight = 7 }, new QualityDefinition(Quality.WAVPACK) { Weight = 22, MinSize = 0, MaxSize = null, GroupName = "Lossless", GroupWeight = 7 }, new QualityDefinition(Quality.FLAC_24) { Weight = 23, MinSize = 0, MaxSize = null, GroupName = "Lossless", GroupWeight = 7 }, - new QualityDefinition(Quality.WAV) { Weight = 24, MinSize = 0, MaxSize = null, GroupWeight = 8} + new QualityDefinition(Quality.WAV) { Weight = 24, MinSize = 0, MaxSize = null, GroupWeight = 8 } }; } @@ -192,7 +207,10 @@ namespace NzbDrone.Core.Qualities public static Quality FindById(int id) { - if (id == 0) return Unknown; + if (id == 0) + { + return Unknown; + } else if (id > AllLookup.Length) { throw new ArgumentException("ID does not match a known quality", nameof(id)); diff --git a/src/NzbDrone.Core/Qualities/QualityDefinition.cs b/src/NzbDrone.Core/Qualities/QualityDefinition.cs index e8669ddd3..6adb1bf41 100644 --- a/src/NzbDrone.Core/Qualities/QualityDefinition.cs +++ b/src/NzbDrone.Core/Qualities/QualityDefinition.cs @@ -1,6 +1,5 @@ using NzbDrone.Core.Datastore; - namespace NzbDrone.Core.Qualities { public class QualityDefinition : ModelBase @@ -18,7 +17,6 @@ namespace NzbDrone.Core.Qualities public QualityDefinition() { - } public QualityDefinition(Quality quality) diff --git a/src/NzbDrone.Core/Qualities/QualityDefinitionRepository.cs b/src/NzbDrone.Core/Qualities/QualityDefinitionRepository.cs index 20286d275..8663b6b4a 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> @@ -14,7 +13,5 @@ namespace NzbDrone.Core.Qualities : base(database, eventAggregator) { } - - } } diff --git a/src/NzbDrone.Core/Qualities/QualityDefinitionService.cs b/src/NzbDrone.Core/Qualities/QualityDefinitionService.cs index edff516eb..64f5157f7 100644 --- a/src/NzbDrone.Core/Qualities/QualityDefinitionService.cs +++ b/src/NzbDrone.Core/Qualities/QualityDefinitionService.cs @@ -1,10 +1,10 @@ +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 @@ namespace NzbDrone.Core.Qualities 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 @@ namespace NzbDrone.Core.Qualities { insertList.Add(definition); } - else { updateList.Add(existing); diff --git a/src/NzbDrone.Core/Qualities/QualityModel.cs b/src/NzbDrone.Core/Qualities/QualityModel.cs index 7b813e09c..77597e437 100644 --- a/src/NzbDrone.Core/Qualities/QualityModel.cs +++ b/src/NzbDrone.Core/Qualities/QualityModel.cs @@ -12,11 +12,10 @@ namespace NzbDrone.Core.Qualities [JsonIgnore] public QualityDetectionSource QualityDetectionSource { get; set; } - + public QualityModel() : this(Quality.Unknown, new Revision()) { - } public QualityModel(Quality quality, Revision revision = null) @@ -32,11 +31,12 @@ namespace NzbDrone.Core.Qualities public override int GetHashCode() { - unchecked // Overflow is fine, just wrap + unchecked { + // Overflow is fine, just wrap 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; } } @@ -82,16 +82,30 @@ namespace NzbDrone.Core.Qualities 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.Equals(Quality) && 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 c0477eb45..42c413c37 100644 --- a/src/NzbDrone.Core/Qualities/Revision.cs +++ b/src/NzbDrone.Core/Qualities/Revision.cs @@ -8,7 +8,7 @@ namespace NzbDrone.Core.Qualities private Revision() { } - + public Revision(int version = 1, int real = 0, bool isRepack = false) { Version = version; @@ -22,17 +22,35 @@ namespace NzbDrone.Core.Qualities 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 @@ namespace NzbDrone.Core.Qualities 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 @@ namespace NzbDrone.Core.Qualities 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 7c5ca327a..1c969c381 100644 --- a/src/NzbDrone.Core/Queue/Queue.cs +++ b/src/NzbDrone.Core/Queue/Queue.cs @@ -3,9 +3,9 @@ using System.Collections.Generic; using NzbDrone.Core.Datastore; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Music; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Queue { diff --git a/src/NzbDrone.Core/Queue/QueueService.cs b/src/NzbDrone.Core/Queue/QueueService.cs index e14ed2610..00401c7a2 100644 --- a/src/NzbDrone.Core/Queue/QueueService.cs +++ b/src/NzbDrone.Core/Queue/QueueService.cs @@ -5,8 +5,8 @@ using NzbDrone.Common.Crypto; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.History; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Music; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Queue { @@ -68,7 +68,7 @@ namespace NzbDrone.Core.Queue { downloadForced = bool.Parse(history.Data["downloadForced"]); } - + var queue = new Queue { Artist = trackedDownload.RemoteAlbum?.Artist, diff --git a/src/NzbDrone.Core/RemotePathMappings/RemotePathMapping.cs b/src/NzbDrone.Core/RemotePathMappings/RemotePathMapping.cs index 2a1322b5b..1aa7f18a9 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 @@ -9,4 +8,4 @@ namespace NzbDrone.Core.RemotePathMappings public string RemotePath { get; set; } public string LocalPath { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingRepository.cs b/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingRepository.cs index 4a20f1576..1eec7e608 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 5e7b0d889..859bcbee4 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 @@ -160,4 +160,4 @@ namespace NzbDrone.Core.RemotePathMappings return localPath; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Rest/JsonNetSerializer.cs b/src/NzbDrone.Core/Rest/JsonNetSerializer.cs index c674fc51e..e5bcdfb3a 100644 --- a/src/NzbDrone.Core/Rest/JsonNetSerializer.cs +++ b/src/NzbDrone.Core/Rest/JsonNetSerializer.cs @@ -7,7 +7,7 @@ namespace NzbDrone.Core.Rest { 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 cc657c4b6..6990fb8fb 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 NzbDrone.Common.EnvironmentInfo; +using RestSharp; namespace NzbDrone.Core.Rest { @@ -12,7 +12,6 @@ namespace NzbDrone.Core.Rest UserAgent = $"{BuildInfo.AppName}/{BuildInfo.Version} ({OsInfo.Os})" }; - return restClient; } } diff --git a/src/NzbDrone.Core/Rest/RestException.cs b/src/NzbDrone.Core/Rest/RestException.cs index 207a20e75..99a0be97a 100644 --- a/src/NzbDrone.Core/Rest/RestException.cs +++ b/src/NzbDrone.Core/Rest/RestException.cs @@ -23,4 +23,4 @@ namespace NzbDrone.Core.Rest return base.ToString(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Rest/RestSharpExtensions.cs b/src/NzbDrone.Core/Rest/RestSharpExtensions.cs index e89144da8..938b8723d 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 @@ namespace NzbDrone.Core.Rest { 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 @@ namespace NzbDrone.Core.Rest } } - 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 @@ namespace NzbDrone.Core.Rest 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,9 +90,12 @@ namespace NzbDrone.Core.Rest { var header = response.Headers.FirstOrDefault(v => v.Name == key); - if (header == null) return null; + if (header == null) + { + return null; + } return header.Value; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/RootFolders/RootFolder.cs b/src/NzbDrone.Core/RootFolders/RootFolder.cs index 0ae3b0155..7e6c5444b 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 6983b67fc..21a1a5264 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) { @@ -18,4 +16,4 @@ namespace NzbDrone.Core.RootFolders protected override bool PublishModelEvents => true; } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/RootFolders/RootFolderService.cs b/src/NzbDrone.Core/RootFolders/RootFolderService.cs index 164ea26e1..9d1cc1194 100644 --- a/src/NzbDrone.Core/RootFolders/RootFolderService.cs +++ b/src/NzbDrone.Core/RootFolders/RootFolderService.cs @@ -1,8 +1,7 @@ -using System.Linq; using System; using System.Collections.Generic; using System.IO; -using System.Threading; +using System.Linq; using System.Threading.Tasks; using NLog; using NzbDrone.Common; @@ -42,7 +41,6 @@ namespace NzbDrone.Core.RootFolders ".grab" }; - public RootFolderService(IRootFolderRepository rootFolderRepository, IDiskProvider diskProvider, IArtistRepository artistRepository, @@ -74,6 +72,7 @@ namespace NzbDrone.Core.RootFolders 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) { diff --git a/src/NzbDrone.Core/RootFolders/UnmappedFolder.cs b/src/NzbDrone.Core/RootFolders/UnmappedFolder.cs index de5b28c5e..3a8a919de 100644 --- a/src/NzbDrone.Core/RootFolders/UnmappedFolder.cs +++ b/src/NzbDrone.Core/RootFolders/UnmappedFolder.cs @@ -5,4 +5,4 @@ public string Name { get; set; } public string Path { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Security/X509CertificateValidationService.cs b/src/NzbDrone.Core/Security/X509CertificateValidationService.cs index d53c24cff..7b6afca75 100644 --- a/src/NzbDrone.Core/Security/X509CertificateValidationService.cs +++ b/src/NzbDrone.Core/Security/X509CertificateValidationService.cs @@ -55,7 +55,6 @@ namespace NzbDrone.Core.Security return true; } - _logger.Error("Certificate validation for {0} failed. {1}", request.Address, sslPolicyErrors); return false; @@ -65,7 +64,7 @@ namespace NzbDrone.Core.Security { 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 20d6c9ce3..7037ff57f 100644 --- a/src/NzbDrone.Core/Tags/TagDetails.cs +++ b/src/NzbDrone.Core/Tags/TagDetails.cs @@ -17,7 +17,7 @@ namespace NzbDrone.Core.Tags { get { - return (ArtistIds.Any() || NotificationIds.Any() || RestrictionIds.Any() || DelayProfileIds.Any() || ImportListIds.Any()); + return ArtistIds.Any() || NotificationIds.Any() || RestrictionIds.Any() || DelayProfileIds.Any() || ImportListIds.Any(); } } } diff --git a/src/NzbDrone.Core/Tags/TagService.cs b/src/NzbDrone.Core/Tags/TagService.cs index 85b966fc4..87ecbe808 100644 --- a/src/NzbDrone.Core/Tags/TagService.cs +++ b/src/NzbDrone.Core/Tags/TagService.cs @@ -1,13 +1,12 @@ -using System; using System.Collections.Generic; using System.Linq; -using NzbDrone.Core.ImportLists; using NzbDrone.Core.Datastore; +using NzbDrone.Core.ImportLists; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Music; using NzbDrone.Core.Notifications; using NzbDrone.Core.Profiles.Delay; using NzbDrone.Core.Profiles.Releases; -using NzbDrone.Core.Music; namespace NzbDrone.Core.Tags { @@ -102,16 +101,15 @@ namespace NzbDrone.Core.Tags foreach (var tag in tags) { details.Add(new TagDetails - { - Id = tag.Id, - Label = tag.Label, - DelayProfileIds = delayProfiles.Where(c => c.Tags.Contains(tag.Id)).Select(c => c.Id).ToList(), - ImportListIds = importLists.Where(c => c.Tags.Contains(tag.Id)).Select(c => c.Id).ToList(), - 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(), - ArtistIds = artists.Where(c => c.Tags.Contains(tag.Id)).Select(c => c.Id).ToList() - } - ); + { + Id = tag.Id, + Label = tag.Label, + DelayProfileIds = delayProfiles.Where(c => c.Tags.Contains(tag.Id)).Select(c => c.Id).ToList(), + ImportListIds = importLists.Where(c => c.Tags.Contains(tag.Id)).Select(c => c.Id).ToList(), + 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(), + ArtistIds = artists.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 47d6ecdf3..83e4013ea 100644 --- a/src/NzbDrone.Core/ThingiProvider/ConfigContractNotFoundException.cs +++ b/src/NzbDrone.Core/ThingiProvider/ConfigContractNotFoundException.cs @@ -8,6 +8,5 @@ namespace NzbDrone.Core.ThingiProvider : base("Couldn't find config contract " + contract) { } - } } diff --git a/src/NzbDrone.Core/ThingiProvider/Events/ProviderUpdatedEvent.cs b/src/NzbDrone.Core/ThingiProvider/Events/ProviderUpdatedEvent.cs index 66222ad52..d1fbda8e0 100644 --- a/src/NzbDrone.Core/ThingiProvider/Events/ProviderUpdatedEvent.cs +++ b/src/NzbDrone.Core/ThingiProvider/Events/ProviderUpdatedEvent.cs @@ -11,4 +11,4 @@ namespace NzbDrone.Core.ThingiProvider.Events Definition = definition; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/ThingiProvider/IProvider.cs b/src/NzbDrone.Core/ThingiProvider/IProvider.cs index 386d2bfaf..ea92d71cd 100644 --- a/src/NzbDrone.Core/ThingiProvider/IProvider.cs +++ b/src/NzbDrone.Core/ThingiProvider/IProvider.cs @@ -14,4 +14,4 @@ namespace NzbDrone.Core.ThingiProvider ValidationResult Test(); object RequestAction(string stage, IDictionary<string, string> query); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/ThingiProvider/IProviderConfig.cs b/src/NzbDrone.Core/ThingiProvider/IProviderConfig.cs index 595e3866c..af3dc2317 100644 --- a/src/NzbDrone.Core/ThingiProvider/IProviderConfig.cs +++ b/src/NzbDrone.Core/ThingiProvider/IProviderConfig.cs @@ -6,4 +6,4 @@ namespace NzbDrone.Core.ThingiProvider { NzbDroneValidationResult Validate(); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/ThingiProvider/IProviderFactory.cs b/src/NzbDrone.Core/ThingiProvider/IProviderFactory.cs index 2627cec14..a2001fb8b 100644 --- a/src/NzbDrone.Core/ThingiProvider/IProviderFactory.cs +++ b/src/NzbDrone.Core/ThingiProvider/IProviderFactory.cs @@ -22,4 +22,4 @@ namespace NzbDrone.Core.ThingiProvider object RequestAction(TProviderDefinition definition, string action, IDictionary<string, string> query); List<TProviderDefinition> AllForTag(int tagId); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/ThingiProvider/IProviderRepository.cs b/src/NzbDrone.Core/ThingiProvider/IProviderRepository.cs index 8e7087344..421cc6899 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); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/ThingiProvider/NullConfig.cs b/src/NzbDrone.Core/ThingiProvider/NullConfig.cs index 9016f6644..f58f4fd95 100644 --- a/src/NzbDrone.Core/ThingiProvider/NullConfig.cs +++ b/src/NzbDrone.Core/ThingiProvider/NullConfig.cs @@ -11,4 +11,4 @@ namespace NzbDrone.Core.ThingiProvider return new NzbDroneValidationResult(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/ThingiProvider/ProviderRepository.cs b/src/NzbDrone.Core/ThingiProvider/ProviderRepository.cs index 1554ef789..305f80efb 100644 --- a/src/NzbDrone.Core/ThingiProvider/ProviderRepository.cs +++ b/src/NzbDrone.Core/ThingiProvider/ProviderRepository.cs @@ -12,9 +12,9 @@ namespace NzbDrone.Core.ThingiProvider { } -// public void DeleteImplementations(string implementation) -// { -// DataMapper.Delete<TProviderDefinition>(c => c.Implementation == implementation); -// } + // public void DeleteImplementations(string implementation) + // { + // DataMapper.Delete<TProviderDefinition>(c => c.Implementation == implementation); + // } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusBase.cs b/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusBase.cs index 395a43efd..229d502ac 100644 --- a/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusBase.cs +++ b/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusBase.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using NzbDrone.Core.Datastore; namespace NzbDrone.Core.ThingiProvider.Status diff --git a/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusRepository.cs b/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusRepository.cs index c2782b409..071f0ea9f 100644 --- a/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusRepository.cs +++ b/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusRepository.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; using System.Linq; -using System.Text; using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; @@ -15,7 +12,6 @@ namespace NzbDrone.Core.ThingiProvider.Status 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/ThingiProvider/Status/ProviderStatusServiceBase.cs b/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusServiceBase.cs index 36cdebd45..129617d3b 100644 --- a/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusServiceBase.cs +++ b/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusServiceBase.cs @@ -21,7 +21,6 @@ namespace NzbDrone.Core.ThingiProvider.Status where TProvider : IProvider where TModel : ProviderStatusBase, new() { - protected readonly object _syncRoot = new object(); protected readonly IProviderStatusRepository<TModel> _providerStatusRepository; diff --git a/src/NzbDrone.Core/TinyTwitter.cs b/src/NzbDrone.Core/TinyTwitter.cs index 29a1d0694..f7f77bb58 100644 --- a/src/NzbDrone.Core/TinyTwitter.cs +++ b/src/NzbDrone.Core/TinyTwitter.cs @@ -28,59 +28,56 @@ namespace TinyTwitter 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(); } /** - * + * * As of June 26th 2015 Direct Messaging is not part of TinyTwitter. * I have added it to Lidarr's copy to make our implementation easier * 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 @@ namespace TinyTwitter 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); @@ -104,9 +101,8 @@ namespace TinyTwitter WriteRequestBody(request); // It looks like a bug in HttpWebRequest. It throws random TimeoutExceptions - // after some requests. Abort the request seems to work. More info: + // 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 @@ namespace TinyTwitter 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 @@ namespace TinyTwitter 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 @@ namespace TinyTwitter 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 @@ namespace TinyTwitter return new Random().Next(0x0000000, 0x7fffffff).ToString("X8"); } } - - #endregion } public static class TinyTwitterHelperExtensions @@ -214,9 +214,10 @@ namespace TinyTwitter 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); @@ -231,4 +232,4 @@ namespace TinyTwitter .Replace("%7E", "~"); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Update/InstallUpdateService.cs b/src/NzbDrone.Core/Update/InstallUpdateService.cs index 4f66d286a..1746422fa 100644 --- a/src/NzbDrone.Core/Update/InstallUpdateService.cs +++ b/src/NzbDrone.Core/Update/InstallUpdateService.cs @@ -34,7 +34,6 @@ namespace NzbDrone.Core.Update private readonly IBackupService _backupService; private readonly IOsInfo _osInfo; - public InstallUpdateService(ICheckUpdateService checkUpdateService, IAppFolderInfo appFolderInfo, IDiskProvider diskProvider, @@ -54,6 +53,7 @@ namespace NzbDrone.Core.Update { 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 71f5c3d46..4f0e7d4ec 100644 --- a/src/NzbDrone.Core/Update/UpdateCheckService.cs +++ b/src/NzbDrone.Core/Update/UpdateCheckService.cs @@ -13,7 +13,6 @@ namespace NzbDrone.Core.Update private readonly IUpdatePackageProvider _updatePackageProvider; private readonly IConfigFileProvider _configFileProvider; - public CheckUpdateService(IUpdatePackageProvider updatePackageProvider, IConfigFileProvider configFileProvider) { @@ -26,4 +25,4 @@ namespace NzbDrone.Core.Update return _updatePackageProvider.GetLatestUpdate(_configFileProvider.Branch, BuildInfo.Version); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Update/UpdatePackageProvider.cs b/src/NzbDrone.Core/Update/UpdatePackageProvider.cs index caa2185a7..01ff9ffb4 100644 --- a/src/NzbDrone.Core/Update/UpdatePackageProvider.cs +++ b/src/NzbDrone.Core/Update/UpdatePackageProvider.cs @@ -48,7 +48,10 @@ namespace NzbDrone.Core.Update 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/Update/UpdateVerificationFailedException.cs b/src/NzbDrone.Core/Update/UpdateVerificationFailedException.cs index 75e9ae29c..e10710645 100644 --- a/src/NzbDrone.Core/Update/UpdateVerificationFailedException.cs +++ b/src/NzbDrone.Core/Update/UpdateVerificationFailedException.cs @@ -12,4 +12,4 @@ { } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Validation/FolderValidator.cs b/src/NzbDrone.Core/Validation/FolderValidator.cs index 32bcb141c..9eedeb459 100644 --- a/src/NzbDrone.Core/Validation/FolderValidator.cs +++ b/src/NzbDrone.Core/Validation/FolderValidator.cs @@ -12,8 +12,12 @@ namespace NzbDrone.Core.Validation protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; + if (context.PropertyValue == null) + { + return false; + } + return context.PropertyValue.ToString().IsPathValid(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Validation/GuidValidator.cs b/src/NzbDrone.Core/Validation/GuidValidator.cs index 37e9d0a9d..92fd53ad3 100644 --- a/src/NzbDrone.Core/Validation/GuidValidator.cs +++ b/src/NzbDrone.Core/Validation/GuidValidator.cs @@ -12,8 +12,11 @@ namespace NzbDrone.Core.Validation protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; - + if (context.PropertyValue == null) + { + return false; + } + return Guid.TryParse(context.PropertyValue.ToString(), out Guid guidOutput); } } diff --git a/src/NzbDrone.Core/Validation/MetadataProfileExistsValidator.cs b/src/NzbDrone.Core/Validation/MetadataProfileExistsValidator.cs index e9203dc59..8fd3e96d4 100644 --- a/src/NzbDrone.Core/Validation/MetadataProfileExistsValidator.cs +++ b/src/NzbDrone.Core/Validation/MetadataProfileExistsValidator.cs @@ -15,8 +15,15 @@ namespace NzbDrone.Core.Validation protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; - if ((int)context.PropertyValue == 0) return true; + if (context.PropertyValue == null) + { + return true; + } + + if ((int)context.PropertyValue == 0) + { + return true; + } return _profileService.Exists((int)context.PropertyValue); } diff --git a/src/NzbDrone.Core/Validation/NzbDroneValidationFailure.cs b/src/NzbDrone.Core/Validation/NzbDroneValidationFailure.cs index c8db4a84b..0cd3c9026 100644 --- a/src/NzbDrone.Core/Validation/NzbDroneValidationFailure.cs +++ b/src/NzbDrone.Core/Validation/NzbDroneValidationFailure.cs @@ -11,13 +11,11 @@ namespace NzbDrone.Core.Validation 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 d675fbb7a..5de154984 100644 --- a/src/NzbDrone.Core/Validation/NzbDroneValidationResult.cs +++ b/src/NzbDrone.Core/Validation/NzbDroneValidationResult.cs @@ -31,6 +31,7 @@ namespace NzbDrone.Core.Validation { failure = new NzbDroneValidationFailure(failureBase); } + if (failure.IsWarning) { warnings.Add(failure); @@ -55,4 +56,4 @@ namespace NzbDrone.Core.Validation public override bool IsValid => Errors.Empty(); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Validation/Paths/ArtistAncestorValidator.cs b/src/NzbDrone.Core/Validation/Paths/ArtistAncestorValidator.cs index d6de1df78..fc4c73d7d 100644 --- a/src/NzbDrone.Core/Validation/Paths/ArtistAncestorValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/ArtistAncestorValidator.cs @@ -17,7 +17,10 @@ namespace NzbDrone.Core.Validation.Paths protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } return !_artistService.GetAllArtists().Any(s => context.PropertyValue.ToString().IsParentPath(s.Path)); } diff --git a/src/NzbDrone.Core/Validation/Paths/ArtistExistsValidator.cs b/src/NzbDrone.Core/Validation/Paths/ArtistExistsValidator.cs index 6b8a12c26..e17a8ab16 100644 --- a/src/NzbDrone.Core/Validation/Paths/ArtistExistsValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/ArtistExistsValidator.cs @@ -1,9 +1,5 @@ using FluentValidation.Validators; using NzbDrone.Core.Music; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace NzbDrone.Core.Validation.Paths { @@ -19,9 +15,12 @@ namespace NzbDrone.Core.Validation.Paths protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } - return (!_artistService.GetAllArtists().Exists(s => s.Metadata.Value.ForeignArtistId == context.PropertyValue.ToString())); + return !_artistService.GetAllArtists().Exists(s => s.Metadata.Value.ForeignArtistId == context.PropertyValue.ToString()); } } } diff --git a/src/NzbDrone.Core/Validation/Paths/ArtistPathValidator.cs b/src/NzbDrone.Core/Validation/Paths/ArtistPathValidator.cs index f901127f3..accd36b03 100644 --- a/src/NzbDrone.Core/Validation/Paths/ArtistPathValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/ArtistPathValidator.cs @@ -1,10 +1,6 @@ using FluentValidation.Validators; using NzbDrone.Common.Extensions; using NzbDrone.Core.Music; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace NzbDrone.Core.Validation.Paths { @@ -20,12 +16,15 @@ namespace NzbDrone.Core.Validation.Paths 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 (!_artistService.GetAllArtists().Exists(s => s.Path.PathEquals(context.PropertyValue.ToString()) && s.Id != instanceId)); + return !_artistService.GetAllArtists().Exists(s => s.Path.PathEquals(context.PropertyValue.ToString()) && s.Id != instanceId); } } } diff --git a/src/NzbDrone.Core/Validation/Paths/FolderWritableValidator.cs b/src/NzbDrone.Core/Validation/Paths/FolderWritableValidator.cs index bf88cf3be..c58b5a273 100644 --- a/src/NzbDrone.Core/Validation/Paths/FolderWritableValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/FolderWritableValidator.cs @@ -16,9 +16,12 @@ namespace NzbDrone.Core.Validation.Paths 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()); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Validation/Paths/MappedNetworkDriveValidator.cs b/src/NzbDrone.Core/Validation/Paths/MappedNetworkDriveValidator.cs index b3de0437e..48e3da21e 100644 --- a/src/NzbDrone.Core/Validation/Paths/MappedNetworkDriveValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/MappedNetworkDriveValidator.cs @@ -22,14 +22,28 @@ namespace NzbDrone.Core.Validation.Paths 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); if (mount != null && mount.DriveType == DriveType.Network) @@ -40,4 +54,4 @@ namespace NzbDrone.Core.Validation.Paths return true; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Validation/Paths/PathExistsValidator.cs b/src/NzbDrone.Core/Validation/Paths/PathExistsValidator.cs index 8e3e39aed..77398b5e8 100644 --- a/src/NzbDrone.Core/Validation/Paths/PathExistsValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/PathExistsValidator.cs @@ -15,9 +15,12 @@ namespace NzbDrone.Core.Validation.Paths 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()); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Validation/Paths/PathValidator.cs b/src/NzbDrone.Core/Validation/Paths/PathValidator.cs index b652672b8..c546d3e79 100644 --- a/src/NzbDrone.Core/Validation/Paths/PathValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/PathValidator.cs @@ -21,8 +21,12 @@ namespace NzbDrone.Core.Validation.Paths protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; + if (context.PropertyValue == null) + { + return false; + } + return context.PropertyValue.ToString().IsPathValid(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Validation/Paths/RootFolderValidator.cs b/src/NzbDrone.Core/Validation/Paths/RootFolderValidator.cs index 43bd1e650..8494ac28b 100644 --- a/src/NzbDrone.Core/Validation/Paths/RootFolderValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/RootFolderValidator.cs @@ -16,9 +16,12 @@ namespace NzbDrone.Core.Validation.Paths 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())); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Validation/Paths/StartupFolderValidator.cs b/src/NzbDrone.Core/Validation/Paths/StartupFolderValidator.cs index 89fd0893e..158a9ca31 100644 --- a/src/NzbDrone.Core/Validation/Paths/StartupFolderValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/StartupFolderValidator.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Core.Validation.Paths public class StartupFolderValidator : PropertyValidator { private readonly IAppFolderInfo _appFolderInfo; - public StartupFolderValidator(IAppFolderInfo appFolderInfo) : base("Path cannot be an ancestor of the start up folder") @@ -17,9 +16,12 @@ namespace NzbDrone.Core.Validation.Paths 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()); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core/Validation/ProfileExistsValidator.cs b/src/NzbDrone.Core/Validation/ProfileExistsValidator.cs index b5d9bdb9f..c708a196e 100644 --- a/src/NzbDrone.Core/Validation/ProfileExistsValidator.cs +++ b/src/NzbDrone.Core/Validation/ProfileExistsValidator.cs @@ -15,7 +15,10 @@ namespace NzbDrone.Core.Validation 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/RuleBuilderExtensions.cs b/src/NzbDrone.Core/Validation/RuleBuilderExtensions.cs index fb4f14c32..900ddf152 100644 --- a/src/NzbDrone.Core/Validation/RuleBuilderExtensions.cs +++ b/src/NzbDrone.Core/Validation/RuleBuilderExtensions.cs @@ -1,7 +1,6 @@ using System.Text.RegularExpressions; using FluentValidation; using FluentValidation.Validators; -using NzbDrone.Core.Parser; namespace NzbDrone.Core.Validation { diff --git a/src/NzbDrone.Core/Validation/UrlValidator.cs b/src/NzbDrone.Core/Validation/UrlValidator.cs index a52c14a90..844ab80f2 100644 --- a/src/NzbDrone.Core/Validation/UrlValidator.cs +++ b/src/NzbDrone.Core/Validation/UrlValidator.cs @@ -21,8 +21,12 @@ namespace NzbDrone.Core.Validation protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; + if (context.PropertyValue == null) + { + return false; + } + return context.PropertyValue.ToString().IsValidUrl(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Host.Test/ContainerFixture.cs b/src/NzbDrone.Host.Test/ContainerFixture.cs index 6227b01ec..7da6a9fbc 100644 --- a/src/NzbDrone.Host.Test/ContainerFixture.cs +++ b/src/NzbDrone.Host.Test/ContainerFixture.cs @@ -1,22 +1,20 @@ 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 NzbDrone.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; namespace NzbDrone.App.Test { diff --git a/src/NzbDrone.Host.Test/NzbDroneProcessServiceFixture.cs b/src/NzbDrone.Host.Test/NzbDroneProcessServiceFixture.cs index fed0c03e6..80dbefe41 100644 --- a/src/NzbDrone.Host.Test/NzbDroneProcessServiceFixture.cs +++ b/src/NzbDrone.Host.Test/NzbDroneProcessServiceFixture.cs @@ -35,7 +35,7 @@ namespace NzbDrone.App.Test .Setup(c => c.FindProcessByName(It.Is<string>(f => f.Contains("NzbDrone")))) .Returns(new List<ProcessInfo> { - new ProcessInfo {Id = CURRENT_PROCESS_ID} + new ProcessInfo { Id = CURRENT_PROCESS_ID } }); Subject.PreventStartIfAlreadyRunning(); @@ -50,8 +50,8 @@ namespace NzbDrone.App.Test .Setup(c => c.FindProcessByName(ProcessProvider.LIDARR_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 @@ namespace NzbDrone.App.Test .Setup(c => c.FindProcessByName(ProcessProvider.LIDARR_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 e604b5761..4d3f44c9c 100644 --- a/src/NzbDrone.Host.Test/RouterTest.cs +++ b/src/NzbDrone.Host.Test/RouterTest.cs @@ -18,7 +18,6 @@ namespace NzbDrone.App.Test WindowsOnly(); } - [Test] public void Route_should_call_install_service_when_application_mode_is_install() { @@ -36,7 +35,6 @@ namespace NzbDrone.App.Test 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 @@ namespace NzbDrone.App.Test 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 @@ namespace NzbDrone.App.Test serviceMock.Setup(c => c.ServiceExist(ServiceProvider.SERVICE_NAME)).Returns(true); Subject.Route(ApplicationModes.InstallService); - } [Test] @@ -103,7 +99,6 @@ namespace NzbDrone.App.Test 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 ebc38f0c4..b8c0da4df 100644 --- a/src/NzbDrone.Host/AccessControl/FirewallAdapter.cs +++ b/src/NzbDrone.Host/AccessControl/FirewallAdapter.cs @@ -58,6 +58,7 @@ namespace NzbDrone.Host.AccessControl { _logger.Warn(ex, "Failed to check for open port in firewall"); } + return false; } @@ -87,7 +88,10 @@ namespace NzbDrone.Host.AccessControl 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 abd481040..71ea33052 100644 --- a/src/NzbDrone.Host/AccessControl/RemoteAccessException.cs +++ b/src/NzbDrone.Host/AccessControl/RemoteAccessException.cs @@ -5,19 +5,23 @@ namespace NzbDrone.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/Bootstrap.cs b/src/NzbDrone.Host/Bootstrap.cs index 8aa0d9379..e59755d05 100644 --- a/src/NzbDrone.Host/Bootstrap.cs +++ b/src/NzbDrone.Host/Bootstrap.cs @@ -15,8 +15,8 @@ namespace NzbDrone.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) { @@ -44,7 +44,6 @@ namespace NzbDrone.Host { startCallback(_container); } - else { SpinToExit(appMode); @@ -155,6 +154,7 @@ namespace NzbDrone.Host { return true; } + default: { return false; diff --git a/src/NzbDrone.Host/BrowserService.cs b/src/NzbDrone.Host/BrowserService.cs index 7ccf23b59..3766699d2 100644 --- a/src/NzbDrone.Host/BrowserService.cs +++ b/src/NzbDrone.Host/BrowserService.cs @@ -47,4 +47,4 @@ namespace NzbDrone.Host } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Host/IUserAlert.cs b/src/NzbDrone.Host/IUserAlert.cs index 04db62985..3be8f7e63 100644 --- a/src/NzbDrone.Host/IUserAlert.cs +++ b/src/NzbDrone.Host/IUserAlert.cs @@ -4,4 +4,4 @@ { void Alert(string message); } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Host/MainAppContainerBuilder.cs b/src/NzbDrone.Host/MainAppContainerBuilder.cs index 4b0b6f640..00de2fd3e 100644 --- a/src/NzbDrone.Host/MainAppContainerBuilder.cs +++ b/src/NzbDrone.Host/MainAppContainerBuilder.cs @@ -1,9 +1,8 @@ using System.Collections.Generic; -using Nancy.Bootstrapper; using Lidarr.Http; +using Nancy.Bootstrapper; using NzbDrone.Common.Composition; using NzbDrone.Common.EnvironmentInfo; -using NzbDrone.Common.Http.Dispatchers; using NzbDrone.SignalR; namespace NzbDrone.Host diff --git a/src/NzbDrone.Host/PlatformValidation.cs b/src/NzbDrone.Host/PlatformValidation.cs index ccd9ef145..be6b1833d 100644 --- a/src/NzbDrone.Host/PlatformValidation.cs +++ b/src/NzbDrone.Host/PlatformValidation.cs @@ -9,10 +9,10 @@ namespace NzbDrone.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 @@ namespace NzbDrone.Host return true; } - private static bool IsAssemblyAvailable(string assemblyString) { try @@ -52,7 +51,6 @@ namespace NzbDrone.Host Logger.Warn(e, "Couldn't load {0}", assemblyString); return false; } - } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Host/Router.cs b/src/NzbDrone.Host/Router.cs index 4cee0c86b..833e0b7ba 100644 --- a/src/NzbDrone.Host/Router.cs +++ b/src/NzbDrone.Host/Router.cs @@ -1,4 +1,3 @@ -using System; using NLog; using NzbDrone.Common; using NzbDrone.Common.EnvironmentInfo; @@ -6,7 +5,6 @@ using NzbDrone.Common.Processes; using NzbDrone.Host.AccessControl; using IServiceProvider = NzbDrone.Common.IServiceProvider; - namespace NzbDrone.Host { public class Router @@ -58,6 +56,7 @@ namespace NzbDrone.Host _nzbDroneConsoleFactory.Start(); break; } + case ApplicationModes.InstallService: { _logger.Debug("Install Service selected"); @@ -75,8 +74,10 @@ namespace NzbDrone.Host // Ensures that there isn't an instance of Lidarr 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"); @@ -91,6 +92,7 @@ namespace NzbDrone.Host break; } + case ApplicationModes.RegisterUrl: { _logger.Debug("Regiser URL selected"); @@ -98,6 +100,7 @@ namespace NzbDrone.Host break; } + default: { _consoleService.PrintHelp(); diff --git a/src/NzbDrone.Host/TerminateApplicationException.cs b/src/NzbDrone.Host/TerminateApplicationException.cs index 734fb65d2..cbcc0ceb2 100644 --- a/src/NzbDrone.Host/TerminateApplicationException.cs +++ b/src/NzbDrone.Host/TerminateApplicationException.cs @@ -9,4 +9,4 @@ namespace NzbDrone.Host { } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Host/WebHost/Middleware/SignalRMiddleware.cs b/src/NzbDrone.Host/WebHost/Middleware/SignalRMiddleware.cs index 1adae83e7..07badd229 100644 --- a/src/NzbDrone.Host/WebHost/Middleware/SignalRMiddleware.cs +++ b/src/NzbDrone.Host/WebHost/Middleware/SignalRMiddleware.cs @@ -66,10 +66,10 @@ namespace NzbDrone.Host.Middleware 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 5e0481369..d9df21338 100644 --- a/src/NzbDrone.Host/WebHost/WebHostController.cs +++ b/src/NzbDrone.Host/WebHost/WebHostController.cs @@ -91,13 +91,17 @@ namespace NzbDrone.Host .AddSignalR() #if !NETCOREAPP .AddJsonProtocol( -#else - .AddNewtonsoftJsonProtocol( -#endif options => { options.PayloadSerializerSettings = Json.GetSerializerSettings(); }); +#else + .AddNewtonsoftJsonProtocol( + options => + { + options.PayloadSerializerSettings = Json.GetSerializerSettings(); + }); +#endif }) .Configure(app => { diff --git a/src/NzbDrone.Integration.Test/ApiTests/ArtistEditorFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/ArtistEditorFixture.cs index d683b304e..fd7e16b86 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/ArtistEditorFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/ArtistEditorFixture.cs @@ -1,7 +1,7 @@ -using FluentAssertions; -using NUnit.Framework; -using Lidarr.Api.V1.Artist; using System.Linq; +using FluentAssertions; +using Lidarr.Api.V1.Artist; +using NUnit.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Integration.Test.ApiTests diff --git a/src/NzbDrone.Integration.Test/ApiTests/ArtistFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/ArtistFixture.cs index 91ce8402f..282ce9710 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/ArtistFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/ArtistFixture.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 ArtistFixture : IntegrationTest { - [Test, Order(0)] + [Test] + [Order(0)] public void add_artist_with_tags_should_store_them() { EnsureNoArtist("f59c5520-5f46-4d2c-b2c4-822eabf53419", "Linkin Park"); @@ -29,7 +30,8 @@ namespace NzbDrone.Integration.Test.ApiTests result.Tags.Should().Equal(tag.Id); } - [Test, Order(0)] + [Test] + [Order(0)] public void add_artist_without_profileid_should_return_badrequest() { IgnoreOnMonoVersions("5.12", "5.14"); @@ -43,7 +45,8 @@ namespace NzbDrone.Integration.Test.ApiTests Artist.InvalidPost(artist); } - [Test, Order(0)] + [Test] + [Order(0)] public void add_artist_without_path_should_return_badrequest() { IgnoreOnMonoVersions("5.12", "5.14"); @@ -57,7 +60,8 @@ namespace NzbDrone.Integration.Test.ApiTests Artist.InvalidPost(artist); } - [Test, Order(1)] + [Test] + [Order(1)] public void add_artist() { EnsureNoArtist("f59c5520-5f46-4d2c-b2c4-822eabf53419", "Linkin Park"); @@ -77,8 +81,8 @@ namespace NzbDrone.Integration.Test.ApiTests result.Path.Should().Be(Path.Combine(ArtistRootFolder, artist.ArtistName)); } - - [Test, Order(2)] + [Test] + [Order(2)] public void get_all_artist() { EnsureArtist("8ac6cc32-8ddf-43b1-9ac4-4b04f9053176", "Alien Ant Farm"); @@ -91,7 +95,8 @@ namespace NzbDrone.Integration.Test.ApiTests artists.Should().Contain(v => v.ForeignArtistId == "cc197bad-dc9c-440d-a5b5-d52ba2e14234"); } - [Test, Order(2)] + [Test] + [Order(2)] public void get_artist_by_id() { var artist = EnsureArtist("8ac6cc32-8ddf-43b1-9ac4-4b04f9053176", "Alien Ant Farm"); @@ -109,7 +114,8 @@ namespace NzbDrone.Integration.Test.ApiTests var result = Artist.InvalidGet(1000000); } - [Test, Order(2)] + [Test] + [Order(2)] public void update_artist_profile_id() { var artist = EnsureArtist("8ac6cc32-8ddf-43b1-9ac4-4b04f9053176", "Alien Ant Farm"); @@ -127,27 +133,30 @@ namespace NzbDrone.Integration.Test.ApiTests Artist.Get(artist.Id).QualityProfileId.Should().Be(profileId); } - [Test, Order(3)] + [Test] + [Order(3)] public void update_artist_monitored() { var artist = EnsureArtist("f59c5520-5f46-4d2c-b2c4-822eabf53419", "Linkin Park", false); artist.Monitored.Should().BeFalse(); - //artist.Seasons.First().Monitored.Should().BeFalse(); + //artist.Seasons.First().Monitored.Should().BeFalse(); artist.Monitored = true; + //artist.Seasons.ForEach(season => //{ // season.Monitored = true; //}); - var result = Artist.Put(artist); result.Monitored.Should().BeTrue(); + //result.Seasons.First().Monitored.Should().BeTrue(); } - [Test, Order(3)] + [Test] + [Order(3)] public void update_artist_tags() { var artist = EnsureArtist("8ac6cc32-8ddf-43b1-9ac4-4b04f9053176", "Alien Ant Farm"); @@ -169,7 +178,8 @@ namespace NzbDrone.Integration.Test.ApiTests } } - [Test, Order(4)] + [Test] + [Order(4)] public void delete_artist() { var artist = EnsureArtist("8ac6cc32-8ddf-43b1-9ac4-4b04f9053176", "Alien Ant Farm"); diff --git a/src/NzbDrone.Integration.Test/ApiTests/BlacklistFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/BlacklistFixture.cs index a67bb8e3c..22b9d3c1f 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/BlacklistFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/BlacklistFixture.cs @@ -1,7 +1,7 @@ using FluentAssertions; -using NUnit.Framework; using Lidarr.Api.V1.Artist; using Lidarr.Api.V1.Blacklist; +using NUnit.Framework; namespace NzbDrone.Integration.Test.ApiTests { @@ -15,7 +15,7 @@ namespace NzbDrone.Integration.Test.ApiTests public void should_be_able_to_add_to_blacklist() { _artist = EnsureArtist("8ac6cc32-8ddf-43b1-9ac4-4b04f9053176", "Alien Ant Farm"); - + Blacklist.Post(new BlacklistResource { ArtistId = _artist.Id, diff --git a/src/NzbDrone.Integration.Test/ApiTests/CalendarFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/CalendarFixture.cs index c386aacf2..240bc9553 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 Lidarr.Api.V1.Albums; -using NzbDrone.Integration.Test.Client; using System; using System.Collections.Generic; using System.Linq; +using FluentAssertions; +using Lidarr.Api.V1.Albums; +using NUnit.Framework; +using NzbDrone.Integration.Test.Client; namespace NzbDrone.Integration.Test.ApiTests { diff --git a/src/NzbDrone.Integration.Test/ApiTests/DiskSpaceFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/DiskSpaceFixture.cs index deb675433..c2f0f3caa 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/DiskSpaceFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/DiskSpaceFixture.cs @@ -1,7 +1,7 @@ using System.Linq; using FluentAssertions; -using NUnit.Framework; using Lidarr.Api.V1.DiskSpace; +using NUnit.Framework; using NzbDrone.Integration.Test.Client; namespace NzbDrone.Integration.Test.ApiTests diff --git a/src/NzbDrone.Integration.Test/ApiTests/DownloadClientFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/DownloadClientFixture.cs index d346c7991..4fe766393 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 @@ namespace NzbDrone.Integration.Test.ApiTests 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 @@ namespace NzbDrone.Integration.Test.ApiTests 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 @@ namespace NzbDrone.Integration.Test.ApiTests DownloadClients.InvalidPost(schema); } - [Test, Order(1)] + [Test] + [Order(1)] public void add_downloadclient() { EnsureNoDownloadClient(); @@ -73,7 +76,8 @@ namespace NzbDrone.Integration.Test.ApiTests result.Enable.Should().BeTrue(); } - [Test, Order(2)] + [Test] + [Order(2)] public void get_all_downloadclients() { EnsureDownloadClient(); @@ -83,7 +87,8 @@ namespace NzbDrone.Integration.Test.ApiTests clients.Should().NotBeNullOrEmpty(); } - [Test, Order(2)] + [Test] + [Order(2)] public void get_downloadclient_by_id() { var client = EnsureDownloadClient(); @@ -101,7 +106,8 @@ namespace NzbDrone.Integration.Test.ApiTests var result = DownloadClients.InvalidGet(1000000); } - [Test, Order(3)] + [Test] + [Order(3)] public void update_downloadclient() { EnsureNoDownloadClient(); @@ -113,7 +119,8 @@ namespace NzbDrone.Integration.Test.ApiTests 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 f49d86dbf..bd2f7d0ec 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/FileSystemFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/FileSystemFixture.cs @@ -1,14 +1,14 @@ +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; using FluentAssertions; using NUnit.Framework; -using System.Linq; +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 { @@ -16,7 +16,7 @@ namespace NzbDrone.Integration.Test.ApiTests public class FileSystemFixture : IntegrationTest { public ClientBase FileSystem; - + private string _file; private string _folder; @@ -33,7 +33,7 @@ namespace NzbDrone.Integration.Test.ApiTests _file = Assembly.GetExecutingAssembly().Location; _folder = Path.GetDirectoryName(_file) + Path.DirectorySeparatorChar; } - + [Test] public void get_filesystem_content_excluding_files() { diff --git a/src/NzbDrone.Integration.Test/ApiTests/HistoryFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/HistoryFixture.cs index 2a6faf9d1..820ef5900 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/HistoryFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/HistoryFixture.cs @@ -17,4 +17,4 @@ namespace NzbDrone.Integration.Test.ApiTests history.Records.Should().BeEmpty(); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Integration.Test/ApiTests/NamingConfigFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/NamingConfigFixture.cs index 12b566645..afdb65865 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() { @@ -42,7 +41,6 @@ namespace NzbDrone.Integration.Test.ApiTests config.RenameTracks = true; config.StandardTrackFormat = ""; - var errors = NamingConfig.InvalidPut(config); errors.Should().NotBeNull(); } diff --git a/src/NzbDrone.Integration.Test/ApiTests/NotificationFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/NotificationFixture.cs index 85ba510ff..28894e732 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/NotificationFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/NotificationFixture.cs @@ -3,7 +3,6 @@ using System.Linq; 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 2101497f8..10784f85a 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/ReleaseFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/ReleaseFixture.cs @@ -1,8 +1,8 @@ -using FluentAssertions; -using NUnit.Framework; -using Lidarr.Api.V1.Indexers; using System.Linq; using System.Net; +using FluentAssertions; +using Lidarr.Api.V1.Indexers; +using NUnit.Framework; namespace NzbDrone.Integration.Test.ApiTests { @@ -38,7 +38,6 @@ namespace NzbDrone.Integration.Test.ApiTests // 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 @@ namespace NzbDrone.Integration.Test.ApiTests releaseResource.Title.Should().NotBeNullOrWhiteSpace(); releaseResource.DownloadUrl.Should().NotBeNullOrWhiteSpace(); releaseResource.ArtistName.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/ReleasePushFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/ReleasePushFixture.cs index a65c3ab0d..799b37349 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/ReleasePushFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/ReleasePushFixture.cs @@ -1,10 +1,10 @@ -using FluentAssertions; -using NUnit.Framework; -using Lidarr.Api.V1.Indexers; -using System.Net; -using System.Collections.Generic; using System; +using System.Collections.Generic; using System.Globalization; +using System.Net; +using FluentAssertions; +using Lidarr.Api.V1.Indexers; +using NUnit.Framework; namespace NzbDrone.Integration.Test.ApiTests { diff --git a/src/NzbDrone.Integration.Test/ApiTests/RootFolderFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/RootFolderFixture.cs index 7030b29d8..5abb4147f 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/RootFolderFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/RootFolderFixture.cs @@ -1,7 +1,7 @@ using System; using FluentAssertions; -using NUnit.Framework; using Lidarr.Api.V1.RootFolders; +using NUnit.Framework; namespace NzbDrone.Integration.Test.ApiTests { @@ -32,12 +32,10 @@ namespace NzbDrone.Integration.Test.ApiTests 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/ApiTests/TrackFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/TrackFixture.cs index e398fb801..91a86091d 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/TrackFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/TrackFixture.cs @@ -1,8 +1,8 @@ +using System.Linq; using System.Threading; using FluentAssertions; -using NUnit.Framework; using Lidarr.Api.V1.Artist; -using System.Linq; +using NUnit.Framework; namespace NzbDrone.Integration.Test.ApiTests { @@ -17,13 +17,15 @@ namespace NzbDrone.Integration.Test.ApiTests _artist = EnsureArtist("8ac6cc32-8ddf-43b1-9ac4-4b04f9053176", "Alien Ant Farm"); } - [Test, Order(0)] + [Test] + [Order(0)] public void should_be_able_to_get_all_tracks_in_artist() { Tracks.GetTracksInArtist(_artist.Id).Count.Should().BeGreaterThan(0); } - [Test, Order(1)] + [Test] + [Order(1)] public void should_be_able_to_get_a_single_track() { var tracks = Tracks.GetTracksInArtist(_artist.Id); diff --git a/src/NzbDrone.Integration.Test/ApiTests/WantedFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/WantedFixture.cs index a3d54d564..377597389 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/WantedFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/WantedFixture.cs @@ -8,7 +8,8 @@ namespace NzbDrone.Integration.Test.ApiTests [TestFixture] public class WantedFixture : IntegrationTest { - [Test, Order(0)] + [Test] + [Order(0)] public void missing_should_be_empty() { EnsureNoArtist("8ac6cc32-8ddf-43b1-9ac4-4b04f9053176", "Alien Ant Farm"); @@ -18,7 +19,8 @@ namespace NzbDrone.Integration.Test.ApiTests result.Records.Should().BeEmpty(); } - [Test, Order(1)] + [Test] + [Order(1)] public void missing_should_have_monitored_items() { EnsureArtist("8ac6cc32-8ddf-43b1-9ac4-4b04f9053176", "Alien Ant Farm", true); @@ -28,7 +30,8 @@ namespace NzbDrone.Integration.Test.ApiTests result.Records.Should().NotBeEmpty(); } - [Test, Order(1)] + [Test] + [Order(1)] public void missing_should_have_artist() { EnsureArtist("8ac6cc32-8ddf-43b1-9ac4-4b04f9053176", "Alien Ant Farm", true); @@ -39,7 +42,8 @@ namespace NzbDrone.Integration.Test.ApiTests result.Records.First().Artist.ArtistName.Should().Be("Alien Ant Farm"); } - [Test, Order(1)] + [Test] + [Order(1)] public void cutoff_should_have_monitored_items() { EnsureProfileCutoff(1, "Lossless"); @@ -51,7 +55,8 @@ namespace NzbDrone.Integration.Test.ApiTests result.Records.Should().NotBeEmpty(); } - [Test, Order(1)] + [Test] + [Order(1)] public void missing_should_not_have_unmonitored_items() { EnsureArtist("8ac6cc32-8ddf-43b1-9ac4-4b04f9053176", "Alien Ant Farm", false); @@ -61,7 +66,8 @@ namespace NzbDrone.Integration.Test.ApiTests result.Records.Should().BeEmpty(); } - [Test, Order(1)] + [Test] + [Order(1)] public void cutoff_should_not_have_unmonitored_items() { EnsureProfileCutoff(1, "Lossless"); @@ -73,7 +79,8 @@ namespace NzbDrone.Integration.Test.ApiTests result.Records.Should().BeEmpty(); } - [Test, Order(1)] + [Test] + [Order(1)] public void cutoff_should_have_artist() { EnsureProfileCutoff(1, "Lossless"); @@ -86,7 +93,8 @@ namespace NzbDrone.Integration.Test.ApiTests result.Records.First().Artist.ArtistName.Should().Be("Alien Ant Farm"); } - [Test, Order(2)] + [Test] + [Order(2)] public void missing_should_have_unmonitored_items() { EnsureArtist("8ac6cc32-8ddf-43b1-9ac4-4b04f9053176", "Alien Ant Farm", false); @@ -96,7 +104,8 @@ namespace NzbDrone.Integration.Test.ApiTests result.Records.Should().NotBeEmpty(); } - [Test, Order(2)] + [Test] + [Order(2)] public void cutoff_should_have_unmonitored_items() { EnsureProfileCutoff(1, "Lossless"); diff --git a/src/NzbDrone.Integration.Test/Client/ArtistClient.cs b/src/NzbDrone.Integration.Test/Client/ArtistClient.cs index e8efd6764..9605b1e4f 100644 --- a/src/NzbDrone.Integration.Test/Client/ArtistClient.cs +++ b/src/NzbDrone.Integration.Test/Client/ArtistClient.cs @@ -31,7 +31,6 @@ namespace NzbDrone.Integration.Test.Client var request = BuildRequest(slug); return Get<ArtistResource>(request, statusCode); } - } public class SystemInfoClient : ClientBase<ArtistResource> diff --git a/src/NzbDrone.Integration.Test/Client/ClientBase.cs b/src/NzbDrone.Integration.Test/Client/ClientBase.cs index c0daa7c93..0dd38b1a5 100644 --- a/src/NzbDrone.Integration.Test/Client/ClientBase.cs +++ b/src/NzbDrone.Integration.Test/Client/ClientBase.cs @@ -60,7 +60,8 @@ namespace NzbDrone.Integration.Test.Client 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 @@ namespace NzbDrone.Integration.Test.Client public ClientBase(IRestClient restClient, string apiKey, string resource = null) : base(restClient, apiKey, resource ?? new TResource().ResourceName) { - } public List<TResource> All() @@ -161,19 +161,22 @@ namespace NzbDrone.Integration.Test.Client 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 30ac0fa0e..a47624916 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.Linq; using System; +using System.Linq; +using System.Threading; +using FluentAssertions; using Lidarr.Http.REST; using Newtonsoft.Json; +using NUnit.Framework; +using NzbDrone.Core.Messaging.Commands; +using RestSharp; namespace NzbDrone.Integration.Test.Client { @@ -27,7 +27,10 @@ namespace NzbDrone.Integration.Test.Client [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 @@ namespace NzbDrone.Integration.Test.Client { } - 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); @@ -72,7 +76,7 @@ namespace NzbDrone.Integration.Test.Client Thread.Sleep(500); resources = All(); } - + Assert.Fail("Commands still processing"); } } diff --git a/src/NzbDrone.Integration.Test/Client/LogsClient.cs b/src/NzbDrone.Integration.Test/Client/LogsClient.cs index b64ec2971..99e4a27ae 100644 --- a/src/NzbDrone.Integration.Test/Client/LogsClient.cs +++ b/src/NzbDrone.Integration.Test/Client/LogsClient.cs @@ -21,4 +21,4 @@ namespace NzbDrone.Integration.Test.Client return lines; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Integration.Test/CorsFixture.cs b/src/NzbDrone.Integration.Test/CorsFixture.cs index 6b0a7bc70..810c5083e 100644 --- a/src/NzbDrone.Integration.Test/CorsFixture.cs +++ b/src/NzbDrone.Integration.Test/CorsFixture.cs @@ -1,6 +1,6 @@ using FluentAssertions; -using NUnit.Framework; using Lidarr.Http.Extensions; +using NUnit.Framework; using RestSharp; namespace NzbDrone.Integration.Test @@ -23,12 +23,12 @@ namespace NzbDrone.Integration.Test return request; } - [Test] + [Test] public void should_not_have_allow_headers_in_response_when_not_included_in_the_request() { var request = BuildOptions(); var response = RestClient.Execute(request); - + response.Headers.Should().NotContain(h => h.Name == AccessControlHeaders.AllowHeaders); } diff --git a/src/NzbDrone.Integration.Test/GenericApiFixture.cs b/src/NzbDrone.Integration.Test/GenericApiFixture.cs index 2f2b2bca7..63c6e9dbc 100644 --- a/src/NzbDrone.Integration.Test/GenericApiFixture.cs +++ b/src/NzbDrone.Integration.Test/GenericApiFixture.cs @@ -1,8 +1,6 @@ using System.Net; using FluentAssertions; using NUnit.Framework; -using NzbDrone.Common.Extensions; -using NzbDrone.Integration.Test.Client; using RestSharp; namespace NzbDrone.Integration.Test @@ -18,7 +16,6 @@ namespace NzbDrone.Integration.Test [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 dc51501b8..8bd1a26fc 100644 --- a/src/NzbDrone.Integration.Test/IndexHtmlFixture.cs +++ b/src/NzbDrone.Integration.Test/IndexHtmlFixture.cs @@ -13,6 +13,5 @@ namespace NzbDrone.Integration.Test var text = new WebClient().DownloadString(RootUrl); text.Should().NotBeNullOrWhiteSpace(); } - } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Integration.Test/IntegrationTest.cs b/src/NzbDrone.Integration.Test/IntegrationTest.cs index d56c8b82c..c4897fd24 100644 --- a/src/NzbDrone.Integration.Test/IntegrationTest.cs +++ b/src/NzbDrone.Integration.Test/IntegrationTest.cs @@ -1,7 +1,7 @@ +using Lidarr.Http.ClientSchema; using NLog; using NzbDrone.Core.Indexers.Newznab; using NzbDrone.Test.Common; -using Lidarr.Http.ClientSchema; namespace NzbDrone.Integration.Test { diff --git a/src/NzbDrone.Integration.Test/IntegrationTestBase.cs b/src/NzbDrone.Integration.Test/IntegrationTestBase.cs index 03f162d79..aadaa7dc1 100644 --- a/src/NzbDrone.Integration.Test/IntegrationTestBase.cs +++ b/src/NzbDrone.Integration.Test/IntegrationTestBase.cs @@ -3,30 +3,30 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; +using System.Threading.Tasks; using FluentAssertions; -using NLog; -using NLog.Config; -using NLog.Targets; -using NUnit.Framework; +using Lidarr.Api.V1.Albums; +using Lidarr.Api.V1.Artist; using Lidarr.Api.V1.Blacklist; using Lidarr.Api.V1.Config; using Lidarr.Api.V1.DownloadClient; using Lidarr.Api.V1.History; using Lidarr.Api.V1.Profiles.Quality; using Lidarr.Api.V1.RootFolders; -using Lidarr.Api.V1.Artist; -using Lidarr.Api.V1.Albums; using Lidarr.Api.V1.Tags; +using Microsoft.AspNetCore.SignalR.Client; +using NLog; +using NLog.Config; +using NLog.Targets; +using NUnit.Framework; using NzbDrone.Common.EnvironmentInfo; +using NzbDrone.Core.MediaFiles.TrackImport.Manual; using NzbDrone.Core.Qualities; using NzbDrone.Integration.Test.Client; using NzbDrone.SignalR; +using NzbDrone.Test.Common; using NzbDrone.Test.Common.Categories; using RestSharp; -using NzbDrone.Core.MediaFiles.TrackImport.Manual; -using NzbDrone.Test.Common; -using System.Threading.Tasks; -using Microsoft.AspNetCore.SignalR.Client; namespace NzbDrone.Integration.Test { @@ -140,7 +140,6 @@ namespace NzbDrone.Integration.Test { if (_signalrConnection != null) { - await _signalrConnection.StopAsync(); _signalrConnection = null; @@ -237,13 +236,17 @@ namespace NzbDrone.Integration.Test for (var i = 0; i < count; i++) { if (predicate()) + { return; + } Thread.Sleep(interval); } if (predicate()) + { return; + } Assert.Fail("Timed on wait"); } @@ -294,7 +297,6 @@ namespace NzbDrone.Integration.Test return result; } - public void EnsureNoArtist(string lidarrId, string artistTitle) { var result = Artist.All().FirstOrDefault(v => v.ForeignArtistId == lidarrId); @@ -316,9 +318,12 @@ namespace NzbDrone.Integration.Test Directory.CreateDirectory(Path.GetDirectoryName(path)); File.WriteAllText(path, "Fake Track"); - Commands.PostAndWait(new ManualImportCommand { - Files = new List<ManualImportFile> { - new ManualImportFile { + Commands.PostAndWait(new ManualImportCommand + { + Files = new List<ManualImportFile> + { + new ManualImportFile + { Path = path, ArtistId = artist.Id, AlbumId = albumId, @@ -326,10 +331,10 @@ namespace NzbDrone.Integration.Test TrackIds = new List<int> { trackId }, Quality = new QualityModel(quality) } - } - }); + } + }); Commands.WaitAll(); - + var track = Tracks.GetTracksInArtist(artist.Id).Single(x => x.Id == trackId); track.TrackFileId.Should().NotBe(0); diff --git a/src/NzbDrone.Mono.Test/DiskProviderTests/DiskProviderFixture.cs b/src/NzbDrone.Mono.Test/DiskProviderTests/DiskProviderFixture.cs index fd4c04594..585c19eb4 100644 --- a/src/NzbDrone.Mono.Test/DiskProviderTests/DiskProviderFixture.cs +++ b/src/NzbDrone.Mono.Test/DiskProviderTests/DiskProviderFixture.cs @@ -14,7 +14,7 @@ using NzbDrone.Mono.Disk; namespace NzbDrone.Mono.Test.DiskProviderTests { [TestFixture] - [Platform(Exclude="Win")] + [Platform(Exclude = "Win")] public class DiskProviderFixture : DiskProviderFixtureBase<DiskProvider> { public DiskProviderFixture() @@ -30,7 +30,6 @@ namespace NzbDrone.Mono.Test.DiskProviderTests } // 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) @@ -101,7 +100,8 @@ namespace NzbDrone.Mono.Test.DiskProviderTests 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 7b6d8bbac..28e162410 100644 --- a/src/NzbDrone.Mono.Test/DiskProviderTests/FreeSpaceFixture.cs +++ b/src/NzbDrone.Mono.Test/DiskProviderTests/FreeSpaceFixture.cs @@ -1,13 +1,13 @@ +using FluentAssertions; using Moq; +using NUnit.Framework; using NzbDrone.Common.Test.DiskTests; using NzbDrone.Mono.Disk; -using NUnit.Framework; -using FluentAssertions; 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/MonoPlatformInfoFixture.cs b/src/NzbDrone.Mono.Test/EnvironmentInfo/MonoPlatformInfoFixture.cs index a2c0ffd5c..e833144ff 100644 --- a/src/NzbDrone.Mono.Test/EnvironmentInfo/MonoPlatformInfoFixture.cs +++ b/src/NzbDrone.Mono.Test/EnvironmentInfo/MonoPlatformInfoFixture.cs @@ -1,4 +1,3 @@ -using System; using FluentAssertions; using NUnit.Framework; using NzbDrone.Common.EnvironmentInfo; diff --git a/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/MacOsVersionAdapterFixture.cs b/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/MacOsVersionAdapterFixture.cs index 6ca90eb90..b650422cd 100644 --- a/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/MacOsVersionAdapterFixture.cs +++ b/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/MacOsVersionAdapterFixture.cs @@ -1,5 +1,4 @@ -using System; -using System.IO; +using System.IO; using FluentAssertions; using Moq; using NUnit.Framework; @@ -39,7 +38,6 @@ namespace NzbDrone.Mono.Test.EnvironmentInfo.VersionAdapters versionName.FullName.Should().Be("macOS " + versionString); } - [TestCase] public void should_detect_server() { @@ -74,4 +72,4 @@ namespace NzbDrone.Mono.Test.EnvironmentInfo.VersionAdapters .Verify(c => c.GetFiles(It.IsAny<string>(), SearchOption.TopDirectoryOnly), Times.Never()); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapterFixture.cs b/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapterFixture.cs index f3f9d28a5..1872c74af 100644 --- a/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapterFixture.cs +++ b/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapterFixture.cs @@ -37,7 +37,6 @@ namespace NzbDrone.Mono.Test.EnvironmentInfo.VersionAdapters Subject.Read().Should().BeNull(); } - [Test] public void should_return_null_if_release_file_doestn_exist() { @@ -76,7 +75,6 @@ namespace NzbDrone.Mono.Test.EnvironmentInfo.VersionAdapters 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 820783be7..b09eb4601 100644 --- a/src/NzbDrone.Mono/Disk/DiskProvider.cs +++ b/src/NzbDrone.Mono/Disk/DiskProvider.cs @@ -15,21 +15,21 @@ 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) : this(new FileSystem(), procMountProvider, symLinkResolver) { } - + public DiskProvider(IFileSystem fileSystem, IProcMountProvider procMountProvider, ISymbolicLinkResolver symLinkResolver) @@ -231,7 +231,10 @@ namespace NzbDrone.Mono.Disk { 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 964eb3a08..488623093 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/ProcMount.cs b/src/NzbDrone.Mono/Disk/ProcMount.cs index 5d7160440..ec6fb9484 100644 --- a/src/NzbDrone.Mono/Disk/ProcMount.cs +++ b/src/NzbDrone.Mono/Disk/ProcMount.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using System.IO; using Mono.Unix; using NzbDrone.Common.Disk; diff --git a/src/NzbDrone.Mono/Disk/ProcMountProvider.cs b/src/NzbDrone.Mono/Disk/ProcMountProvider.cs index 88e834d8a..3471116a9 100644 --- a/src/NzbDrone.Mono/Disk/ProcMountProvider.cs +++ b/src/NzbDrone.Mono/Disk/ProcMountProvider.cs @@ -16,13 +16,13 @@ namespace NzbDrone.Mono.Disk 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 readonly Regex OctalRegex = new Regex(@"\\\d{3}", RegexOptions.Compiled); + 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; private readonly Logger _logger; diff --git a/src/NzbDrone.Mono/Disk/SymbolicLinkResolver.cs b/src/NzbDrone.Mono/Disk/SymbolicLinkResolver.cs index 28edae7ca..829197522 100644 --- a/src/NzbDrone.Mono/Disk/SymbolicLinkResolver.cs +++ b/src/NzbDrone.Mono/Disk/SymbolicLinkResolver.cs @@ -24,7 +24,10 @@ namespace NzbDrone.Mono.Disk public string GetCompleteRealPath(string path) { - if (path == null) return null; + if (path == null) + { + return null; + } try { @@ -39,6 +42,7 @@ namespace NzbDrone.Mono.Disk dir += dirs[0]; realPath.Append(GetRealPath(dir)); } + for (var i = 1; i < lastIndex; ++i) { realPath.Append("/").Append(dirs[i]); @@ -46,6 +50,7 @@ namespace NzbDrone.Mono.Disk realPath.Remove(0, realPath.Length); realPath.Append(realSubPath); } + return realPath.ToString(); } catch (Exception ex) @@ -55,7 +60,6 @@ namespace NzbDrone.Mono.Disk } } - private static void GetPathComponents(string path, out string[] components, out int lastIndex) { var dirs = path.Split(UnixPath.DirectorySeparatorChar); @@ -83,6 +87,7 @@ namespace NzbDrone.Mono.Disk dirs[target++] = dirs[i]; } } + components = dirs; lastIndex = target; } @@ -113,8 +118,8 @@ namespace NzbDrone.Mono.Disk 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 4ba15f7eb..2965f5a1a 100644 --- a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/IssueFileVersionAdapter.cs +++ b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/IssueFileVersionAdapter.cs @@ -30,11 +30,10 @@ namespace NzbDrone.Mono.EnvironmentInfo.VersionAdapters var fileContent = _diskProvider.ReadAllText(issueFile); - // Ubuntu 14.04.5 LTS \n \l // Ubuntu 16.04.1 LTS \n \l - // Fedora/Centos + // Fedora/Centos // Kernel \r on an \m (\l) // Arch Linux \r (\l) @@ -49,4 +48,4 @@ namespace NzbDrone.Mono.EnvironmentInfo.VersionAdapters public bool Enabled => OsInfo.IsLinux; } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/MacOsVersionAdapter.cs b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/MacOsVersionAdapter.cs index b42e77f27..0a9b1f8ca 100644 --- a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/MacOsVersionAdapter.cs +++ b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/MacOsVersionAdapter.cs @@ -9,13 +9,11 @@ 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 +38,7 @@ namespace NzbDrone.Mono.EnvironmentInfo.VersionAdapters var versionFile = allFiles.SingleOrDefault(c => c.EndsWith("SystemVersion.plist") || - c.EndsWith("ServerVersion.plist") - ); + c.EndsWith("ServerVersion.plist")); if (string.IsNullOrWhiteSpace(versionFile)) { @@ -52,8 +49,6 @@ namespace NzbDrone.Mono.EnvironmentInfo.VersionAdapters var text = _diskProvider.ReadAllText(versionFile); var match = DarwinVersionRegex.Match(text); - - if (match.Success) { version = match.Groups["version"].Value; @@ -66,4 +61,4 @@ namespace NzbDrone.Mono.EnvironmentInfo.VersionAdapters public bool Enabled => OsInfo.IsOsx; } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapter.cs b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapter.cs index 80b05c148..78dcceec6 100644 --- a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapter.cs +++ b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapter.cs @@ -33,7 +33,7 @@ namespace NzbDrone.Mono.EnvironmentInfo.VersionAdapters 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,9 +71,8 @@ namespace NzbDrone.Mono.EnvironmentInfo.VersionAdapters } return new OsVersionModel(name, version, fullName); - } public bool Enabled => OsInfo.IsLinux; } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/SynologyVersionAdapter.cs b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/SynologyVersionAdapter.cs index 02bba34b1..994867527 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 @@ namespace NzbDrone.Mono.EnvironmentInfo.VersionAdapters 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.SignalR/SignalRMessage.cs b/src/NzbDrone.SignalR/SignalRMessage.cs index 17a7d4187..548d988a9 100644 --- a/src/NzbDrone.SignalR/SignalRMessage.cs +++ b/src/NzbDrone.SignalR/SignalRMessage.cs @@ -11,4 +11,4 @@ namespace NzbDrone.SignalR [JsonIgnore] public ModelAction Action { get; set; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Test.Common/AutoMoq/AutoMoqer.cs b/src/NzbDrone.Test.Common/AutoMoq/AutoMoqer.cs index 05cdb6811..f7eee539c 100644 --- a/src/NzbDrone.Test.Common/AutoMoq/AutoMoqer.cs +++ b/src/NzbDrone.Test.Common/AutoMoq/AutoMoqer.cs @@ -6,13 +6,13 @@ using System.Linq; 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.Disk; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Test.Common.AutoMoq.Unity; +using Unity; using Unity.Resolution; [assembly: InternalsVisibleTo("AutoMoq.Tests")] @@ -36,7 +36,6 @@ namespace NzbDrone.Test.Common.AutoMoq { DefaultBehavior = defaultBehavior; SetupAutoMoqer(new UnityContainer()); - } public AutoMoqer(IUnityContainer container) @@ -62,12 +61,14 @@ namespace NzbDrone.Test.Common.AutoMoq 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>(); @@ -89,9 +90,14 @@ namespace NzbDrone.Test.Common.AutoMoq 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) @@ -100,32 +106,38 @@ namespace NzbDrone.Test.Common.AutoMoq 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); } @@ -136,19 +148,19 @@ namespace NzbDrone.Test.Common.AutoMoq { var mock = registeredMock.Value as Mock; if (mock != null) + { mock.VerifyAll(); + } } } - #region private methods - private void SetupAutoMoqer(IUnityContainer container) { _container = container; container.RegisterInstance(this); _registeredMocks = new Dictionary<Type, object>(); - + RegisterPlatformLibrary(container); AddTheAutoMockingContainerExtensionToTheContainer(container); @@ -163,12 +175,14 @@ namespace NzbDrone.Test.Common.AutoMoq 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); @@ -180,7 +194,8 @@ namespace NzbDrone.Test.Common.AutoMoq return _registeredMocks.ContainsKey(type) == false; } - private static Type GetTheMockType<T>() where T : class + private static Type GetTheMockType<T>() + where T : class { return typeof(T); } @@ -203,14 +218,12 @@ namespace NzbDrone.Test.Common.AutoMoq // This seems to be required now so that Unity can resolve the extra arguments to the // Mono DiskProvider. I don't understand why we need this now but didn't before. // It's auto registering everything in the assembly with Ixxx -> xxx. - types.Except(new [] { diskProvider }).Where(t => t.GetInterfaces().Any(i => i.Name == "I" + t.Name)).ToList() + types.Except(new[] { diskProvider }).Where(t => t.GetInterfaces().Any(i => i.Name == "I" + t.Name)).ToList() .ForEach(t => container.RegisterType(t.GetInterface("I" + t.Name, false), t)); // This tells the mocker to resolve IFileSystem using an actual filesystem (and not a mock) // if not specified, giving the old behaviour before we switched to System.IO.Abstractions. SetConstant<IFileSystem>(new FileSystem()); } - - #endregion } } diff --git a/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingBuilderStrategy.cs b/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingBuilderStrategy.cs index 1756fe656..c841dc7d7 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 @@ namespace NzbDrone.Test.Common.AutoMoq.Unity } } - #region private methods - private bool AMockObjectShouldBeCreatedForThisType(Type type) { var mocker = _container.Resolve<AutoMoqer>(); @@ -78,7 +76,5 @@ namespace NzbDrone.Test.Common.AutoMoq.Unity { 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 b764c929d..71838c545 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 @@ namespace NzbDrone.Test.Common.AutoMoq.Unity 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 faccff30d..d62a0dce0 100644 --- a/src/NzbDrone.Test.Common/Categories/DiskAccessTestAttribute.cs +++ b/src/NzbDrone.Test.Common/Categories/DiskAccessTestAttribute.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Test.Common.Categories public DiskAccessTestAttribute() : base("DiskAccessTest") { - } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Test.Common/Categories/IntegrationTestAttribute.cs b/src/NzbDrone.Test.Common/Categories/IntegrationTestAttribute.cs index 43d46f0fe..f26c5e84e 100644 --- a/src/NzbDrone.Test.Common/Categories/IntegrationTestAttribute.cs +++ b/src/NzbDrone.Test.Common/Categories/IntegrationTestAttribute.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Test.Common.Categories public IntegrationTestAttribute() : base("IntegrationTest") { - } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Test.Common/Categories/ManualTestAttribute.cs b/src/NzbDrone.Test.Common/Categories/ManualTestAttribute.cs index 37700203b..0dd8fdec3 100644 --- a/src/NzbDrone.Test.Common/Categories/ManualTestAttribute.cs +++ b/src/NzbDrone.Test.Common/Categories/ManualTestAttribute.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Test.Common.Categories public ManualTestAttribute() : base("ManualTest") { - } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Test.Common/ConcurrencyCounter.cs b/src/NzbDrone.Test.Common/ConcurrencyCounter.cs index 03586ad60..6ee4554db 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 @@ namespace NzbDrone.Test.Common int threadId = Thread.CurrentThread.ManagedThreadId; lock (_mutex) { - _threads[threadId] = 1; } @@ -54,4 +53,4 @@ namespace NzbDrone.Test.Common } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Test.Common/ExceptionVerification.cs b/src/NzbDrone.Test.Common/ExceptionVerification.cs index a60d1297b..bcf417434 100644 --- a/src/NzbDrone.Test.Common/ExceptionVerification.cs +++ b/src/NzbDrone.Test.Common/ExceptionVerification.cs @@ -55,6 +55,7 @@ namespace NzbDrone.Test.Common errors += Environment.NewLine + string.Format("[{0}] {1}: {2} {3}", log.Level, log.LoggerName, log.FormattedMessage, exception); } + return errors; } @@ -75,7 +76,9 @@ namespace NzbDrone.Test.Common } if (!_waitEvent.Wait(msec)) + { break; + } } Expected(LogLevel.Error, count); @@ -142,9 +145,11 @@ namespace NzbDrone.Test.Common 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 + @@ -166,4 +171,4 @@ namespace NzbDrone.Test.Common } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Test.Common/LoggingTest.cs b/src/NzbDrone.Test.Common/LoggingTest.cs index 13706633d..2bb704971 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/MockerExtensions.cs b/src/NzbDrone.Test.Common/MockerExtensions.cs index 45f528e54..c4e18fd1c 100644 --- a/src/NzbDrone.Test.Common/MockerExtensions.cs +++ b/src/NzbDrone.Test.Common/MockerExtensions.cs @@ -12,4 +12,4 @@ namespace NzbDrone.Test.Common return service; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Test.Common/NzbDroneRunner.cs b/src/NzbDrone.Test.Common/NzbDroneRunner.cs index 8ebf5b1c1..600758638 100644 --- a/src/NzbDrone.Test.Common/NzbDroneRunner.cs +++ b/src/NzbDrone.Test.Common/NzbDroneRunner.cs @@ -113,7 +113,6 @@ namespace NzbDrone.Test.Common var args = "-nobrowser -data=\"" + AppData + "\""; _nzbDroneProcess = _processProvider.Start(outputNzbdroneConsoleExe, args, null, OnOutputDataReceived, OnOutputDataReceived); - } private void OnOutputDataReceived(string data) @@ -134,12 +133,10 @@ namespace NzbDrone.Test.Common var apiKey = Guid.NewGuid().ToString().Replace("-", ""); var xDoc = new XDocument( - new XDeclaration("1.0", "utf-8", "yes"), + 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 3cdb3bf35..659be6170 100644 --- a/src/NzbDrone.Test.Common/StringExtensions.cs +++ b/src/NzbDrone.Test.Common/StringExtensions.cs @@ -14,10 +14,11 @@ namespace NzbDrone.Test.Common path = path.Replace(":", ""); path = Path.DirectorySeparatorChar + path; } + path = path.Replace("\\", Path.DirectorySeparatorChar.ToString()); } return path; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Test.Common/TestBase.cs b/src/NzbDrone.Test.Common/TestBase.cs index 618643419..4968cf416 100644 --- a/src/NzbDrone.Test.Common/TestBase.cs +++ b/src/NzbDrone.Test.Common/TestBase.cs @@ -14,16 +14,15 @@ using NzbDrone.Test.Common.AutoMoq; 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 virtual void CoreTestSetup() { _subject = null; - } protected TSubject Subject @@ -37,9 +36,7 @@ namespace NzbDrone.Test.Common return _subject; } - } - } public abstract class TestBase : LoggingTest @@ -64,7 +61,6 @@ namespace NzbDrone.Test.Common } } - protected int RandomNumber { get @@ -79,7 +75,10 @@ namespace NzbDrone.Test.Common get { var virtualPath = Path.Combine(TempFolder, "VirtualNzbDrone"); - if (!Directory.Exists(virtualPath)) Directory.CreateDirectory(virtualPath); + if (!Directory.Exists(virtualPath)) + { + Directory.CreateDirectory(virtualPath); + } return virtualPath; } @@ -119,7 +118,6 @@ namespace NzbDrone.Test.Common DeleteTempFolder(_tempFolder); } - public static string GetUID() { return Process.GetCurrentProcess().Id + "_" + DateTime.Now.Ticks + "_" + Interlocked.Increment(ref _nextUid); @@ -200,17 +198,20 @@ namespace NzbDrone.Test.Common 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.Common/TestException.cs b/src/NzbDrone.Test.Common/TestException.cs index 751b4c346..b51331474 100644 --- a/src/NzbDrone.Test.Common/TestException.cs +++ b/src/NzbDrone.Test.Common/TestException.cs @@ -5,4 +5,4 @@ namespace NzbDrone.Test.Common public class TestException : Exception { } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Test.Dummy/DummyApp.cs b/src/NzbDrone.Test.Dummy/DummyApp.cs index 37b7f261e..9f515041d 100644 --- a/src/NzbDrone.Test.Dummy/DummyApp.cs +++ b/src/NzbDrone.Test.Dummy/DummyApp.cs @@ -7,7 +7,7 @@ namespace NzbDrone.Test.Dummy { public const string DUMMY_PROCCESS_NAME = "Lidarr.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 6d9a95687..91e41b692 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 7c3688682..dbba223db 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 @@ namespace NzbDrone.Update.Test [Test] public void should_call_update_with_correct_path() { - var ProcessPath = @"C:\Lidarr\lidarr.exe".AsOsAgnostic(); + var processPath = @"C:\Lidarr\lidarr.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:\Lidarr".AsOsAgnostic(), 12), Times.Once()); } - - } } diff --git a/src/NzbDrone.Update/UpdateApp.cs b/src/NzbDrone.Update/UpdateApp.cs index 67aa21b71..e975c9fad 100644 --- a/src/NzbDrone.Update/UpdateApp.cs +++ b/src/NzbDrone.Update/UpdateApp.cs @@ -15,10 +15,11 @@ namespace NzbDrone.Update { 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 +115,6 @@ namespace NzbDrone.Update 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 8a0f2fa4d..78b487e64 100644 --- a/src/NzbDrone.Update/UpdateContainerBuilder.cs +++ b/src/NzbDrone.Update/UpdateContainerBuilder.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using NzbDrone.Common.Composition; using NzbDrone.Common.EnvironmentInfo; -using NzbDrone.Common.Http.Dispatchers; namespace NzbDrone.Update { @@ -10,7 +9,6 @@ namespace NzbDrone.Update private UpdateContainerBuilder(IStartupContext startupContext, List<string> assemblies) : base(startupContext, assemblies) { - } public static IContainer Build(IStartupContext startupContext) diff --git a/src/NzbDrone.Update/UpdateEngine/BackupAppData.cs b/src/NzbDrone.Update/UpdateEngine/BackupAppData.cs index 0031b55cb..22b0b481a 100644 --- a/src/NzbDrone.Update/UpdateEngine/BackupAppData.cs +++ b/src/NzbDrone.Update/UpdateEngine/BackupAppData.cs @@ -43,7 +43,6 @@ namespace NzbDrone.Update.UpdateEngine _diskProvider.CreateFolder(backupFolderAppData); } - try { _diskTransferService.TransferFile(_appFolderInfo.GetConfigPath(), _appFolderInfo.GetUpdateBackupConfigFile(), TransferMode.Copy); diff --git a/src/NzbDrone.Update/UpdateEngine/DetectApplicationType.cs b/src/NzbDrone.Update/UpdateEngine/DetectApplicationType.cs index 23434ec51..ae56909fe 100644 --- a/src/NzbDrone.Update/UpdateEngine/DetectApplicationType.cs +++ b/src/NzbDrone.Update/UpdateEngine/DetectApplicationType.cs @@ -42,4 +42,4 @@ namespace NzbDrone.Update.UpdateEngine return AppType.Normal; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Update/UpdateEngine/InstallUpdateService.cs b/src/NzbDrone.Update/UpdateEngine/InstallUpdateService.cs index 6a2ffda00..84e939d14 100644 --- a/src/NzbDrone.Update/UpdateEngine/InstallUpdateService.cs +++ b/src/NzbDrone.Update/UpdateEngine/InstallUpdateService.cs @@ -57,10 +57,14 @@ namespace NzbDrone.Update.UpdateEngine _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 @@ namespace NzbDrone.Update.UpdateEngine _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) @@ -154,7 +160,6 @@ namespace NzbDrone.Update.UpdateEngine } } } - } } } diff --git a/src/NzbDrone.Update/UpdateEngine/StartNzbDrone.cs b/src/NzbDrone.Update/UpdateEngine/StartNzbDrone.cs index 1ae411bbe..acb5d096e 100644 --- a/src/NzbDrone.Update/UpdateEngine/StartNzbDrone.cs +++ b/src/NzbDrone.Update/UpdateEngine/StartNzbDrone.cs @@ -37,7 +37,6 @@ namespace NzbDrone.Update.UpdateEngine try { StartService(); - } catch (InvalidOperationException e) { diff --git a/src/NzbDrone.Update/UpdateEngine/TerminateNzbDrone.cs b/src/NzbDrone.Update/UpdateEngine/TerminateNzbDrone.cs index 7ad7173c3..38307a885 100644 --- a/src/NzbDrone.Update/UpdateEngine/TerminateNzbDrone.cs +++ b/src/NzbDrone.Update/UpdateEngine/TerminateNzbDrone.cs @@ -61,4 +61,4 @@ namespace NzbDrone.Update.UpdateEngine } } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Windows.Test/DiskProviderTests/DiskProviderFixture.cs b/src/NzbDrone.Windows.Test/DiskProviderTests/DiskProviderFixture.cs index ac1b5bb6f..0f8d96c0a 100644 --- a/src/NzbDrone.Windows.Test/DiskProviderTests/DiskProviderFixture.cs +++ b/src/NzbDrone.Windows.Test/DiskProviderTests/DiskProviderFixture.cs @@ -19,7 +19,6 @@ namespace NzbDrone.Windows.Test.DiskProviderTests 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.Test/DiskProviderTests/FreeSpaceFixture.cs b/src/NzbDrone.Windows.Test/DiskProviderTests/FreeSpaceFixture.cs index 633877880..fdb0b0988 100644 --- a/src/NzbDrone.Windows.Test/DiskProviderTests/FreeSpaceFixture.cs +++ b/src/NzbDrone.Windows.Test/DiskProviderTests/FreeSpaceFixture.cs @@ -22,7 +22,9 @@ namespace NzbDrone.Windows.Test.DiskProviderTests for (char driveletter = 'Z'; driveletter > 'D'; driveletter--) { if (new DriveInfo(driveletter.ToString()).IsReady) + { continue; + } Assert.Throws<DirectoryNotFoundException>(() => Subject.GetAvailableSpace(driveletter + @":\NOT_A_REAL_PATH\DOES_NOT_EXIST")); return; diff --git a/src/NzbDrone.Windows/Disk/DiskProvider.cs b/src/NzbDrone.Windows/Disk/DiskProvider.cs index 1ded18049..a0a01e86e 100644 --- a/src/NzbDrone.Windows/Disk/DiskProvider.cs +++ b/src/NzbDrone.Windows/Disk/DiskProvider.cs @@ -2,7 +2,6 @@ using System.IO; using System.IO.Abstractions; using System.Runtime.InteropServices; -using System.Security.AccessControl; using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.EnsureThat; @@ -16,14 +15,14 @@ namespace NzbDrone.Windows.Disk [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 DiskProvider() : this(new FileSystem()) @@ -42,7 +41,9 @@ namespace NzbDrone.Windows.Disk var root = GetPathRoot(path); if (!FolderExists(root)) + { throw new DirectoryNotFoundException(root); + } return DriveFreeSpaceEx(root); } @@ -59,12 +60,10 @@ namespace NzbDrone.Windows.Disk public override void SetPermissions(string path, string mask, string user, string group) { - } public override void CopyPermissions(string sourcePath, string targetPath, bool includeOwner) { - } public override long? GetTotalSize(string path) @@ -74,7 +73,9 @@ namespace NzbDrone.Windows.Disk var root = GetPathRoot(path); if (!FolderExists(root)) + { throw new DirectoryNotFoundException(root); + } return DriveTotalSizeEx(root); } @@ -121,7 +122,6 @@ namespace NzbDrone.Windows.Disk return 0; } - public override bool TryCreateHardLink(string source, string destination) { try diff --git a/src/NzbDrone.Windows/EnvironmentInfo/WindowsVersionInfo.cs b/src/NzbDrone.Windows/EnvironmentInfo/WindowsVersionInfo.cs index d71c9a7f0..6d9699f87 100644 --- a/src/NzbDrone.Windows/EnvironmentInfo/WindowsVersionInfo.cs +++ b/src/NzbDrone.Windows/EnvironmentInfo/WindowsVersionInfo.cs @@ -46,4 +46,4 @@ namespace NzbDrone.Windows.EnvironmentInfo return false; } } -} \ No newline at end of file +} diff --git a/src/NzbDrone/MessageBoxUserAlert.cs b/src/NzbDrone/MessageBoxUserAlert.cs index 1b5686864..b95eec3de 100644 --- a/src/NzbDrone/MessageBoxUserAlert.cs +++ b/src/NzbDrone/MessageBoxUserAlert.cs @@ -10,4 +10,4 @@ namespace NzbDrone MessageBox.Show(text: message, buttons: MessageBoxButtons.OK, icon: MessageBoxIcon.Warning, caption: "NzbDrone"); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone/SysTray/SysTrayApp.cs b/src/NzbDrone/SysTray/SysTrayApp.cs index c98a54f54..296394483 100644 --- a/src/NzbDrone/SysTray/SysTrayApp.cs +++ b/src/NzbDrone/SysTray/SysTrayApp.cs @@ -76,9 +76,8 @@ namespace NzbDrone.SysTray if (InvokeRequired) { - base.Invoke(new MethodInvoker(() => Dispose(isDisposing))); + Invoke(new MethodInvoker(() => Dispose(isDisposing))); } - else { base.Dispose(isDisposing); @@ -99,7 +98,6 @@ namespace NzbDrone.SysTray } catch (Exception) { - } } @@ -129,7 +127,6 @@ namespace NzbDrone.SysTray } catch (Exception) { - } } } diff --git a/src/ServiceHelpers/ServiceInstall/Program.cs b/src/ServiceHelpers/ServiceInstall/Program.cs index 02938247b..2cd9e7f37 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 265b86c43..923b2d076 100644 --- a/src/ServiceHelpers/ServiceInstall/ServiceHelper.cs +++ b/src/ServiceHelpers/ServiceInstall/ServiceHelper.cs @@ -31,18 +31,18 @@ namespace ServiceInstall } var startInfo = new ProcessStartInfo - { - FileName = LidarrExe, - Arguments = arg, - UseShellExecute = false, - RedirectStandardOutput = true, - RedirectStandardError = true, - CreateNoWindow = true - }; + { + FileName = LidarrExe, + 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(); diff --git a/src/ServiceHelpers/ServiceUninstall/Program.cs b/src/ServiceHelpers/ServiceUninstall/Program.cs index c8bc4f181..f57066bb7 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 9ad0944ee..c54ba9258 100644 --- a/src/ServiceHelpers/ServiceUninstall/ServiceHelper.cs +++ b/src/ServiceHelpers/ServiceUninstall/ServiceHelper.cs @@ -31,18 +31,18 @@ namespace ServiceUninstall } var startInfo = new ProcessStartInfo - { - FileName = LidarrExe, - Arguments = arg, - UseShellExecute = false, - RedirectStandardOutput = true, - RedirectStandardError = true, - CreateNoWindow = true - }; + { + FileName = LidarrExe, + 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(); diff --git a/src/Stylecop.ruleset b/src/Stylecop.ruleset new file mode 100644 index 000000000..2cc451f2d --- /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 000000000..b4321a13b --- /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" + } + } +}