From 6ca22c0f5cf64b3350b679e1ff7e4ad79da3d65e Mon Sep 17 00:00:00 2001 From: Jesus Recio Date: Wed, 2 Oct 2024 17:12:26 +0200 Subject: [PATCH 01/74] feat: add detekt setup --- build.gradle | 2 + config/detekt/detekt.yml | 682 ++++++++++++++++++++++++++++++++++++++ gradle/libs.versions.toml | 2 + 3 files changed, 686 insertions(+) create mode 100644 config/detekt/detekt.yml diff --git a/build.gradle b/build.gradle index 6fc0ba10acc..86ee228dcee 100644 --- a/build.gradle +++ b/build.gradle @@ -21,6 +21,7 @@ buildscript { plugins { alias libs.plugins.sonarqube alias libs.plugins.ksp apply false + alias libs.plugins.detekt } allprojects { @@ -37,6 +38,7 @@ subprojects { apply plugin: "com.google.devtools.ksp" apply plugin: "org.jlleitschuh.gradle.ktlint" apply plugin: "org.sonarqube" + apply plugin: "io.gitlab.arturbosch.detekt" } sonarqube { diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.yml new file mode 100644 index 00000000000..9879910ba86 --- /dev/null +++ b/config/detekt/detekt.yml @@ -0,0 +1,682 @@ +build: + maxIssues: 0 + excludeCorrectable: false + weights: + # complexity: 2 + # LongParameterList: 1 + # style: 1 + # comments: 1 + +config: + validation: true + warningsAsErrors: false + # when writing own rules with new properties, exclude the property path e.g.: 'my_rule_set,.*>.*>[my_property]' + excludes: '' + +processors: + active: true + exclude: + - 'DetektProgressListener' + # - 'KtFileCountProcessor' + # - 'PackageCountProcessor' + # - 'ClassCountProcessor' + # - 'FunctionCountProcessor' + # - 'PropertyCountProcessor' + # - 'ProjectComplexityProcessor' + # - 'ProjectCognitiveComplexityProcessor' + # - 'ProjectLLOCProcessor' + # - 'ProjectCLOCProcessor' + # - 'ProjectLOCProcessor' + # - 'ProjectSLOCProcessor' + # - 'LicenseHeaderLoaderExtension' + +console-reports: + active: true + exclude: + - 'ProjectStatisticsReport' + - 'ComplexityReport' + - 'NotificationReport' + - 'FindingsReport' + - 'FileBasedFindingsReport' + # - 'LiteFindingsReport' + +output-reports: + active: true + exclude: + # - 'TxtOutputReport' + # - 'XmlOutputReport' + # - 'HtmlOutputReport' + +comments: + active: true + AbsentOrWrongFileLicense: + active: false + licenseTemplateFile: 'license.template' + licenseTemplateIsRegex: false + CommentOverPrivateFunction: + active: false + CommentOverPrivateProperty: + active: false + DeprecatedBlockTag: + active: false + EndOfSentenceFormat: + active: false + endOfSentenceFormat: '([.?!][ \t\n\r\f<])|([.?!:]$)' + OutdatedDocumentation: + active: false + matchTypeParameters: true + matchDeclarationsOrder: true + allowParamOnConstructorProperties: false + UndocumentedPublicClass: + active: false + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + searchInNestedClass: true + searchInInnerClass: true + searchInInnerObject: true + searchInInnerInterface: true + UndocumentedPublicFunction: + active: false + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + UndocumentedPublicProperty: + active: false + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + +complexity: + active: true + ComplexCondition: + active: true + threshold: 4 + ComplexInterface: + active: false + threshold: 10 + includeStaticDeclarations: false + includePrivateDeclarations: false + ComplexMethod: + active: true + threshold: 15 + ignoreSingleWhenExpression: false + ignoreSimpleWhenEntries: false + ignoreNestingFunctions: false + nestingFunctions: + - 'also' + - 'apply' + - 'forEach' + - 'isNotNull' + - 'ifNull' + - 'let' + - 'run' + - 'use' + - 'with' + LabeledExpression: + active: false + ignoredLabels: [] + LargeClass: + active: true + threshold: 600 + LongMethod: + active: true + threshold: 60 + LongParameterList: + active: true + functionThreshold: 6 + constructorThreshold: 7 + ignoreDefaultParameters: false + ignoreDataClasses: true + ignoreAnnotatedParameter: [] + MethodOverloading: + active: false + threshold: 6 + NamedArguments: + active: false + threshold: 3 + ignoreArgumentsMatchingNames: false + NestedBlockDepth: + active: true + threshold: 4 + ReplaceSafeCallChainWithRun: + active: false + StringLiteralDuplication: + active: false + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + threshold: 3 + ignoreAnnotation: true + excludeStringsWithLessThan5Characters: true + ignoreStringsRegex: '$^' + TooManyFunctions: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + thresholdInFiles: 11 + thresholdInClasses: 11 + thresholdInInterfaces: 11 + thresholdInObjects: 11 + thresholdInEnums: 11 + ignoreDeprecated: false + ignorePrivate: false + ignoreOverridden: false + +coroutines: + active: true + GlobalCoroutineUsage: + active: false + InjectDispatcher: + active: false + dispatcherNames: + - 'IO' + - 'Default' + - 'Unconfined' + RedundantSuspendModifier: + active: false + SleepInsteadOfDelay: + active: false + SuspendFunWithCoroutineScopeReceiver: + active: false + SuspendFunWithFlowReturnType: + active: false + +empty-blocks: + active: true + EmptyCatchBlock: + active: true + allowedExceptionNameRegex: '_|(ignore|expected).*' + EmptyClassBlock: + active: true + EmptyDefaultConstructor: + active: true + EmptyDoWhileBlock: + active: true + EmptyElseBlock: + active: true + EmptyFinallyBlock: + active: true + EmptyForBlock: + active: true + EmptyFunctionBlock: + active: true + ignoreOverridden: false + EmptyIfBlock: + active: true + EmptyInitBlock: + active: true + EmptyKtFile: + active: true + EmptySecondaryConstructor: + active: true + EmptyTryBlock: + active: true + EmptyWhenBlock: + active: true + EmptyWhileBlock: + active: true + +exceptions: + active: true + ExceptionRaisedInUnexpectedLocation: + active: true + methodNames: + - 'equals' + - 'finalize' + - 'hashCode' + - 'toString' + InstanceOfCheckForException: + active: false + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + NotImplementedDeclaration: + active: false + ObjectExtendsThrowable: + active: false + PrintStackTrace: + active: true + RethrowCaughtException: + active: true + ReturnFromFinally: + active: true + ignoreLabeled: false + SwallowedException: + active: true + ignoredExceptionTypes: + - 'InterruptedException' + - 'MalformedURLException' + - 'NumberFormatException' + - 'ParseException' + allowedExceptionNameRegex: '_|(ignore|expected).*' + ThrowingExceptionFromFinally: + active: true + ThrowingExceptionInMain: + active: false + ThrowingExceptionsWithoutMessageOrCause: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + exceptions: + - 'ArrayIndexOutOfBoundsException' + - 'Exception' + - 'IllegalArgumentException' + - 'IllegalMonitorStateException' + - 'IllegalStateException' + - 'IndexOutOfBoundsException' + - 'NullPointerException' + - 'RuntimeException' + - 'Throwable' + ThrowingNewInstanceOfSameException: + active: true + TooGenericExceptionCaught: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + exceptionNames: + - 'ArrayIndexOutOfBoundsException' + - 'Error' + - 'Exception' + - 'IllegalMonitorStateException' + - 'IndexOutOfBoundsException' + - 'NullPointerException' + - 'RuntimeException' + - 'Throwable' + allowedExceptionNameRegex: '_|(ignore|expected).*' + TooGenericExceptionThrown: + active: true + exceptionNames: + - 'Error' + - 'Exception' + - 'RuntimeException' + - 'Throwable' + +naming: + active: true + BooleanPropertyNaming: + active: false + allowedPattern: '^(is|has|are)' + ignoreOverridden: true + ClassNaming: + active: true + classPattern: '[A-Z][a-zA-Z0-9]*' + ConstructorParameterNaming: + active: true + parameterPattern: '[a-z][A-Za-z0-9]*' + privateParameterPattern: '[a-z][A-Za-z0-9]*' + excludeClassPattern: '$^' + ignoreOverridden: true + EnumNaming: + active: true + enumEntryPattern: '[A-Z][_a-zA-Z0-9]*' + ForbiddenClassName: + active: false + forbiddenName: [] + FunctionMaxLength: + active: false + maximumFunctionNameLength: 30 + FunctionMinLength: + active: false + minimumFunctionNameLength: 3 + FunctionNaming: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + functionPattern: '[a-z][a-zA-Z0-9]*' + excludeClassPattern: '$^' + ignoreOverridden: true + FunctionParameterNaming: + active: true + parameterPattern: '[a-z][A-Za-z0-9]*' + excludeClassPattern: '$^' + ignoreOverridden: true + InvalidPackageDeclaration: + active: false + rootPackage: '' + requireRootInDeclaration: false + LambdaParameterNaming: + active: false + parameterPattern: '[a-z][A-Za-z0-9]*|_' + MatchingDeclarationName: + active: true + mustBeFirst: true + MemberNameEqualsClassName: + active: true + ignoreOverridden: true + NoNameShadowing: + active: false + NonBooleanPropertyPrefixedWithIs: + active: false + ObjectPropertyNaming: + active: true + constantPattern: '[A-Za-z][_A-Za-z0-9]*' + propertyPattern: '[A-Za-z][_A-Za-z0-9]*' + privatePropertyPattern: '(_)?[A-Za-z][_A-Za-z0-9]*' + PackageNaming: + active: true + packagePattern: '[a-z]+(\.[a-z][A-Za-z0-9]*)*' + TopLevelPropertyNaming: + active: true + constantPattern: '[A-Z][_A-Z0-9]*' + propertyPattern: '[A-Za-z][_A-Za-z0-9]*' + privatePropertyPattern: '_?[A-Za-z][_A-Za-z0-9]*' + VariableMaxLength: + active: false + maximumVariableNameLength: 64 + VariableMinLength: + active: false + minimumVariableNameLength: 1 + VariableNaming: + active: true + variablePattern: '[a-z][A-Za-z0-9]*' + privateVariablePattern: '(_)?[a-z][A-Za-z0-9]*' + excludeClassPattern: '$^' + ignoreOverridden: true + +performance: + active: true + ArrayPrimitive: + active: true + ForEachOnRange: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + SpreadOperator: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + UnnecessaryTemporaryInstantiation: + active: true + +potential-bugs: + active: true + AvoidReferentialEquality: + active: false + forbiddenTypePatterns: + - 'kotlin.String' + CastToNullableType: + active: false + Deprecation: + active: false + DontDowncastCollectionTypes: + active: false + DoubleMutabilityForCollection: + active: false + mutableTypes: + - 'kotlin.collections.MutableList' + - 'kotlin.collections.MutableMap' + - 'kotlin.collections.MutableSet' + - 'java.util.ArrayList' + - 'java.util.LinkedHashSet' + - 'java.util.HashSet' + - 'java.util.LinkedHashMap' + - 'java.util.HashMap' + DuplicateCaseInWhenExpression: + active: true + ElseCaseInsteadOfExhaustiveWhen: + active: false + EqualsAlwaysReturnsTrueOrFalse: + active: true + EqualsWithHashCodeExist: + active: true + ExitOutsideMain: + active: false + ExplicitGarbageCollectionCall: + active: true + HasPlatformType: + active: false + IgnoredReturnValue: + active: false + restrictToAnnotatedMethods: true + returnValueAnnotations: + - '*.CheckResult' + - '*.CheckReturnValue' + ignoreReturnValueAnnotations: + - '*.CanIgnoreReturnValue' + ignoreFunctionCall: [] + ImplicitDefaultLocale: + active: true + ImplicitUnitReturnType: + active: false + allowExplicitReturnType: true + InvalidRange: + active: true + IteratorHasNextCallsNextMethod: + active: true + IteratorNotThrowingNoSuchElementException: + active: true + LateinitUsage: + active: false + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + ignoreOnClassesPattern: '' + MapGetWithNotNullAssertionOperator: + active: false + MissingPackageDeclaration: + active: false + excludes: ['**/*.kts'] + MissingWhenCase: + active: true + allowElseExpression: true + NullCheckOnMutableProperty: + active: false + NullableToStringCall: + active: false + RedundantElseInWhen: + active: true + UnconditionalJumpStatementInLoop: + active: false + UnnecessaryNotNullOperator: + active: true + UnnecessarySafeCall: + active: true + UnreachableCatchBlock: + active: false + UnreachableCode: + active: true + UnsafeCallOnNullableType: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + UnsafeCast: + active: true + UnusedUnaryOperator: + active: false + UselessPostfixExpression: + active: false + WrongEqualsTypeParameter: + active: true + +style: + active: true + CanBeNonNullable: + active: false + ClassOrdering: + active: false + CollapsibleIfStatements: + active: false + DataClassContainsFunctions: + active: false + conversionFunctionPrefix: 'to' + DataClassShouldBeImmutable: + active: false + DestructuringDeclarationWithTooManyEntries: + active: false + maxDestructuringEntries: 3 + EqualsNullCall: + active: true + EqualsOnSignatureLine: + active: false + ExplicitCollectionElementAccessMethod: + active: false + ExplicitItLambdaParameter: + active: false + ExpressionBodySyntax: + active: false + includeLineWrapping: false + ForbiddenComment: + active: true + values: + - 'FIXME:' + - 'STOPSHIP:' + - 'TODO:' + allowedPatterns: '' + customMessage: '' + ForbiddenImport: + active: false + imports: [] + forbiddenPatterns: '' + ForbiddenMethodCall: + active: false + methods: + - 'kotlin.io.print' + - 'kotlin.io.println' + ForbiddenPublicDataClass: + active: true + excludes: ['**'] + ignorePackages: + - '*.internal' + - '*.internal.*' + ForbiddenVoid: + active: false + ignoreOverridden: false + ignoreUsageInGenerics: false + FunctionOnlyReturningConstant: + active: true + ignoreOverridableFunction: true + ignoreActualFunction: true + excludedFunctions: '' + LibraryCodeMustSpecifyReturnType: + active: true + excludes: ['**'] + LibraryEntitiesShouldNotBePublic: + active: true + excludes: ['**'] + LoopWithTooManyJumpStatements: + active: true + maxJumpCount: 1 + MagicNumber: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + ignoreNumbers: + - '-1' + - '0' + - '1' + - '2' + ignoreHashCodeFunction: true + ignorePropertyDeclaration: false + ignoreLocalVariableDeclaration: false + ignoreConstantDeclaration: true + ignoreCompanionObjectPropertyDeclaration: true + ignoreAnnotation: false + ignoreNamedArgument: true + ignoreEnums: false + ignoreRanges: false + ignoreExtensionFunctions: true + MandatoryBracesIfStatements: + active: false + MandatoryBracesLoops: + active: false + MaxLineLength: + active: true + maxLineLength: 120 + excludePackageStatements: true + excludeImportStatements: true + excludeCommentStatements: false + MayBeConst: + active: true + ModifierOrder: + active: true + MultilineLambdaItParameter: + active: false + NestedClassesVisibility: + active: true + NewLineAtEndOfFile: + active: true + NoTabs: + active: false + ObjectLiteralToLambda: + active: false + OptionalAbstractKeyword: + active: true + OptionalUnit: + active: false + OptionalWhenBraces: + active: false + PreferToOverPairSyntax: + active: false + ProtectedMemberInFinalClass: + active: true + RedundantExplicitType: + active: false + RedundantHigherOrderMapUsage: + active: false + RedundantVisibilityModifierRule: + active: false + ReturnCount: + active: true + max: 2 + excludedFunctions: 'equals' + excludeLabeled: false + excludeReturnFromLambda: true + excludeGuardClauses: false + SafeCast: + active: true + SerialVersionUIDInSerializableClass: + active: true + SpacingBetweenPackageAndImports: + active: false + ThrowsCount: + active: true + max: 2 + excludeGuardClauses: false + TrailingWhitespace: + active: false + UnderscoresInNumericLiterals: + active: false + acceptableLength: 4 + allowNonStandardGrouping: false + UnnecessaryAbstractClass: + active: true + UnnecessaryAnnotationUseSiteTarget: + active: false + UnnecessaryApply: + active: true + UnnecessaryFilter: + active: false + UnnecessaryInheritance: + active: true + UnnecessaryInnerClass: + active: false + UnnecessaryLet: + active: false + UnnecessaryParentheses: + active: false + UntilInsteadOfRangeTo: + active: false + UnusedImports: + active: false + UnusedPrivateClass: + active: true + UnusedPrivateMember: + active: true + allowedNames: '(_|ignored|expected|serialVersionUID)' + UseAnyOrNoneInsteadOfFind: + active: false + UseArrayLiteralsInAnnotations: + active: false + UseCheckNotNull: + active: false + UseCheckOrError: + active: false + UseDataClass: + active: false + allowVars: false + UseEmptyCounterpart: + active: false + UseIfEmptyOrIfBlank: + active: false + UseIfInsteadOfWhen: + active: false + UseIsNullOrEmpty: + active: false + UseOrEmpty: + active: false + UseRequire: + active: false + UseRequireNotNull: + active: false + UselessCallOnNotNull: + active: true + UtilityClassWithPublicConstructor: + active: true + VarCouldBeVal: + active: true + WildcardImport: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + excludeImports: + - 'java.util.*' diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 841312da68b..0611eb9cb03 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -22,6 +22,7 @@ androidxTestMonitor = "1.6.1" androidxTestUiAutomator ="2.2.0" androidxWork = "2.8.1" coil = "2.2.2" +detekt="1.20.0" dexopener = "2.0.5" disklrucache = "2.0.2" media3 ="1.1.1" @@ -124,3 +125,4 @@ markwon = ["markwon-core", "markwon-ext-tables", "markwon-ext-strikethrough", "m kotlin = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } sonarqube = { id = "org.sonarqube", version.ref = "sonarqube" } +detekt = { id = "io.gitlab.arturbosch.detekt", version.ref = "detekt" } From 0bcf121d95affa367752f5f266716ea694ae0e39 Mon Sep 17 00:00:00 2001 From: Jesus Recio Date: Fri, 4 Oct 2024 14:03:07 +0200 Subject: [PATCH 02/74] feat: add yml setup to execute in github actions --- .github/workflows/detekt.yml | 62 ++++++++++++++++++++++++++++++++++++ config/detekt/detekt.yml | 57 ++++++++++++++++----------------- 2 files changed, 89 insertions(+), 30 deletions(-) create mode 100644 .github/workflows/detekt.yml diff --git a/.github/workflows/detekt.yml b/.github/workflows/detekt.yml new file mode 100644 index 00000000000..eb1d6b19ec9 --- /dev/null +++ b/.github/workflows/detekt.yml @@ -0,0 +1,62 @@ +# This is a basic workflow that is manually triggered + +name: Detekt + +# Controls when the action will run. Workflow runs when manually triggered using the UI +# or API. +on: + workflow_dispatch: + # Inputs the workflow accepts. + inputs: + name: + # Friendly description to be shown in the UI instead of 'name' + description: 'Detekt' + # Default value if no value is explicitly provided + default: 'World' + # Input has to be provided for the workflow to run + required: true + # The data type of the input + type: string + + push: + branches: + - feature/detekt + pull_request: + branches: + - "master" + paths: + - ".github/workflows/detekt.yml" + +# A workflow run is made up of one or more jobs that can run sequentially or in parallel +jobs: + # This workflow contains a single job called "greet" + run: + # The type of runner that the job will run on + runs-on: ubuntu-latest + + # Steps represent a sequence of tasks that will be executed as part of the job + + steps: + - uses: actions/checkout@v4 + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: '17' + distribution: 'temurin' + + # Configure Gradle for optimal use in GitHub Actions, including caching of downloaded dependencies. + # See: https://github.com/gradle/actions/blob/main/setup-gradle/README.md + - name: Setup Gradle + uses: gradle/actions/setup-gradle@af1da67850ed9a4cedd57bfd976089dd991e2582 # v4.0.0 + - name: Set base line + run: ./gradlew detektBaseline + - name: module owncloudApp + run: ./gradlew detekt + - name: module owncloudDomain + run: ./gradlew owncloudDomain:detekt + - name: module owncloudData + run: ./gradlew owncloudData:detekt + - name: module owncloudComLibrary + run: ./gradlew owncloudComLibrary:detekt + - name: module owncloudTestUtil + run: ./gradlew owncloudTestUtil:detekt diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.yml index 9879910ba86..1c0e0dec11c 100644 --- a/config/detekt/detekt.yml +++ b/config/detekt/detekt.yml @@ -48,7 +48,7 @@ output-reports: # - 'HtmlOutputReport' comments: - active: true + active: false AbsentOrWrongFileLicense: active: false licenseTemplateFile: 'license.template' @@ -85,7 +85,7 @@ complexity: active: true ComplexCondition: active: true - threshold: 4 + threshold: 5 ComplexInterface: active: false threshold: 10 @@ -111,20 +111,20 @@ complexity: active: false ignoredLabels: [] LargeClass: - active: true + active: false threshold: 600 LongMethod: active: true - threshold: 60 + threshold: 100 LongParameterList: - active: true + active: false functionThreshold: 6 constructorThreshold: 7 ignoreDefaultParameters: false ignoreDataClasses: true ignoreAnnotatedParameter: [] MethodOverloading: - active: false + active: true threshold: 6 NamedArguments: active: false @@ -132,7 +132,7 @@ complexity: ignoreArgumentsMatchingNames: false NestedBlockDepth: active: true - threshold: 4 + threshold: 5 ReplaceSafeCallChainWithRun: active: false StringLiteralDuplication: @@ -143,7 +143,7 @@ complexity: excludeStringsWithLessThan5Characters: true ignoreStringsRegex: '$^' TooManyFunctions: - active: true + active: false excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] thresholdInFiles: 11 thresholdInClasses: 11 @@ -157,7 +157,7 @@ complexity: coroutines: active: true GlobalCoroutineUsage: - active: false + active: true InjectDispatcher: active: false dispatcherNames: @@ -165,13 +165,13 @@ coroutines: - 'Default' - 'Unconfined' RedundantSuspendModifier: - active: false + active: true SleepInsteadOfDelay: - active: false + active: true SuspendFunWithCoroutineScopeReceiver: - active: false + active: true SuspendFunWithFlowReturnType: - active: false + active: true empty-blocks: active: true @@ -192,7 +192,7 @@ empty-blocks: active: true EmptyFunctionBlock: active: true - ignoreOverridden: false + ignoreOverridden: true EmptyIfBlock: active: true EmptyInitBlock: @@ -211,19 +211,19 @@ empty-blocks: exceptions: active: true ExceptionRaisedInUnexpectedLocation: - active: true + active: false methodNames: - 'equals' - 'finalize' - 'hashCode' - 'toString' InstanceOfCheckForException: - active: false + active: true excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] NotImplementedDeclaration: - active: false + active: true ObjectExtendsThrowable: - active: false + active: true PrintStackTrace: active: true RethrowCaughtException: @@ -259,7 +259,7 @@ exceptions: ThrowingNewInstanceOfSameException: active: true TooGenericExceptionCaught: - active: true + active: false excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] exceptionNames: - 'ArrayIndexOutOfBoundsException' @@ -293,7 +293,6 @@ naming: parameterPattern: '[a-z][A-Za-z0-9]*' privateParameterPattern: '[a-z][A-Za-z0-9]*' excludeClassPattern: '$^' - ignoreOverridden: true EnumNaming: active: true enumEntryPattern: '[A-Z][_a-zA-Z0-9]*' @@ -311,27 +310,25 @@ naming: excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] functionPattern: '[a-z][a-zA-Z0-9]*' excludeClassPattern: '$^' - ignoreOverridden: true FunctionParameterNaming: active: true parameterPattern: '[a-z][A-Za-z0-9]*' excludeClassPattern: '$^' - ignoreOverridden: true InvalidPackageDeclaration: - active: false + active: true rootPackage: '' requireRootInDeclaration: false LambdaParameterNaming: - active: false + active: true parameterPattern: '[a-z][A-Za-z0-9]*|_' MatchingDeclarationName: active: true - mustBeFirst: true + mustBeFirst: false MemberNameEqualsClassName: active: true ignoreOverridden: true NoNameShadowing: - active: false + active: true NonBooleanPropertyPrefixedWithIs: active: false ObjectPropertyNaming: @@ -368,7 +365,7 @@ performance: active: true excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] SpreadOperator: - active: true + active: false excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] UnnecessaryTemporaryInstantiation: active: true @@ -539,7 +536,7 @@ style: active: true maxJumpCount: 1 MagicNumber: - active: true + active: false excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] ignoreNumbers: - '-1' @@ -562,7 +559,7 @@ style: active: false MaxLineLength: active: true - maxLineLength: 120 + maxLineLength: 150 excludePackageStatements: true excludeImportStatements: true excludeCommentStatements: false @@ -610,7 +607,7 @@ style: SpacingBetweenPackageAndImports: active: false ThrowsCount: - active: true + active: false max: 2 excludeGuardClauses: false TrailingWhitespace: From 419b8d452e95d95f2cfe21585882f067ee4cd89c Mon Sep 17 00:00:00 2001 From: Jesus Recio Date: Thu, 14 Nov 2024 09:20:40 +0100 Subject: [PATCH 03/74] feat: update detekt version to 1.23.3, adding new fields and removed deprecated ones --- config/detekt/detekt.yml | 53 +++++++++++++-------------------------- gradle/libs.versions.toml | 2 +- 2 files changed, 19 insertions(+), 36 deletions(-) diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.yml index 1c0e0dec11c..dc9eeda31f1 100644 --- a/config/detekt/detekt.yml +++ b/config/detekt/detekt.yml @@ -83,6 +83,9 @@ comments: complexity: active: true + CognitiveComplexMethod: + active: false + threshold: 15 ComplexCondition: active: true threshold: 5 @@ -91,7 +94,7 @@ complexity: threshold: 10 includeStaticDeclarations: false includePrivateDeclarations: false - ComplexMethod: + CyclomaticComplexMethod: active: true threshold: 15 ignoreSingleWhenExpression: false @@ -284,7 +287,6 @@ naming: BooleanPropertyNaming: active: false allowedPattern: '^(is|has|are)' - ignoreOverridden: true ClassNaming: active: true classPattern: '[A-Z][a-zA-Z0-9]*' @@ -355,7 +357,6 @@ naming: variablePattern: '[a-z][A-Za-z0-9]*' privateVariablePattern: '(_)?[a-z][A-Za-z0-9]*' excludeClassPattern: '$^' - ignoreOverridden: true performance: active: true @@ -393,8 +394,6 @@ potential-bugs: - 'java.util.HashSet' - 'java.util.LinkedHashMap' - 'java.util.HashMap' - DuplicateCaseInWhenExpression: - active: true ElseCaseInsteadOfExhaustiveWhen: active: false EqualsAlwaysReturnsTrueOrFalse: @@ -409,7 +408,7 @@ potential-bugs: active: false IgnoredReturnValue: active: false - restrictToAnnotatedMethods: true + restrictToConfig: true returnValueAnnotations: - '*.CheckResult' - '*.CheckReturnValue' @@ -436,15 +435,10 @@ potential-bugs: MissingPackageDeclaration: active: false excludes: ['**/*.kts'] - MissingWhenCase: - active: true - allowElseExpression: true NullCheckOnMutableProperty: active: false NullableToStringCall: active: false - RedundantElseInWhen: - active: true UnconditionalJumpStatementInLoop: active: false UnnecessaryNotNullOperator: @@ -469,6 +463,14 @@ potential-bugs: style: active: true + AlsoCouldBeApply: + active: false + BracesOnIfStatements: + singleLine: 'never' + multiLine: 'always' + BracesOnWhenStatements: + singleLine: 'necessary' + multiLine: 'consistent' CanBeNonNullable: active: false ClassOrdering: @@ -477,7 +479,8 @@ style: active: false DataClassContainsFunctions: active: false - conversionFunctionPrefix: 'to' + allowOperators: false + conversionFunctionPrefix: ['to'] DataClassShouldBeImmutable: active: false DestructuringDeclarationWithTooManyEntries: @@ -496,12 +499,8 @@ style: includeLineWrapping: false ForbiddenComment: active: true - values: - - 'FIXME:' - - 'STOPSHIP:' - - 'TODO:' allowedPatterns: '' - customMessage: '' + comments: ['FIXME:', 'STOPSHIP:', 'TODO:'] ForbiddenImport: active: false imports: [] @@ -511,12 +510,6 @@ style: methods: - 'kotlin.io.print' - 'kotlin.io.println' - ForbiddenPublicDataClass: - active: true - excludes: ['**'] - ignorePackages: - - '*.internal' - - '*.internal.*' ForbiddenVoid: active: false ignoreOverridden: false @@ -525,13 +518,7 @@ style: active: true ignoreOverridableFunction: true ignoreActualFunction: true - excludedFunctions: '' - LibraryCodeMustSpecifyReturnType: - active: true - excludes: ['**'] - LibraryEntitiesShouldNotBePublic: - active: true - excludes: ['**'] + excludedFunctions: [] LoopWithTooManyJumpStatements: active: true maxJumpCount: 1 @@ -553,8 +540,6 @@ style: ignoreEnums: false ignoreRanges: false ignoreExtensionFunctions: true - MandatoryBracesIfStatements: - active: false MandatoryBracesLoops: active: false MaxLineLength: @@ -581,8 +566,6 @@ style: active: true OptionalUnit: active: false - OptionalWhenBraces: - active: false PreferToOverPairSyntax: active: false ProtectedMemberInFinalClass: @@ -596,7 +579,7 @@ style: ReturnCount: active: true max: 2 - excludedFunctions: 'equals' + excludedFunctions: ['equals'] excludeLabeled: false excludeReturnFromLambda: true excludeGuardClauses: false diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 0611eb9cb03..0aa22203c6c 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -22,7 +22,7 @@ androidxTestMonitor = "1.6.1" androidxTestUiAutomator ="2.2.0" androidxWork = "2.8.1" coil = "2.2.2" -detekt="1.20.0" +detekt="1.23.3" dexopener = "2.0.5" disklrucache = "2.0.2" media3 ="1.1.1" From c81bbfc03afe79fc1c90c3acab9bdf5bae964cc7 Mon Sep 17 00:00:00 2001 From: Jesus Recio Date: Wed, 20 Nov 2024 11:09:48 +0100 Subject: [PATCH 04/74] feat: add dependency for detekt-rules-libraries and add available fields to detekt.yml file --- config/detekt/detekt.yml | 11 +++++++++++ gradle/libs.versions.toml | 1 + owncloudApp/build.gradle | 3 +++ owncloudComLibrary/build.gradle | 3 +++ owncloudData/build.gradle | 3 +++ owncloudDomain/build.gradle | 3 +++ owncloudTestUtil/build.gradle | 3 +++ 7 files changed, 27 insertions(+) diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.yml index dc9eeda31f1..1ad5d1301ad 100644 --- a/config/detekt/detekt.yml +++ b/config/detekt/detekt.yml @@ -282,6 +282,17 @@ exceptions: - 'RuntimeException' - 'Throwable' +libraries: + active: true + ForbiddenPublicDataClass: + active: true + ignorePackages: ['*.internal', '*.internal.*'] + LibraryCodeMustSpecifyReturnType: + active: true + allowOmitUnit: false + LibraryEntitiesShouldNotBePublic: + active: true + naming: active: true BooleanPropertyNaming: diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 0aa22203c6c..a9deda2f568 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -81,6 +81,7 @@ androidx-test-runner = { group = "androidx.test", name = "runner", version.ref = androidx-test-uiautomator = { group = "androidx.test.uiautomator", name = "uiautomator", version.ref = "androidxTestUiAutomator" } androidx-work-runtime-ktx = { group = "androidx.work", name = "work-runtime-ktx", version.ref = "androidxWork" } coil = { group = "io.coil-kt", name = "coil", version.ref = "coil" } +detekt-libraries = { module = "io.gitlab.arturbosch.detekt:detekt-rules-libraries", version.ref = "detekt" } dexopener = { group = "com.github.tmurakami", name = "dexopener", version.ref = "dexopener" } disklrucache = { group = "com.jakewharton", name = "disklrucache", version.ref = "disklrucache" } media3-exoplayer = { group = "androidx.media3", name = "media3-exoplayer", version.ref = "media3" } diff --git a/owncloudApp/build.gradle b/owncloudApp/build.gradle index 45cf212a379..ad2ef86b50b 100644 --- a/owncloudApp/build.gradle +++ b/owncloudApp/build.gradle @@ -85,6 +85,9 @@ dependencies { debugImplementation libs.androidx.fragment.testing debugImplementation libs.androidx.test.monitor debugImplementation libs.stetho + + // Detekt + detektPlugins libs.detekt.libraries } android { diff --git a/owncloudComLibrary/build.gradle b/owncloudComLibrary/build.gradle index 990895e4ff7..5660fc75c3c 100644 --- a/owncloudComLibrary/build.gradle +++ b/owncloudComLibrary/build.gradle @@ -26,6 +26,9 @@ dependencies { testImplementation 'junit:junit:4.13.2' testImplementation 'org.robolectric:robolectric:4.10' debugImplementation 'com.facebook.stetho:stetho-okhttp3:1.6.0' + + // Detekt + detektPlugins libs.detekt.libraries } android { diff --git a/owncloudData/build.gradle b/owncloudData/build.gradle index 0e62c821d84..f0ad6aff321 100644 --- a/owncloudData/build.gradle +++ b/owncloudData/build.gradle @@ -89,4 +89,7 @@ dependencies { androidTestImplementation libs.androidx.test.runner androidTestImplementation libs.kotlinx.coroutines.test androidTestImplementation(libs.mockk.android) { exclude module: "objenesis" } + + // Detekt + detektPlugins libs.detekt.libraries } diff --git a/owncloudDomain/build.gradle b/owncloudDomain/build.gradle index 93d50153250..cf369752485 100644 --- a/owncloudDomain/build.gradle +++ b/owncloudDomain/build.gradle @@ -45,4 +45,7 @@ dependencies { testImplementation libs.junit4 testImplementation libs.kotlinx.coroutines.test testImplementation libs.mockk + + // Detekt + detektPlugins libs.detekt.libraries } diff --git a/owncloudTestUtil/build.gradle b/owncloudTestUtil/build.gradle index 9e03fd7fc45..d3a3c184176 100644 --- a/owncloudTestUtil/build.gradle +++ b/owncloudTestUtil/build.gradle @@ -33,4 +33,7 @@ dependencies { implementation project(':owncloudComLibrary') implementation libs.kotlin.stdlib implementation libs.androidx.lifecycle.livedata.ktx + + // Detekt + detektPlugins libs.detekt.libraries } From 8c49a603c2e324377f8461cca30e93ce783703f3 Mon Sep 17 00:00:00 2001 From: Jesus Recio Date: Wed, 20 Nov 2024 13:05:42 +0100 Subject: [PATCH 05/74] feat: add dependency for detekt-formatting and add available fields to detekt.yml file --- config/detekt/detekt.yml | 196 +++++++++++++++++++++++++++++++- gradle/libs.versions.toml | 1 + owncloudApp/build.gradle | 1 + owncloudComLibrary/build.gradle | 1 + owncloudData/build.gradle | 1 + owncloudDomain/build.gradle | 1 + owncloudTestUtil/build.gradle | 1 + 7 files changed, 201 insertions(+), 1 deletion(-) diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.yml index 1ad5d1301ad..afa5077a48a 100644 --- a/config/detekt/detekt.yml +++ b/config/detekt/detekt.yml @@ -282,8 +282,202 @@ exceptions: - 'RuntimeException' - 'Throwable' +formatting: + active: false + AnnotationOnSeparateLine: + active: true + indentSize: 4 + AnnotationSpacing: + active: true + ArgumentListWrapping: + active: true + indentSize: 4 + maxLineLength: 120 + BlockCommentInitialStarAlignment: + active: true + ChainWrapping: + active: true + indentSize: 4 + ClassName: + active: false + CommentSpacing: + active: true + CommentWrapping: + active: true + indentSize: 4 + ContentReceiverMapping: + active: false + maxLineLength: 120 + indentSize: 4 + DiscouragedCommentLocation: + active: false + EnumEntryNameCase: + active: true + EnumWrapping: + active: false + intentSize: 4 + Filename: + active: true + FinalNewline: + active: true + insertFinalNewLine: true + FunKeywordSpacing: + active: true + FunctionName: + active: false + FunctionReturnTypeSpacing: + active: true + maxLineLength: 120 + FunctionSignature: + active: false + forceMultilineWhenParameterCountGreaterOrEqualThan: 2147483647 + functionBodyExpressionWrapping: 'default' + maxLineLength: 120 + indentSize: 4 + FunctionStartOfBodySpacing: + active: true + FunctionTypeReferenceSpacing: + active: true + IfElseBracing: + active: false + IfElseWrapping: + active: false + indentSize: 4 + ImportOrdering: + active: true + layout: '*,java.**,javax.**,kotlin.**,^' + Indentation: + active: true + indentSize: 4 + KdocWrapping: + active: true + indentSize: 4 + MaximumLineLength: + active: true + maxLineLength: 120 + ignoreBackTickedIdentifier: false + ModifierListSpacing: + active: true + MultiLineIfElse: + active: true + indentSize: 4 + MultilineExpressionWrapping: + active: false + indentSize: 4 + NoBlankLineBeforeRbrace: + active: true + NoBlankLineInList: + active: false + NoBlankLinesInChainedMethodCalls: + active: true + NoConsecutiveBlankLines: + active: true + NoConsecutiveComments: + active: false + NoEmptyClassBody: + active: true + NoEmptyFirstLineInClassBody: + active: false + indentSize: 4 + NoEmptyFirstLineInMethodBlock: + active: true + NoLineBreakAfterElse: + active: true + NoLineBreakBeforeAssignment: + active: true + NoMultipleSpaces: + active: true + NoSemicolons: + active: true + NoSingleLineBlockComment: + active: false + indentSize: 4 + NoTrailingSpaces: + active: true + NoUnitReturn: + active: true + NoUnusedImports: + active: true + NoWildcardImports: + active: true + packagesToUseImportOnDemandProperty: 'java.util.*,kotlinx.android.synthetic.**' + NullableTypeSpacing: + active: true + PackageName: + active: true + ParameterListSpacing: + active: false + ParameterListWrapping: + active: true + maxLineLength: 120 + indentSize: 4 + ParameterWrapping: + active: true + indentSize: 4 + MaxLineLength: 120 + PropertyName: + active: false + PropertyWrapping: + active: true + indentSize: 4 + maxLineLength: 120 + SpacingAroundAngleBrackets: + active: true + SpacingAroundColon: + active: true + SpacingAroundComma: + active: true + SpacingAroundCurly: + active: true + SpacingAroundDot: + active: true + SpacingAroundDoubleColon: + active: true + SpacingAroundKeyword: + active: true + SpacingAroundOperators: + active: true + SpacingAroundParens: + active: true + SpacingAroundRangeOperator: + active: true + SpacingAroundUnaryOperator: + active: true + SpacingBetweenDeclarationsWithAnnotations: + active: true + SpacingBetweenDeclarationsWithComments: + active: true + SpacingBetweenFunctionNameAndOpeningParenthesis: + active: true + StringTemplate: + active: true + StringTemplateIndent: + active: false + indentSize: 4 + TrailingCommaOnCallSite: + active: false + useTrailingCommaOnCallSite: true + TrailingCommaOnDeclarationSite: + active: false + useTrailingCommaOnDeclarationSite: true + TryCatchFinallySpacing: + active: false + indentSize: 4 + TypeArgumentListSpacing: + active: false + indentSize: 4 + TypeParameterListSpacing: + active: false + indentSize: 4 + UnnecessaryParenthesesBeforeTrailingLambda: + active: true + Wrapping: + active: true + indentSize: 4 + maxLineLength: 120 + libraries: - active: true + active: false ForbiddenPublicDataClass: active: true ignorePackages: ['*.internal', '*.internal.*'] diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index a9deda2f568..df12f8d39a2 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -81,6 +81,7 @@ androidx-test-runner = { group = "androidx.test", name = "runner", version.ref = androidx-test-uiautomator = { group = "androidx.test.uiautomator", name = "uiautomator", version.ref = "androidxTestUiAutomator" } androidx-work-runtime-ktx = { group = "androidx.work", name = "work-runtime-ktx", version.ref = "androidxWork" } coil = { group = "io.coil-kt", name = "coil", version.ref = "coil" } +detekt-formatting = { module = "io.gitlab.arturbosch.detekt:detekt-formatting", version.ref = "detekt" } detekt-libraries = { module = "io.gitlab.arturbosch.detekt:detekt-rules-libraries", version.ref = "detekt" } dexopener = { group = "com.github.tmurakami", name = "dexopener", version.ref = "dexopener" } disklrucache = { group = "com.jakewharton", name = "disklrucache", version.ref = "disklrucache" } diff --git a/owncloudApp/build.gradle b/owncloudApp/build.gradle index ad2ef86b50b..1d419095ec7 100644 --- a/owncloudApp/build.gradle +++ b/owncloudApp/build.gradle @@ -87,6 +87,7 @@ dependencies { debugImplementation libs.stetho // Detekt + detektPlugins libs.detekt.formatting detektPlugins libs.detekt.libraries } diff --git a/owncloudComLibrary/build.gradle b/owncloudComLibrary/build.gradle index 5660fc75c3c..b67c6464539 100644 --- a/owncloudComLibrary/build.gradle +++ b/owncloudComLibrary/build.gradle @@ -28,6 +28,7 @@ dependencies { debugImplementation 'com.facebook.stetho:stetho-okhttp3:1.6.0' // Detekt + detektPlugins libs.detekt.formatting detektPlugins libs.detekt.libraries } diff --git a/owncloudData/build.gradle b/owncloudData/build.gradle index f0ad6aff321..7f50823a276 100644 --- a/owncloudData/build.gradle +++ b/owncloudData/build.gradle @@ -91,5 +91,6 @@ dependencies { androidTestImplementation(libs.mockk.android) { exclude module: "objenesis" } // Detekt + detektPlugins libs.detekt.formatting detektPlugins libs.detekt.libraries } diff --git a/owncloudDomain/build.gradle b/owncloudDomain/build.gradle index cf369752485..e547d68bcd2 100644 --- a/owncloudDomain/build.gradle +++ b/owncloudDomain/build.gradle @@ -47,5 +47,6 @@ dependencies { testImplementation libs.mockk // Detekt + detektPlugins libs.detekt.formatting detektPlugins libs.detekt.libraries } diff --git a/owncloudTestUtil/build.gradle b/owncloudTestUtil/build.gradle index d3a3c184176..52a902d188f 100644 --- a/owncloudTestUtil/build.gradle +++ b/owncloudTestUtil/build.gradle @@ -35,5 +35,6 @@ dependencies { implementation libs.androidx.lifecycle.livedata.ktx // Detekt + detektPlugins libs.detekt.formatting detektPlugins libs.detekt.libraries } From 272e6c7188739a729bb1b73d4941c55678180280 Mon Sep 17 00:00:00 2001 From: Jesus Recio Date: Wed, 20 Nov 2024 13:42:50 +0100 Subject: [PATCH 06/74] feat: add new fields in 1.23.3 that were disabled: KDocReferencesNonPublicProperty and NestedScopeFunctions --- config/detekt/detekt.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.yml index afa5077a48a..a4e1763fa2e 100644 --- a/config/detekt/detekt.yml +++ b/config/detekt/detekt.yml @@ -62,6 +62,8 @@ comments: EndOfSentenceFormat: active: false endOfSentenceFormat: '([.?!][ \t\n\r\f<])|([.?!:]$)' + KDocReferencesNonPublicProperty: + active: false OutdatedDocumentation: active: false matchTypeParameters: true @@ -136,6 +138,10 @@ complexity: NestedBlockDepth: active: true threshold: 5 + NestedScopeFunctions: + active: false + threshold: 1 + functions: ['kotlin.apply', 'kotlin.run', 'kotlin.with', 'kotlin.let', 'kotlin.also'] ReplaceSafeCallChainWithRun: active: false StringLiteralDuplication: From d0033c6f70df5dfb62f83eb79511c3d0a8a85e90 Mon Sep 17 00:00:00 2001 From: Jesus Recio Date: Mon, 2 Dec 2024 09:14:17 +0100 Subject: [PATCH 07/74] fix: set the version line with correct format in toml file --- gradle/libs.versions.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index df12f8d39a2..16106794a60 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -22,7 +22,7 @@ androidxTestMonitor = "1.6.1" androidxTestUiAutomator ="2.2.0" androidxWork = "2.8.1" coil = "2.2.2" -detekt="1.23.3" +detekt = "1.23.3" dexopener = "2.0.5" disklrucache = "2.0.2" media3 ="1.1.1" From 93e5997d5c2282a92296d7f73fed327684dbc986 Mon Sep 17 00:00:00 2001 From: Jesus Recio Date: Wed, 4 Dec 2024 10:51:21 +0100 Subject: [PATCH 08/74] feat: detekt.yml file with latest rules changes for the first iteration --- config/detekt/detekt.yml | 167 ++++++++++++++++++++++++++------------- 1 file changed, 110 insertions(+), 57 deletions(-) diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.yml index a4e1763fa2e..cb449f47faf 100644 --- a/config/detekt/detekt.yml +++ b/config/detekt/detekt.yml @@ -86,8 +86,8 @@ comments: complexity: active: true CognitiveComplexMethod: - active: false - threshold: 15 + active: true + threshold: 20 ComplexCondition: active: true threshold: 5 @@ -573,29 +573,36 @@ performance: active: true ArrayPrimitive: active: true + CouldBeSequence: + active: false + threshold: 3 ForEachOnRange: active: true excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] SpreadOperator: - active: false + active: true excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + UnnecessaryPartOfBinaryExpression: + active: true UnnecessaryTemporaryInstantiation: active: true potential-bugs: active: true AvoidReferentialEquality: - active: false + active: true forbiddenTypePatterns: - 'kotlin.String' + CastNullableToNonNullableType: + active: true CastToNullableType: - active: false + active: true Deprecation: active: false DontDowncastCollectionTypes: - active: false + active: true DoubleMutabilityForCollection: - active: false + active: true mutableTypes: - 'kotlin.collections.MutableList' - 'kotlin.collections.MutableMap' @@ -606,17 +613,18 @@ potential-bugs: - 'java.util.LinkedHashMap' - 'java.util.HashMap' ElseCaseInsteadOfExhaustiveWhen: - active: false + active: true + ignoredSubjectTypes: [] EqualsAlwaysReturnsTrueOrFalse: active: true EqualsWithHashCodeExist: active: true ExitOutsideMain: - active: false + active: true ExplicitGarbageCollectionCall: active: true HasPlatformType: - active: false + active: true IgnoredReturnValue: active: false restrictToConfig: true @@ -629,8 +637,8 @@ potential-bugs: ImplicitDefaultLocale: active: true ImplicitUnitReturnType: - active: false - allowExplicitReturnType: true + active: true + allowExplicitReturnType: false InvalidRange: active: true IteratorHasNextCallsNextMethod: @@ -642,52 +650,59 @@ potential-bugs: excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] ignoreOnClassesPattern: '' MapGetWithNotNullAssertionOperator: - active: false + active: true MissingPackageDeclaration: - active: false - excludes: ['**/*.kts'] + active: true NullCheckOnMutableProperty: active: false NullableToStringCall: - active: false + active: true + PropertyUsedBeforeDeclaration: + active: true UnconditionalJumpStatementInLoop: - active: false + active: true + UnnecessaryNotNullCheck: + active: true UnnecessaryNotNullOperator: active: true UnnecessarySafeCall: active: true UnreachableCatchBlock: - active: false + active: true UnreachableCode: active: true UnsafeCallOnNullableType: - active: true - excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + active: false UnsafeCast: active: true UnusedUnaryOperator: - active: false + active: true UselessPostfixExpression: - active: false + active: true WrongEqualsTypeParameter: active: true style: active: true AlsoCouldBeApply: - active: false + active: true BracesOnIfStatements: - singleLine: 'never' - multiLine: 'always' + active: true + singleLine: 'consistent' + multiLine: 'consistent' BracesOnWhenStatements: - singleLine: 'necessary' + active: true + singleLine: 'consistent' multiLine: 'consistent' CanBeNonNullable: + active: true + CascadingCallWrapping: active: false + includeElvis: true ClassOrdering: - active: false + active: true CollapsibleIfStatements: - active: false + active: true DataClassContainsFunctions: active: false allowOperators: false @@ -697,17 +712,24 @@ style: DestructuringDeclarationWithTooManyEntries: active: false maxDestructuringEntries: 3 + DoubleNegativeLambda: + active: true + negativeFunctions: ['takeUnless', 'none'] + negativeFunctionNameParts: ['not', 'non'] EqualsNullCall: active: true EqualsOnSignatureLine: - active: false + active: true ExplicitCollectionElementAccessMethod: - active: false + active: true ExplicitItLambdaParameter: - active: false + active: true ExpressionBodySyntax: + active: true + includeLineWrapping: true + ForbiddenAnnotation: active: false - includeLineWrapping: false + annotations: ['java.lang.SuppressWarnings', 'java.lang.Deprecated', 'java.lang.annotation.Documented', 'java.lang.annotation.Target', 'java.lang.annotation.Retention', 'java.lang.annotation.Repeatable', 'java.lang.annotation.Inherited'] ForbiddenComment: active: true allowedPatterns: '' @@ -717,12 +739,13 @@ style: imports: [] forbiddenPatterns: '' ForbiddenMethodCall: + active: true + methods: ['kotlin.io.print', 'kotlin.io.println'] + ForbiddenSuppress: active: false - methods: - - 'kotlin.io.print' - - 'kotlin.io.println' + rules: [] ForbiddenVoid: - active: false + active: true ignoreOverridden: false ignoreUsageInGenerics: false FunctionOnlyReturningConstant: @@ -752,7 +775,7 @@ style: ignoreRanges: false ignoreExtensionFunctions: true MandatoryBracesLoops: - active: false + active: true MaxLineLength: active: true maxLineLength: 150 @@ -765,28 +788,34 @@ style: active: true MultilineLambdaItParameter: active: false + MultilineRawStringIndentation: + active: false + indentSize: 4 + trimmingMethods: ['trimIndent', 'trimMargin'] NestedClassesVisibility: active: true NewLineAtEndOfFile: active: true NoTabs: active: false + NullableBooleanCheck: + active: true ObjectLiteralToLambda: - active: false + active: true OptionalAbstractKeyword: active: true OptionalUnit: - active: false + active: true PreferToOverPairSyntax: - active: false + active: true ProtectedMemberInFinalClass: active: true RedundantExplicitType: - active: false + active: true RedundantHigherOrderMapUsage: - active: false + active: true RedundantVisibilityModifierRule: - active: false + active: true ReturnCount: active: true max: 2 @@ -799,13 +828,20 @@ style: SerialVersionUIDInSerializableClass: active: true SpacingBetweenPackageAndImports: + active: true + StringShouldBeRawString: active: false + maxEscapedCharacterCount: 2 + ignoredCharacters: [] ThrowsCount: active: false max: 2 excludeGuardClauses: false TrailingWhitespace: + active: true + TrimMultilineRawString: active: false + trimmingMethods: ['trimIndent', 'trimMargin'] UnderscoresInNumericLiterals: active: false acceptableLength: 4 @@ -816,56 +852,73 @@ style: active: false UnnecessaryApply: active: true - UnnecessaryFilter: + UnnecessaryBackticks: active: false + UnnecessaryBracesAroundTrailingLambda: + active: true + UnnecessaryFilter: + active: true UnnecessaryInheritance: active: true UnnecessaryInnerClass: - active: false + active: true UnnecessaryLet: - active: false + active: true UnnecessaryParentheses: active: false + allowForUnclearPrecedence: true UntilInsteadOfRangeTo: - active: false + active: true UnusedImports: - active: false + active: true + UnusedParameter: + active: true + allowedNames: 'ignored|expected' UnusedPrivateClass: active: true UnusedPrivateMember: active: true allowedNames: '(_|ignored|expected|serialVersionUID)' + UnusedPrivateProperty: + active: true + allowedNames: '_|ignored|expected|serialVersionUID' UseAnyOrNoneInsteadOfFind: - active: false + active: true UseArrayLiteralsInAnnotations: - active: false + active: true UseCheckNotNull: active: false UseCheckOrError: active: false UseDataClass: - active: false - allowVars: false + active: true + allowVars: true UseEmptyCounterpart: - active: false + active: true UseIfEmptyOrIfBlank: - active: false + active: true UseIfInsteadOfWhen: - active: false + active: true + ignoreWhenContainingVariableDeclaration: false UseIsNullOrEmpty: - active: false + active: true + UseLet: + active: true UseOrEmpty: - active: false + active: true UseRequire: active: false UseRequireNotNull: active: false + UseSumOfInsteadOfFlatMapSize: + active: false UselessCallOnNotNull: active: true UtilityClassWithPublicConstructor: active: true VarCouldBeVal: active: true + ignoreLateinitVar: false WildcardImport: active: true excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] From 8a73d2dac34e8a9f557d810bf30c38c1761a2a47 Mon Sep 17 00:00:00 2001 From: Jesus Recio Date: Wed, 4 Dec 2024 10:54:20 +0100 Subject: [PATCH 09/74] fix: remove base line, and use correct version of action for gradle --- .github/workflows/detekt.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/workflows/detekt.yml b/.github/workflows/detekt.yml index eb1d6b19ec9..efc259ff36b 100644 --- a/.github/workflows/detekt.yml +++ b/.github/workflows/detekt.yml @@ -47,9 +47,7 @@ jobs: # Configure Gradle for optimal use in GitHub Actions, including caching of downloaded dependencies. # See: https://github.com/gradle/actions/blob/main/setup-gradle/README.md - name: Setup Gradle - uses: gradle/actions/setup-gradle@af1da67850ed9a4cedd57bfd976089dd991e2582 # v4.0.0 - - name: Set base line - run: ./gradlew detektBaseline + uses: gradle/actions/setup-gradle@v4 - name: module owncloudApp run: ./gradlew detekt - name: module owncloudDomain From 97012eada3882704907a2454bc1880211eb257c7 Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Wed, 4 Dec 2024 08:26:52 +0100 Subject: [PATCH 10/74] style: make lines wrap automatically when they reach 150 characters in IDE --- .idea/codeStyles/Project.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml index 0a8ab42d20d..af4fbad11b6 100644 --- a/.idea/codeStyles/Project.xml +++ b/.idea/codeStyles/Project.xml @@ -2,6 +2,7 @@ - \ No newline at end of file + From 9da3c12e186864bf8fa6512974d63c1e7849ff00 Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Wed, 4 Dec 2024 14:41:10 +0100 Subject: [PATCH 11/74] style: wrap lines more than 150 characters in module `owncloudApp` --- .../datamodel/FileDataStorageManager.kt | 17 ++++++----- .../dependecyinjection/ViewModelModule.kt | 6 ++-- .../authentication/LoginActivity.kt | 6 ++-- .../conflicts/ConflictsResolveActivity.kt | 3 +- .../files/details/FileDetailsFragment.kt | 3 +- .../files/filelist/MainFileListFragment.kt | 30 ++++++++++++------- .../files/filelist/MainFileListViewModel.kt | 7 +++-- .../operations/FileOperationsViewModel.kt | 3 +- .../SettingsVideoUploadsFragment.kt | 3 +- .../security/SettingsSecurityFragment.kt | 3 +- .../sharing/PublicLinkPasswordUtils.kt | 3 +- .../sharing/ShareFragmentListener.kt | 2 +- .../shares/PublicShareDialogFragment.kt | 18 ++++++++--- .../android/providers/LogsProvider.kt | 3 +- .../ui/activity/FileDisplayActivity.kt | 6 ++-- .../ui/preview/PreviewAudioFragment.kt | 3 +- .../ui/preview/PreviewImageFragment.kt | 3 +- .../android/ui/preview/PreviewTextFragment.kt | 3 +- .../ui/preview/PreviewVideoActivity.kt | 12 +++++--- .../synchronization/SynchronizeFileUseCase.kt | 3 +- .../sharing/PublicLinkPasswordUtilsTest.kt | 3 +- 21 files changed, 92 insertions(+), 48 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt b/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt index 398586f1590..dca870423ec 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt @@ -52,14 +52,15 @@ class FileDataStorageManager( getFileByPathAndAccount(remotePath, account.name, spaceId) } - private fun getFileByPathAndAccount(remotePath: String, accountName: String, spaceId: String? = null): OCFile? = runBlocking(CoroutinesDispatcherProvider().io) { - val getFileByRemotePathUseCase: GetFileByRemotePathUseCase by inject() - - val result = withContext(CoroutineScope(CoroutinesDispatcherProvider().io).coroutineContext) { - getFileByRemotePathUseCase(GetFileByRemotePathUseCase.Params(accountName, remotePath, spaceId)) - }.getDataOrNull() - result - } + private fun getFileByPathAndAccount(remotePath: String, accountName: String, spaceId: String? = null): OCFile? = + runBlocking(CoroutinesDispatcherProvider().io) { + val getFileByRemotePathUseCase: GetFileByRemotePathUseCase by inject() + + val result = withContext(CoroutineScope(CoroutinesDispatcherProvider().io).coroutineContext) { + getFileByRemotePathUseCase(GetFileByRemotePathUseCase.Params(accountName, remotePath, spaceId)) + }.getDataOrNull() + result + } fun getRootPersonalFolder() = runBlocking(CoroutinesDispatcherProvider().io) { val getPersonalRootFolderForAccountUseCase: GetPersonalRootFolderForAccountUseCase by inject() diff --git a/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/ViewModelModule.kt b/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/ViewModelModule.kt index e1a566498d4..4d42fbb8c1f 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/ViewModelModule.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/ViewModelModule.kt @@ -91,12 +91,14 @@ val viewModelModule = module { ShareViewModel(filePath, accountName, get(), get(), get(), get(), get(), get(), get(), get(), get(), get()) } viewModel { (initialFolderToDisplay: OCFile, fileListOption: FileListOption) -> - MainFileListViewModel(get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), initialFolderToDisplay, fileListOption) + MainFileListViewModel(get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), + initialFolderToDisplay, fileListOption) } viewModel { (ocFile: OCFile) -> ConflictsResolveViewModel(get(), get(), get(), get(), get(), ocFile) } viewModel { AuthenticationViewModel(get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get()) } viewModel { MigrationViewModel(MainApp.dataFolder, get(), get(), get(), get(), get(), get(), get()) } - viewModel { TransfersViewModel(get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get()) } + viewModel { TransfersViewModel(get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), + get()) } viewModel { ReceiveExternalFilesViewModel(get(), get(), get(), get()) } viewModel { (accountName: String, showPersonalSpace: Boolean) -> SpacesListViewModel(get(), get(), get(), get(), get(), get(), get(), accountName, showPersonalSpace) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/LoginActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/LoginActivity.kt index 4720c437baa..81889dac1c7 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/LoginActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/LoginActivity.kt @@ -548,7 +548,8 @@ class LoginActivity : AppCompatActivity(), SslUntrustedCertDialog.OnSslUntrusted codeChallenge = authenticationViewModel.codeChallenge, state = authenticationViewModel.oidcState, username = username, - sendLoginHintAndUser = mdmProvider.getBrandingBoolean(mdmKey = CONFIGURATION_SEND_LOGIN_HINT_AND_USER, booleanKey = R.bool.send_login_hint_and_user), + sendLoginHintAndUser = mdmProvider.getBrandingBoolean(mdmKey = CONFIGURATION_SEND_LOGIN_HINT_AND_USER, + booleanKey = R.bool.send_login_hint_and_user), ) try { @@ -585,7 +586,8 @@ class LoginActivity : AppCompatActivity(), SslUntrustedCertDialog.OnSslUntrusted val authorizationError = intent.data?.getQueryParameter("error") val authorizationErrorDescription = intent.data?.getQueryParameter("error_description") - Timber.e("OAuth request to get authorization code failed. Error: [$authorizationError]. Error description: [$authorizationErrorDescription]") + Timber.e("OAuth request to get authorization code failed. Error: [$authorizationError]." + + " Error description: [$authorizationErrorDescription]") val authorizationException = if (authorizationError == "access_denied") UnauthorizedException() else Throwable() updateOAuthStatusIconAndText(authorizationException) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/conflicts/ConflictsResolveActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/conflicts/ConflictsResolveActivity.kt index 67380a633be..af746e819bf 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/conflicts/ConflictsResolveActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/conflicts/ConflictsResolveActivity.kt @@ -50,7 +50,8 @@ class ConflictsResolveActivity : AppCompatActivity(), ConflictsResolveDialogFrag lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { conflictsResolveViewModel.currentFile.collectLatest { updatedOCFile -> - Timber.d("File ${updatedOCFile?.remotePath} from ${updatedOCFile?.owner} needs to fix a conflict with etag in conflict ${updatedOCFile?.etagInConflict}") + Timber.d("File ${updatedOCFile?.remotePath} from ${updatedOCFile?.owner} needs to fix a conflict with etag" + + " in conflict ${updatedOCFile?.etagInConflict}") // Finish if the file does not exists or if the file is not in conflict anymore. updatedOCFile?.etagInConflict ?: finish() } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/details/FileDetailsFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/details/FileDetailsFragment.kt index f1973a9f407..3af7d5892c2 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/details/FileDetailsFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/details/FileDetailsFragment.kt @@ -149,7 +149,8 @@ class FileDetailsFragment : FileFragment() { // Mimetypes not supported via open in web, send 500 if (uiResult.error is InstanceNotConfiguredException) { val message = - getString(R.string.open_in_web_error_generic) + " " + getString(R.string.error_reason) + " " + getString(R.string.open_in_web_error_not_supported) + getString(R.string.open_in_web_error_generic) + " " + getString(R.string.error_reason) + + " " + getString(R.string.open_in_web_error_not_supported) this.showMessageInSnackbar(message, Snackbar.LENGTH_LONG) } else if (uiResult.error is TooEarlyException) { this.showMessageInSnackbar(getString(R.string.open_in_web_error_too_early), Snackbar.LENGTH_LONG) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt index 8bc5ffea26e..097480b0133 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt @@ -375,7 +375,8 @@ class MainFileListFragment : Fragment(), // Mimetypes not supported via open in web, send 500 if (uiResult.error is InstanceNotConfiguredException) { val message = - getString(R.string.open_in_web_error_generic) + " " + getString(R.string.error_reason) + " " + getString(R.string.open_in_web_error_not_supported) + getString(R.string.open_in_web_error_generic) + " " + getString(R.string.error_reason) + + " " + getString(R.string.open_in_web_error_not_supported) this.showMessageInSnackbar(message, Snackbar.LENGTH_LONG) } else if (uiResult.error is TooEarlyException) { this.showMessageInSnackbar(getString(R.string.open_in_web_error_too_early), Snackbar.LENGTH_LONG) @@ -835,7 +836,8 @@ class MainFileListFragment : Fragment(), * @param newFileListOption new file list option to enable. */ private fun showOrHideFab(newFileListOption: FileListOption, currentFolder: OCFile) { - if (!newFileListOption.isAllFiles() || isPickingAFolder() || (!currentFolder.hasAddFilePermission && !currentFolder.hasAddSubdirectoriesPermission)) { + if (!newFileListOption.isAllFiles() || isPickingAFolder() || + (!currentFolder.hasAddFilePermission && !currentFolder.hasAddSubdirectoriesPermission)) { toggleFabVisibility(false) } else { toggleFabVisibility(true) @@ -881,7 +883,8 @@ class MainFileListFragment : Fragment(), fabNewfile.isFocusable = isFabExpanded() fabNewshortcut.isFocusable = isFabExpanded() if (fabMain.isExpanded) { - binding.fabMain.findViewById(com.getbase.floatingactionbutton.R.id.fab_expand_menu_button).contentDescription = getString(R.string.content_description_add_new_content_expanded) + binding.fabMain.findViewById(com.getbase.floatingactionbutton.R.id.fab_expand_menu_button) + .contentDescription = getString(R.string.content_description_add_new_content_expanded) } else { setFabMainContentDescription() } @@ -1451,16 +1454,23 @@ class MainFileListFragment : Fragment(), if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val roleAccessibilityDescription = getString(R.string.button_role_accessibility) menu?.apply { - findItem(R.id.file_action_select_all)?.contentDescription = "${getString(R.string.actionbar_select_all)} $roleAccessibilityDescription" - findItem(R.id.action_select_inverse)?.contentDescription = "${getString(R.string.actionbar_select_inverse)} $roleAccessibilityDescription" - findItem(R.id.action_open_file_with)?.contentDescription = "${getString(R.string.actionbar_open_with)} $roleAccessibilityDescription" + findItem(R.id.file_action_select_all)?.contentDescription = + "${getString(R.string.actionbar_select_all)} $roleAccessibilityDescription" + findItem(R.id.action_select_inverse)?.contentDescription = + "${getString(R.string.actionbar_select_inverse)} $roleAccessibilityDescription" + findItem(R.id.action_open_file_with)?.contentDescription = + "${getString(R.string.actionbar_open_with)} $roleAccessibilityDescription" findItem(R.id.action_rename_file)?.contentDescription = "${getString(R.string.common_rename)} $roleAccessibilityDescription" findItem(R.id.action_move)?.contentDescription = "${getString(R.string.actionbar_move)} $roleAccessibilityDescription" findItem(R.id.action_copy)?.contentDescription = "${getString(R.string.copy)} $roleAccessibilityDescription" - findItem(R.id.action_send_file)?.contentDescription = "${getString(R.string.actionbar_send_file)} $roleAccessibilityDescription" - findItem(R.id.action_set_available_offline)?.contentDescription = "${getString(R.string.set_available_offline)} $roleAccessibilityDescription" - findItem(R.id.action_unset_available_offline)?.contentDescription = "${getString(R.string.unset_available_offline)} $roleAccessibilityDescription" - findItem(R.id.action_see_details)?.contentDescription = "${getString(R.string.actionbar_see_details)} $roleAccessibilityDescription" + findItem(R.id.action_send_file)?.contentDescription = + "${getString(R.string.actionbar_send_file)} $roleAccessibilityDescription" + findItem(R.id.action_set_available_offline)?.contentDescription = + "${getString(R.string.set_available_offline)} $roleAccessibilityDescription" + findItem(R.id.action_unset_available_offline)?.contentDescription = + "${getString(R.string.unset_available_offline)} $roleAccessibilityDescription" + findItem(R.id.action_see_details)?.contentDescription = + "${getString(R.string.actionbar_see_details)} $roleAccessibilityDescription" findItem(R.id.action_remove_file)?.contentDescription = "${getString(R.string.common_remove)} $roleAccessibilityDescription" } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListViewModel.kt index 62246558373..37bdfd2ba31 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListViewModel.kt @@ -226,9 +226,10 @@ class MainFileListViewModel( FileListOption.SHARED_BY_LINK -> { val fileById = fileByIdResult.getDataOrNull() - parentDir = if (fileById != null && (!fileById.sharedByLink || fileById.sharedWithSharee != true) && fileById.spaceId == null) { - getFileByRemotePathUseCase(GetFileByRemotePathUseCase.Params(fileById.owner, ROOT_PATH)).getDataOrNull() - } else fileById + parentDir = + if (fileById != null && (!fileById.sharedByLink || fileById.sharedWithSharee != true) && fileById.spaceId == null) { + getFileByRemotePathUseCase(GetFileByRemotePathUseCase.Params(fileById.owner, ROOT_PATH)).getDataOrNull() + } else fileById } FileListOption.AV_OFFLINE -> { diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/operations/FileOperationsViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/operations/FileOperationsViewModel.kt index 7a0781c5a19..7b894b52850 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/operations/FileOperationsViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/operations/FileOperationsViewModel.kt @@ -275,7 +275,8 @@ class FileOperationsViewModel( remotePath = fileOperation.folderToRefresh.remotePath, accountName = fileOperation.folderToRefresh.owner, spaceId = fileOperation.folderToRefresh.spaceId, - syncMode = if (fileOperation.shouldSyncContents) SynchronizeFolderUseCase.SyncFolderMode.SYNC_CONTENTS else SynchronizeFolderUseCase.SyncFolderMode.REFRESH_FOLDER + syncMode = if (fileOperation.shouldSyncContents) SynchronizeFolderUseCase.SyncFolderMode.SYNC_CONTENTS + else SynchronizeFolderUseCase.SyncFolderMode.REFRESH_FOLDER ) ) } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/automaticuploads/SettingsVideoUploadsFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/automaticuploads/SettingsVideoUploadsFragment.kt index 9d1f39b2b45..a2e4ceab694 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/automaticuploads/SettingsVideoUploadsFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/automaticuploads/SettingsVideoUploadsFragment.kt @@ -103,7 +103,8 @@ class SettingsVideoUploadsFragment : PreferenceFragmentCompat() { prefVideoUploadsSourcePath = findPreference(PREF__CAMERA_VIDEO_UPLOADS_SOURCE) prefVideoUploadsLastSync = findPreference(PreferenceManager.PREF__CAMERA_VIDEO_UPLOADS_LAST_SYNC) prefVideoUploadsBehaviour = findPreference(PREF__CAMERA_VIDEO_UPLOADS_BEHAVIOUR)?.apply { - entries = listOf(getString(R.string.pref_behaviour_entries_keep_file), getString(R.string.pref_behaviour_entries_remove_original_file)).toTypedArray() + entries = listOf(getString(R.string.pref_behaviour_entries_keep_file), + getString(R.string.pref_behaviour_entries_remove_original_file)).toTypedArray() entryValues = listOf(UploadBehavior.COPY.name, UploadBehavior.MOVE.name).toTypedArray() } prefVideoUploadsAccount = findPreference(PREF__CAMERA_VIDEO_UPLOADS_ACCOUNT_NAME) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/security/SettingsSecurityFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/security/SettingsSecurityFragment.kt index 0e3cbab8d17..a883999ac51 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/security/SettingsSecurityFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/security/SettingsSecurityFragment.kt @@ -172,7 +172,8 @@ class SettingsSecurityFragment : PreferenceFragmentCompat() { if (!BiometricManager.isHardwareDetected()) { // Biometric not supported screenSecurity?.removePreferenceFromScreen(prefBiometric) } else { - if (prefPasscode?.isChecked == false && prefPattern?.isChecked == false) { // Disable biometric lock if Passcode or Pattern locks are disabled + // Disable biometric lock if Passcode or Pattern locks are disabled + if (prefPasscode?.isChecked == false && prefPattern?.isChecked == false) { disableBiometric() } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtils.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtils.kt index c322c5d5a9c..b64730ba364 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtils.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtils.kt @@ -25,7 +25,8 @@ import java.security.SecureRandom private val charsetLowercase = ('a'..'z').toList() private val charsetUppercase = ('A'..'Z').toList() private val charsetDigits = ('0'..'9').toList() -private val charsetSpecial = listOf('!', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~') +private val charsetSpecial = listOf('!', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', + '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~') fun generatePassword( minChars: Int?, diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareFragmentListener.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareFragmentListener.kt index 7f52b90220e..ee921df5f10 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareFragmentListener.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareFragmentListener.kt @@ -34,7 +34,7 @@ import com.owncloud.android.domain.sharing.shares.model.OCShare * contained in that activity. * * - * See the Android Training lesson [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html) for more information. + * See the Android docs [Communicating with fragments](https://developer.android.com/guide/fragments/communicate) for more information. */ interface ShareFragmentListener { fun copyOrSendPrivateLink(file: OCFile) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/shares/PublicShareDialogFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/shares/PublicShareDialogFragment.kt index 5ee96c8656d..daffcdb5573 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/shares/PublicShareDialogFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/shares/PublicShareDialogFragment.kt @@ -518,7 +518,8 @@ class PublicShareDialogFragment : DialogFragment() { val x = event.x.toInt() val y = event.y.toInt() val bounds = rightDrawable.bounds - if (x >= view.right - bounds.width() - fuzz && x <= view.right - view.paddingRight + fuzz && y >= view.paddingTop - fuzz && y <= view.height - view.paddingBottom + fuzz) { + if (x >= view.right - bounds.width() - fuzz && x <= view.right - view.paddingRight + fuzz && y >= view.paddingTop - fuzz && + y <= view.height - view.paddingBottom + fuzz) { return onDrawableTouch(event) } @@ -836,7 +837,9 @@ class PublicShareDialogFragment : DialogFragment() { // - Upload only is supported by the server version // - Upload only capability is set // - Allow editing capability is set - if (!(isSharedFolder && serverVersion?.isPublicSharingWriteOnlySupported == true && capabilities?.filesSharingPublicSupportsUploadOnly == CapabilityBooleanType.TRUE && capabilities?.filesSharingPublicUpload == CapabilityBooleanType.TRUE)) { + if (!(isSharedFolder && serverVersion?.isPublicSharingWriteOnlySupported == true && + capabilities?.filesSharingPublicSupportsUploadOnly == CapabilityBooleanType.TRUE && + capabilities?.filesSharingPublicUpload == CapabilityBooleanType.TRUE)) { binding.shareViaLinkEditPermissionGroup.isVisible = false } @@ -867,7 +870,12 @@ class PublicShareDialogFragment : DialogFragment() { } // Set password label when opening the dialog - if (binding.shareViaLinkEditPermissionReadOnly.isChecked && capabilities?.filesSharingPublicPasswordEnforcedReadOnly == CapabilityBooleanType.TRUE || binding.shareViaLinkEditPermissionReadAndWrite.isChecked && capabilities?.filesSharingPublicPasswordEnforcedReadWrite == CapabilityBooleanType.TRUE || binding.shareViaLinkEditPermissionUploadFiles.isChecked && capabilities?.filesSharingPublicPasswordEnforcedUploadOnly == CapabilityBooleanType.TRUE) { + if (binding.shareViaLinkEditPermissionReadOnly.isChecked && + capabilities?.filesSharingPublicPasswordEnforcedReadOnly == CapabilityBooleanType.TRUE || + binding.shareViaLinkEditPermissionReadAndWrite.isChecked && + capabilities?.filesSharingPublicPasswordEnforcedReadWrite == CapabilityBooleanType.TRUE || + binding.shareViaLinkEditPermissionUploadFiles.isChecked && + capabilities?.filesSharingPublicPasswordEnforcedUploadOnly == CapabilityBooleanType.TRUE) { setPasswordEnforced() } @@ -898,7 +906,9 @@ class PublicShareDialogFragment : DialogFragment() { // When there's no password enforced for capability val hasPasswordEnforcedFor = - capabilities?.filesSharingPublicPasswordEnforcedReadOnly == CapabilityBooleanType.TRUE || capabilities?.filesSharingPublicPasswordEnforcedReadWrite == CapabilityBooleanType.TRUE || capabilities?.filesSharingPublicPasswordEnforcedUploadOnly == CapabilityBooleanType.TRUE + capabilities?.filesSharingPublicPasswordEnforcedReadOnly == CapabilityBooleanType.TRUE || + capabilities?.filesSharingPublicPasswordEnforcedReadWrite == CapabilityBooleanType.TRUE || + capabilities?.filesSharingPublicPasswordEnforcedUploadOnly == CapabilityBooleanType.TRUE // hide password switch if password is enforced to prevent it is removed if (!hasPasswordEnforcedFor && capabilities?.filesSharingPublicPasswordEnforced == CapabilityBooleanType.TRUE) { diff --git a/owncloudApp/src/main/java/com/owncloud/android/providers/LogsProvider.kt b/owncloudApp/src/main/java/com/owncloud/android/providers/LogsProvider.kt index 3a8818ebaa1..25a21bb84e8 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/providers/LogsProvider.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/providers/LogsProvider.kt @@ -58,7 +58,8 @@ class LogsProvider( private fun initHttpLogs() { val httpLogsEnabled: Boolean = sharedPreferencesProvider.getBoolean(PREFERENCE_LOG_HTTP, false) LogInterceptor.httpLogsEnabled = httpLogsEnabled - val redactAuthHeader = mdmProvider.getBrandingBoolean(mdmKey = CONFIGURATION_REDACT_AUTH_HEADER_LOGS, booleanKey = R.bool.redact_auth_header_logs) + val redactAuthHeader = + mdmProvider.getBrandingBoolean(mdmKey = CONFIGURATION_REDACT_AUTH_HEADER_LOGS, booleanKey = R.bool.redact_auth_header_logs) LogInterceptor.redactAuthHeader = redactAuthHeader } diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt index 6a817e2d54d..f25f33b00b6 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt @@ -751,7 +751,8 @@ class FileDisplayActivity : FileActivity(), // If secondFragment was shown, we need to navigate to the parent of the displayed file // Need a cleanup val folderIdToDisplay = - if (fileListOption == FileListOption.AV_OFFLINE) storageManager.getRootPersonalFolder()!!.id!! else secondFragment!!.file!!.parentId!! + if (fileListOption == FileListOption.AV_OFFLINE) storageManager.getRootPersonalFolder()!!.id!! + else secondFragment!!.file!!.parentId!! mainFileListFragment?.navigateToFolderId(folderIdToDisplay) cleanSecondFragment() updateToolbar(mainFileListFragment?.getCurrentFile()) @@ -965,7 +966,8 @@ class FileDisplayActivity : FileActivity(), private fun updateToolbar(chosenFileFromParam: OCFile?, space: OCSpace? = null) { val chosenFile = chosenFileFromParam ?: file // If no file is passed, current file decides - // If we come from a preview activity (image or video), not updating toolbar when initializing this activity or it will show the root folder one + // If we come from a preview activity (image or video), not updating toolbar when initializing this activity + // or it will show the root folder one if (intent.action == ACTION_DETAILS && chosenFile?.remotePath == OCFile.ROOT_PATH && secondFragment is FileDetailsFragment) return if (chosenFile == null || (chosenFile.remotePath == OCFile.ROOT_PATH && (space == null || diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewAudioFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewAudioFragment.kt index 2087cfffb49..a02d50d26d0 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewAudioFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewAudioFragment.kt @@ -259,7 +259,8 @@ class PreviewAudioFragment : FileFragment() { private fun setRolesAccessibilityToMenuItems(menu: Menu) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - menu.findItem(R.id.action_see_details)?.contentDescription = "${getString(R.string.actionbar_see_details)} ${getString(R.string.button_role_accessibility)}" + menu.findItem(R.id.action_see_details)?.contentDescription = + "${getString(R.string.actionbar_see_details)} ${getString(R.string.button_role_accessibility)}" } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageFragment.kt index 1e1e2bdd7b8..a3e0bdd3dfc 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageFragment.kt @@ -206,7 +206,8 @@ class PreviewImageFragment : FileFragment() { private fun setRolesAccessibilityToMenuItems(menu: Menu) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - menu.findItem(R.id.action_see_details)?.contentDescription = "${getString(R.string.actionbar_see_details)} ${getString(R.string.button_role_accessibility)}" + menu.findItem(R.id.action_see_details)?.contentDescription = + "${getString(R.string.actionbar_see_details)} ${getString(R.string.button_role_accessibility)}" } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewTextFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewTextFragment.kt index 18421282bc6..b56c0ea2bf3 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewTextFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewTextFragment.kt @@ -247,7 +247,8 @@ class PreviewTextFragment : FileFragment() { private fun setRolesAccessibilityToMenuItems(menu: Menu) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - menu.findItem(R.id.action_see_details)?.contentDescription = "${getString(R.string.actionbar_see_details)} ${getString(R.string.button_role_accessibility)}" + menu.findItem(R.id.action_see_details)?.contentDescription = + "${getString(R.string.actionbar_see_details)} ${getString(R.string.button_role_accessibility)}" } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewVideoActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewVideoActivity.kt index 0cd8482b328..072ef4d7955 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewVideoActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewVideoActivity.kt @@ -354,11 +354,15 @@ class PreviewVideoActivity : FileActivity(), Player.Listener, OnPrepareVideoPlay if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val roleAccessibilityDescription = getString(R.string.button_role_accessibility) menu.apply { - menu.findItem(R.id.action_open_file_with)?.contentDescription = "${getString(R.string.actionbar_open_with)} $roleAccessibilityDescription" + menu.findItem(R.id.action_open_file_with)?.contentDescription = + "${getString(R.string.actionbar_open_with)} $roleAccessibilityDescription" menu.findItem(R.id.action_send_file)?.contentDescription = "${getString(R.string.actionbar_send_file)} $roleAccessibilityDescription" - menu.findItem(R.id.action_set_available_offline)?.contentDescription = "${getString(R.string.set_available_offline)} $roleAccessibilityDescription" - menu.findItem(R.id.action_unset_available_offline)?.contentDescription = "${getString(R.string.unset_available_offline)} $roleAccessibilityDescription" - menu.findItem(R.id.action_see_details)?.contentDescription = "${getString(R.string.actionbar_see_details)} $roleAccessibilityDescription" + menu.findItem(R.id.action_set_available_offline)?.contentDescription = + "${getString(R.string.set_available_offline)} $roleAccessibilityDescription" + menu.findItem(R.id.action_unset_available_offline)?.contentDescription = + "${getString(R.string.unset_available_offline)} $roleAccessibilityDescription" + menu.findItem(R.id.action_see_details)?.contentDescription = + "${getString(R.string.actionbar_see_details)} $roleAccessibilityDescription" menu.findItem(R.id.action_remove_file)?.contentDescription = "${getString(R.string.common_remove)} $roleAccessibilityDescription" } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/usecases/synchronization/SynchronizeFileUseCase.kt b/owncloudApp/src/main/java/com/owncloud/android/usecases/synchronization/SynchronizeFileUseCase.kt index b87f24c3590..543930d9b01 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/usecases/synchronization/SynchronizeFileUseCase.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/usecases/synchronization/SynchronizeFileUseCase.kt @@ -73,7 +73,8 @@ class SynchronizeFileUseCase( // 3. Check if file has changed locally val changedLocally = fileToSynchronize.localModificationTimestamp > fileToSynchronize.lastSyncDateForData!! - Timber.i("Local file modification timestamp :${fileToSynchronize.localModificationTimestamp} and last sync date for data :${fileToSynchronize.lastSyncDateForData}") + Timber.i("Local file modification timestamp :${fileToSynchronize.localModificationTimestamp}" + + " and last sync date for data :${fileToSynchronize.lastSyncDateForData}") Timber.i("So it has changed locally: $changedLocally") // 4. Check if file has changed remotely diff --git a/owncloudApp/src/test/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtilsTest.kt b/owncloudApp/src/test/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtilsTest.kt index f81abe73df5..c4a2471b72f 100644 --- a/owncloudApp/src/test/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtilsTest.kt +++ b/owncloudApp/src/test/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtilsTest.kt @@ -28,7 +28,8 @@ class PublicLinkPasswordUtilsTest { private val charsetLowercase = ('a'..'z').toList() private val charsetUppercase = ('A'..'Z').toList() private val charsetDigits = ('0'..'9').toList() - private val charsetSpecial = listOf('!', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~') + private val charsetSpecial = listOf('!', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', + '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~') private val minCharacters = 10 private val maxCharacters = 100 From a6ee78e5b67a1d6afde1de4e3fefeab814254b7d Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Wed, 4 Dec 2024 17:05:24 +0100 Subject: [PATCH 12/74] style: wrap lines more than 150 characters in module `owncloudComLibrary` --- ...reateRemoteFileWithAppProviderOperation.kt | 3 ++- .../status/responses/CapabilityResponse.kt | 24 ++++++++++++------- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/appregistry/CreateRemoteFileWithAppProviderOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/appregistry/CreateRemoteFileWithAppProviderOperation.kt index e4f85a32fa1..9428b5c8c3e 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/appregistry/CreateRemoteFileWithAppProviderOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/appregistry/CreateRemoteFileWithAppProviderOperation.kt @@ -61,7 +61,8 @@ class CreateRemoteFileWithAppProviderOperation( } val status = client.executeHttpMethod(postMethod) - Timber.d("Create file $filename with app provider in folder with ID $parentContainerId - $status${if (!isSuccess(status)) "(FAIL)" else ""}") + Timber.d("Create file $filename with app provider in folder with ID $parentContainerId" + + " - $status${if (!isSuccess(status)) "(FAIL)" else ""}") if (isSuccess(status)) RemoteOperationResult(ResultCode.OK).apply { val moshi = Moshi.Builder().build() diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/responses/CapabilityResponse.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/responses/CapabilityResponse.kt index cecd5f19eb3..2f3a4ef6cb8 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/responses/CapabilityResponse.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/responses/CapabilityResponse.kt @@ -50,10 +50,14 @@ data class CapabilityResponse( filesSharingApiEnabled = CapabilityBooleanType.fromBooleanValue(capabilities?.fileSharingCapabilities?.fileSharingApiEnabled), filesSharingResharing = CapabilityBooleanType.fromBooleanValue(capabilities?.fileSharingCapabilities?.fileSharingReSharing), filesSharingPublicEnabled = CapabilityBooleanType.fromBooleanValue(capabilities?.fileSharingCapabilities?.fileSharingPublic?.enabled), - filesSharingPublicUpload = CapabilityBooleanType.fromBooleanValue(capabilities?.fileSharingCapabilities?.fileSharingPublic?.fileSharingPublicUpload), - filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.fromBooleanValue(capabilities?.fileSharingCapabilities?.fileSharingPublic?.fileSharingPublicUploadOnly), - filesSharingPublicMultiple = CapabilityBooleanType.fromBooleanValue(capabilities?.fileSharingCapabilities?.fileSharingPublic?.fileSharingPublicMultiple), - filesSharingPublicPasswordEnforced = CapabilityBooleanType.fromBooleanValue(capabilities?.fileSharingCapabilities?.fileSharingPublic?.fileSharingPublicPassword?.enforced), + filesSharingPublicUpload = + CapabilityBooleanType.fromBooleanValue(capabilities?.fileSharingCapabilities?.fileSharingPublic?.fileSharingPublicUpload), + filesSharingPublicSupportsUploadOnly = + CapabilityBooleanType.fromBooleanValue(capabilities?.fileSharingCapabilities?.fileSharingPublic?.fileSharingPublicUploadOnly), + filesSharingPublicMultiple = + CapabilityBooleanType.fromBooleanValue(capabilities?.fileSharingCapabilities?.fileSharingPublic?.fileSharingPublicMultiple), + filesSharingPublicPasswordEnforced = + CapabilityBooleanType.fromBooleanValue(capabilities?.fileSharingCapabilities?.fileSharingPublic?.fileSharingPublicPassword?.enforced), filesSharingPublicPasswordEnforcedReadOnly = CapabilityBooleanType.fromBooleanValue( capabilities?.fileSharingCapabilities?.fileSharingPublic?.fileSharingPublicPassword?.enforcedFor?.enforcedReadOnly ), @@ -63,7 +67,8 @@ data class CapabilityResponse( filesSharingPublicPasswordEnforcedUploadOnly = CapabilityBooleanType.fromBooleanValue( capabilities?.fileSharingCapabilities?.fileSharingPublic?.fileSharingPublicPassword?.enforcedFor?.enforcedUploadOnly ), - filesSharingPublicExpireDateEnabled = CapabilityBooleanType.fromBooleanValue(capabilities?.fileSharingCapabilities?.fileSharingPublic?.fileSharingPublicExpireDate?.enabled), + filesSharingPublicExpireDateEnabled = + CapabilityBooleanType.fromBooleanValue(capabilities?.fileSharingCapabilities?.fileSharingPublic?.fileSharingPublicExpireDate?.enabled), filesSharingPublicExpireDateDays = capabilities?.fileSharingCapabilities?.fileSharingPublic?.fileSharingPublicExpireDate?.days ?: 0, filesSharingPublicExpireDateEnforced = CapabilityBooleanType.fromBooleanValue( @@ -75,9 +80,12 @@ data class CapabilityResponse( filesPrivateLinks = capabilities?.fileCapabilities?.privateLinks?.let { CapabilityBooleanType.fromBooleanValue(it) } ?: CapabilityBooleanType.UNKNOWN, filesAppProviders = capabilities?.fileCapabilities?.appProviders?.map { it.toAppProviders() }, - filesSharingFederationIncoming = CapabilityBooleanType.fromBooleanValue(capabilities?.fileSharingCapabilities?.fileSharingFederation?.incoming), - filesSharingFederationOutgoing = CapabilityBooleanType.fromBooleanValue(capabilities?.fileSharingCapabilities?.fileSharingFederation?.outgoing), - filesSharingUserProfilePicture = CapabilityBooleanType.fromBooleanValue(capabilities?.fileSharingCapabilities?.fileSharingUser?.profilePicture), + filesSharingFederationIncoming = + CapabilityBooleanType.fromBooleanValue(capabilities?.fileSharingCapabilities?.fileSharingFederation?.incoming), + filesSharingFederationOutgoing = + CapabilityBooleanType.fromBooleanValue(capabilities?.fileSharingCapabilities?.fileSharingFederation?.outgoing), + filesSharingUserProfilePicture = + CapabilityBooleanType.fromBooleanValue(capabilities?.fileSharingCapabilities?.fileSharingUser?.profilePicture), spaces = capabilities?.spacesCapabilities?.toSpaces(), passwordPolicy = capabilities?.passwordPolicyCapabilities?.toPasswordPolicy(), ) From 6ff4964828fafd56fdf95f5099ecaeff49e65fb9 Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Tue, 10 Dec 2024 11:06:35 +0100 Subject: [PATCH 13/74] style: wrap lines more than 150 characters in module `owncloudData` --- .../data/files/repository/OCFileRepository.kt | 6 +- .../android/data/migrations/Migration_28.kt | 26 ++++++++- .../android/data/migrations/Migration_29.kt | 33 ++++++++++- .../android/data/migrations/Migration_30.kt | 28 ++++++++- .../android/data/migrations/Migration_32.kt | 3 +- .../android/data/migrations/Migration_33.kt | 6 +- .../android/data/migrations/Migration_34.kt | 4 +- .../android/data/migrations/Migration_38.kt | 12 +++- .../OCLocalFileDataSourceTest.kt | 19 ++++-- .../files/repository/OCFileRepositoryTest.kt | 58 ++++++++++++++++--- .../OCLocalTransferDataSourceTest.kt | 7 ++- 11 files changed, 173 insertions(+), 29 deletions(-) diff --git a/owncloudData/src/main/java/com/owncloud/android/data/files/repository/OCFileRepository.kt b/owncloudData/src/main/java/com/owncloud/android/data/files/repository/OCFileRepository.kt index 0ada7453f64..29421665a4f 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/files/repository/OCFileRepository.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/files/repository/OCFileRepository.kt @@ -396,7 +396,8 @@ class OCFileRepository( // DO NOT update etag till contents are synced. etag = localChildToSync.etag needsToUpdateThumbnail = - (!remoteChild.isFolder && remoteChild.modificationTimestamp != localChildToSync.modificationTimestamp) || localChildToSync.needsToUpdateThumbnail + (!remoteChild.isFolder && remoteChild.modificationTimestamp != localChildToSync.modificationTimestamp) || + localChildToSync.needsToUpdateThumbnail // Probably not needed, if the child was already in the database, the av offline status should be also there if (remoteFolder.isAvailableOffline) { availableOfflineStatus = AVAILABLE_OFFLINE_PARENT @@ -584,7 +585,8 @@ class OCFileRepository( // 1. Remove folder content recursively folderContent.forEach { file -> - if (!(onlyFromLocalStorage && file.isAvailableOffline)) { // The condition will not be met when onlyFromLocalStorage is true and the file is of type available offline + // The condition will not be met when onlyFromLocalStorage is true and the file is of type available offline + if (!(onlyFromLocalStorage && file.isAvailableOffline)) { if (file.isFolder) { deleteLocalFolderRecursively(ocFile = file, onlyFromLocalStorage = onlyFromLocalStorage) } else { diff --git a/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_28.kt b/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_28.kt index f69a271d7fe..6f0bb2c0143 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_28.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_28.kt @@ -26,11 +26,33 @@ val MIGRATION_27_28 = object : Migration(27, 28) { override fun migrate(database: SupportSQLiteDatabase) { database.run { execSQL( - "CREATE TABLE IF NOT EXISTS `${ProviderTableMeta.CAPABILITIES_TABLE_NAME}2` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `account` TEXT, `version_mayor` INTEGER NOT NULL, `version_minor` INTEGER NOT NULL, `version_micro` INTEGER NOT NULL, `version_string` TEXT, `version_edition` TEXT, `core_pollinterval` INTEGER NOT NULL, `sharing_api_enabled` INTEGER NOT NULL DEFAULT -1, `search_min_length` INTEGER, `sharing_public_enabled` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced_read_only` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced_read_write` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced_public_only` INTEGER NOT NULL DEFAULT -1, `sharing_public_expire_date_enabled` INTEGER NOT NULL DEFAULT -1, `sharing_public_expire_date_days` INTEGER NOT NULL, `sharing_public_expire_date_enforced` INTEGER NOT NULL DEFAULT -1, `sharing_public_send_mail` INTEGER NOT NULL DEFAULT -1, `sharing_public_upload` INTEGER NOT NULL DEFAULT -1, `sharing_public_multiple` INTEGER NOT NULL DEFAULT -1, `supports_upload_only` INTEGER NOT NULL DEFAULT -1, `sharing_user_send_mail` INTEGER NOT NULL DEFAULT -1, `sharing_resharing` INTEGER NOT NULL DEFAULT -1, `sharing_federation_outgoing` INTEGER NOT NULL DEFAULT -1, `sharing_federation_incoming` INTEGER NOT NULL DEFAULT -1, `files_bigfilechunking` INTEGER NOT NULL DEFAULT -1, `files_undelete` INTEGER NOT NULL DEFAULT -1, `files_versioning` INTEGER NOT NULL DEFAULT -1)" + "CREATE TABLE IF NOT EXISTS `${ProviderTableMeta.CAPABILITIES_TABLE_NAME}2` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + + " `account` TEXT, `version_mayor` INTEGER NOT NULL, `version_minor` INTEGER NOT NULL, `version_micro` INTEGER NOT NULL," + + " `version_string` TEXT, `version_edition` TEXT, `core_pollinterval` INTEGER NOT NULL, `sharing_api_enabled`" + + " INTEGER NOT NULL DEFAULT -1, `search_min_length` INTEGER, `sharing_public_enabled` INTEGER NOT NULL DEFAULT -1," + + " `sharing_public_password_enforced` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced_read_only`" + + " INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced_read_write` INTEGER NOT NULL DEFAULT -1," + + " `sharing_public_password_enforced_public_only` INTEGER NOT NULL DEFAULT -1, `sharing_public_expire_date_enabled`" + + " INTEGER NOT NULL DEFAULT -1, `sharing_public_expire_date_days` INTEGER NOT NULL, `sharing_public_expire_date_enforced`" + + " INTEGER NOT NULL DEFAULT -1, `sharing_public_send_mail` INTEGER NOT NULL DEFAULT -1, `sharing_public_upload` INTEGER" + + " NOT NULL DEFAULT -1, `sharing_public_multiple` INTEGER NOT NULL DEFAULT -1, `supports_upload_only` INTEGER NOT NULL" + + " DEFAULT -1, `sharing_user_send_mail` INTEGER NOT NULL DEFAULT -1, `sharing_resharing` INTEGER NOT NULL DEFAULT -1," + + " `sharing_federation_outgoing` INTEGER NOT NULL DEFAULT -1, `sharing_federation_incoming` INTEGER NOT NULL DEFAULT -1," + + " `files_bigfilechunking` INTEGER NOT NULL DEFAULT -1, `files_undelete` INTEGER NOT NULL DEFAULT -1, `files_versioning`" + + " INTEGER NOT NULL DEFAULT -1)" ) execSQL("ALTER TABLE ${ProviderTableMeta.CAPABILITIES_TABLE_NAME} ADD COLUMN search_min_length INTEGER") execSQL( - "INSERT INTO `${ProviderTableMeta.CAPABILITIES_TABLE_NAME}2` SELECT id, account, version_mayor, version_minor, version_micro, version_string, version_edition,core_pollinterval, IFNULL(sharing_api_enabled, -1), search_min_length, IFNULL(sharing_public_enabled, -1), IFNULL(sharing_public_password_enforced, -1),IFNULL(sharing_public_password_enforced_read_only, -1),IFNULL(sharing_public_password_enforced_read_write, -1),IFNULL(sharing_public_password_enforced_public_only, -1),IFNULL(sharing_public_expire_date_enabled, -1),IFNULL(sharing_public_expire_date_days, 0),IFNULL(sharing_public_expire_date_enforced, -1),IFNULL(sharing_public_send_mail, -1),IFNULL(sharing_public_upload, -1),IFNULL(sharing_public_multiple, -1), IFNULL(supports_upload_only, -1), IFNULL(sharing_user_send_mail, -1),IFNULL(sharing_resharing, -1),IFNULL(sharing_federation_outgoing, -1),IFNULL(sharing_federation_incoming, -1),IFNULL(files_bigfilechunking, -1),IFNULL(files_undelete, -1),IFNULL(files_versioning, -1) FROM ${ProviderTableMeta.CAPABILITIES_TABLE_NAME}" + "INSERT INTO `${ProviderTableMeta.CAPABILITIES_TABLE_NAME}2` SELECT id, account, version_mayor, version_minor, version_micro," + + " version_string, version_edition,core_pollinterval, IFNULL(sharing_api_enabled, -1), search_min_length," + + " IFNULL(sharing_public_enabled, -1), IFNULL(sharing_public_password_enforced, -1)," + + "IFNULL(sharing_public_password_enforced_read_only, -1),IFNULL(sharing_public_password_enforced_read_write, -1)," + + "IFNULL(sharing_public_password_enforced_public_only, -1),IFNULL(sharing_public_expire_date_enabled, -1)," + + "IFNULL(sharing_public_expire_date_days, 0),IFNULL(sharing_public_expire_date_enforced, -1)," + + "IFNULL(sharing_public_send_mail, -1),IFNULL(sharing_public_upload, -1),IFNULL(sharing_public_multiple, -1)," + + " IFNULL(supports_upload_only, -1), IFNULL(sharing_user_send_mail, -1),IFNULL(sharing_resharing, -1)," + + "IFNULL(sharing_federation_outgoing, -1),IFNULL(sharing_federation_incoming, -1),IFNULL(files_bigfilechunking, -1)," + + "IFNULL(files_undelete, -1),IFNULL(files_versioning, -1) FROM ${ProviderTableMeta.CAPABILITIES_TABLE_NAME}" ) execSQL("DROP TABLE ${ProviderTableMeta.CAPABILITIES_TABLE_NAME}") execSQL("ALTER TABLE ${ProviderTableMeta.CAPABILITIES_TABLE_NAME}2 RENAME TO ${ProviderTableMeta.CAPABILITIES_TABLE_NAME}") diff --git a/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_29.kt b/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_29.kt index 500d651d60e..e4e42d20f57 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_29.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_29.kt @@ -27,13 +27,40 @@ val MIGRATION_28_29 = object : Migration(28, 29) { database.run { execSQL("DROP TABLE ${ProviderTableMeta.OCSHARES_TABLE_NAME}") execSQL( - "CREATE TABLE IF NOT EXISTS `${ProviderTableMeta.OCSHARES_TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `file_source` TEXT NOT NULL, `item_source` TEXT NOT NULL, `share_type` INTEGER NOT NULL, `shate_with` TEXT, `path` TEXT NOT NULL, `permissions` INTEGER NOT NULL, `shared_date` INTEGER NOT NULL, `expiration_date` INTEGER NOT NULL, `token` TEXT, `shared_with_display_name` TEXT, `share_with_additional_info` TEXT, `is_directory` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `id_remote_shared` INTEGER NOT NULL, `owner_share` TEXT NOT NULL, `name` TEXT, `url` TEXT)" + "CREATE TABLE IF NOT EXISTS `${ProviderTableMeta.OCSHARES_TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + + " `file_source` TEXT NOT NULL, `item_source` TEXT NOT NULL, `share_type` INTEGER NOT NULL, `shate_with` TEXT," + + " `path` TEXT NOT NULL, `permissions` INTEGER NOT NULL, `shared_date` INTEGER NOT NULL, `expiration_date` INTEGER" + + " NOT NULL, `token` TEXT, `shared_with_display_name` TEXT, `share_with_additional_info` TEXT, `is_directory` INTEGER" + + " NOT NULL, `user_id` INTEGER NOT NULL, `id_remote_shared` INTEGER NOT NULL, `owner_share` TEXT NOT NULL," + + " `name` TEXT, `url` TEXT)" ) execSQL( - "CREATE TABLE IF NOT EXISTS `${ProviderTableMeta.CAPABILITIES_TABLE_NAME}2` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `account` TEXT, `version_mayor` INTEGER NOT NULL, `version_minor` INTEGER NOT NULL, `version_micro` INTEGER NOT NULL, `version_string` TEXT, `version_edition` TEXT, `core_pollinterval` INTEGER NOT NULL, `sharing_api_enabled` INTEGER NOT NULL DEFAULT -1, `sharing_public_enabled` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced_read_only` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced_read_write` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced_public_only` INTEGER NOT NULL DEFAULT -1, `sharing_public_expire_date_enabled` INTEGER NOT NULL DEFAULT -1, `sharing_public_expire_date_days` INTEGER NOT NULL, `sharing_public_expire_date_enforced` INTEGER NOT NULL DEFAULT -1, `sharing_public_send_mail` INTEGER NOT NULL DEFAULT -1, `sharing_public_upload` INTEGER NOT NULL DEFAULT -1, `sharing_public_multiple` INTEGER NOT NULL DEFAULT -1, `supports_upload_only` INTEGER NOT NULL DEFAULT -1, `sharing_user_send_mail` INTEGER NOT NULL DEFAULT -1, `sharing_resharing` INTEGER NOT NULL DEFAULT -1, `sharing_federation_outgoing` INTEGER NOT NULL DEFAULT -1, `sharing_federation_incoming` INTEGER NOT NULL DEFAULT -1, `files_bigfilechunking` INTEGER NOT NULL DEFAULT -1, `files_undelete` INTEGER NOT NULL DEFAULT -1, `files_versioning` INTEGER NOT NULL DEFAULT -1)" + "CREATE TABLE IF NOT EXISTS `${ProviderTableMeta.CAPABILITIES_TABLE_NAME}2` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + + " `account` TEXT, `version_mayor` INTEGER NOT NULL, `version_minor` INTEGER NOT NULL, `version_micro` INTEGER NOT NULL," + + " `version_string` TEXT, `version_edition` TEXT, `core_pollinterval` INTEGER NOT NULL, `sharing_api_enabled` INTEGER NOT" + + " NULL DEFAULT -1, `sharing_public_enabled` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced` INTEGER NOT" + + " NULL DEFAULT -1, `sharing_public_password_enforced_read_only` INTEGER NOT NULL DEFAULT -1," + + " `sharing_public_password_enforced_read_write` INTEGER NOT NULL DEFAULT -1," + + " `sharing_public_password_enforced_public_only` INTEGER NOT NULL DEFAULT -1, `sharing_public_expire_date_enabled`" + + " INTEGER NOT NULL DEFAULT -1, `sharing_public_expire_date_days` INTEGER NOT NULL, `sharing_public_expire_date_enforced`" + + " INTEGER NOT NULL DEFAULT -1, `sharing_public_send_mail` INTEGER NOT NULL DEFAULT -1, `sharing_public_upload` INTEGER NOT" + + " NULL DEFAULT -1, `sharing_public_multiple` INTEGER NOT NULL DEFAULT -1, `supports_upload_only` INTEGER NOT NULL DEFAULT" + + " -1, `sharing_user_send_mail` INTEGER NOT NULL DEFAULT -1, `sharing_resharing` INTEGER NOT NULL DEFAULT -1," + + " `sharing_federation_outgoing` INTEGER NOT NULL DEFAULT -1, `sharing_federation_incoming` INTEGER NOT NULL DEFAULT -1," + + " `files_bigfilechunking` INTEGER NOT NULL DEFAULT -1, `files_undelete` INTEGER NOT NULL DEFAULT -1, `files_versioning`" + + " INTEGER NOT NULL DEFAULT -1)" ) execSQL( - "INSERT INTO `${ProviderTableMeta.CAPABILITIES_TABLE_NAME}2` SELECT id, account, version_mayor, version_minor, version_micro, version_string, version_edition, core_pollinterval, IFNULL(sharing_api_enabled, -1), IFNULL(sharing_public_enabled, -1), IFNULL(sharing_public_password_enforced, -1),IFNULL(sharing_public_password_enforced_read_only, -1),IFNULL(sharing_public_password_enforced_read_write, -1),IFNULL(sharing_public_password_enforced_public_only, -1),IFNULL(sharing_public_expire_date_enabled, -1),IFNULL(sharing_public_expire_date_days, 0),IFNULL(sharing_public_expire_date_enforced, -1),IFNULL(sharing_public_send_mail, -1),IFNULL(sharing_public_upload, -1),IFNULL(sharing_public_multiple, -1), IFNULL(supports_upload_only, -1), IFNULL(sharing_user_send_mail, -1),IFNULL(sharing_resharing, -1),IFNULL(sharing_federation_outgoing, -1),IFNULL(sharing_federation_incoming, -1),IFNULL(files_bigfilechunking, -1),IFNULL(files_undelete, -1),IFNULL(files_versioning, -1) FROM ${ProviderTableMeta.CAPABILITIES_TABLE_NAME}" + "INSERT INTO `${ProviderTableMeta.CAPABILITIES_TABLE_NAME}2` SELECT id, account, version_mayor, version_minor, version_micro," + + " version_string, version_edition, core_pollinterval, IFNULL(sharing_api_enabled, -1), IFNULL(sharing_public_enabled, -1)," + + " IFNULL(sharing_public_password_enforced, -1),IFNULL(sharing_public_password_enforced_read_only, -1)," + + "IFNULL(sharing_public_password_enforced_read_write, -1),IFNULL(sharing_public_password_enforced_public_only, -1)," + + "IFNULL(sharing_public_expire_date_enabled, -1),IFNULL(sharing_public_expire_date_days, 0)," + + "IFNULL(sharing_public_expire_date_enforced, -1),IFNULL(sharing_public_send_mail, -1),IFNULL(sharing_public_upload, -1)," + + "IFNULL(sharing_public_multiple, -1), IFNULL(supports_upload_only, -1), IFNULL(sharing_user_send_mail, -1)," + + "IFNULL(sharing_resharing, -1),IFNULL(sharing_federation_outgoing, -1),IFNULL(sharing_federation_incoming, -1)," + + "IFNULL(files_bigfilechunking, -1),IFNULL(files_undelete, -1),IFNULL(files_versioning, -1) " + + "FROM ${ProviderTableMeta.CAPABILITIES_TABLE_NAME}" ) execSQL("DROP TABLE ${ProviderTableMeta.CAPABILITIES_TABLE_NAME}") execSQL("ALTER TABLE ${ProviderTableMeta.CAPABILITIES_TABLE_NAME}2 RENAME TO ${ProviderTableMeta.CAPABILITIES_TABLE_NAME}") diff --git a/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_30.kt b/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_30.kt index 8cf2ccf6d82..2d700cdec94 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_30.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_30.kt @@ -27,13 +27,35 @@ val MIGRATION_29_30 = object : Migration(29, 30) { override fun migrate(database: SupportSQLiteDatabase) { database.run { execSQL( - "CREATE TABLE IF NOT EXISTS `${ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME}2` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `account` TEXT, `version_mayor` INTEGER NOT NULL, `version_minor` INTEGER NOT NULL, `version_micro` INTEGER NOT NULL, `version_string` TEXT, `version_edition` TEXT, `core_pollinterval` INTEGER NOT NULL, `dav_chunking_version` TEXT NOT NULL DEFAULT '',`sharing_api_enabled` INTEGER NOT NULL DEFAULT -1, `sharing_public_enabled` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced_read_only` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced_read_write` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced_public_only` INTEGER NOT NULL DEFAULT -1, `sharing_public_expire_date_enabled` INTEGER NOT NULL DEFAULT -1, `sharing_public_expire_date_days` INTEGER NOT NULL, `sharing_public_expire_date_enforced` INTEGER NOT NULL DEFAULT -1, `sharing_public_upload` INTEGER NOT NULL DEFAULT -1, `sharing_public_multiple` INTEGER NOT NULL DEFAULT -1, `supports_upload_only` INTEGER NOT NULL DEFAULT -1, `sharing_resharing` INTEGER NOT NULL DEFAULT -1, `sharing_federation_outgoing` INTEGER NOT NULL DEFAULT -1, `sharing_federation_incoming` INTEGER NOT NULL DEFAULT -1, `files_bigfilechunking` INTEGER NOT NULL DEFAULT -1, `files_undelete` INTEGER NOT NULL DEFAULT -1, `files_versioning` INTEGER NOT NULL DEFAULT -1)" + "CREATE TABLE IF NOT EXISTS `${ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME}2` (`id` INTEGER PRIMARY KEY AUTOINCREMENT" + + " NOT NULL, `account` TEXT, `version_mayor` INTEGER NOT NULL, `version_minor` INTEGER NOT NULL, `version_micro` INTEGER" + + " NOT NULL, `version_string` TEXT, `version_edition` TEXT, `core_pollinterval` INTEGER NOT NULL, `dav_chunking_version`" + + " TEXT NOT NULL DEFAULT '',`sharing_api_enabled` INTEGER NOT NULL DEFAULT -1, `sharing_public_enabled` INTEGER NOT NULL" + + " DEFAULT -1, `sharing_public_password_enforced` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced_read_only`" + + " INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced_read_write` INTEGER NOT NULL DEFAULT -1," + + " `sharing_public_password_enforced_public_only` INTEGER NOT NULL DEFAULT -1, `sharing_public_expire_date_enabled` INTEGER" + + " NOT NULL DEFAULT -1, `sharing_public_expire_date_days` INTEGER NOT NULL, `sharing_public_expire_date_enforced` INTEGER" + + " NOT NULL DEFAULT -1, `sharing_public_upload` INTEGER NOT NULL DEFAULT -1, `sharing_public_multiple` INTEGER NOT NULL" + + " DEFAULT -1, `supports_upload_only` INTEGER NOT NULL DEFAULT -1, `sharing_resharing` INTEGER NOT NULL DEFAULT -1," + + " `sharing_federation_outgoing` INTEGER NOT NULL DEFAULT -1, `sharing_federation_incoming` INTEGER NOT NULL DEFAULT -1," + + " `files_bigfilechunking` INTEGER NOT NULL DEFAULT -1, `files_undelete` INTEGER NOT NULL DEFAULT -1, `files_versioning`" + + " INTEGER NOT NULL DEFAULT -1)" ) execSQL( - "INSERT INTO `${ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME}2` SELECT id, account, version_mayor, version_minor, version_micro, version_string, version_edition, core_pollinterval, '', IFNULL(sharing_api_enabled, -1), IFNULL(sharing_public_enabled, -1), IFNULL(sharing_public_password_enforced, -1),IFNULL(sharing_public_password_enforced_read_only, -1),IFNULL(sharing_public_password_enforced_read_write, -1),IFNULL(sharing_public_password_enforced_public_only, -1),IFNULL(sharing_public_expire_date_enabled, -1),IFNULL(sharing_public_expire_date_days, 0),IFNULL(sharing_public_expire_date_enforced, -1), IFNULL(sharing_public_upload, -1),IFNULL(sharing_public_multiple, -1), IFNULL(supports_upload_only, -1), IFNULL(sharing_resharing, -1),IFNULL(sharing_federation_outgoing, -1),IFNULL(sharing_federation_incoming, -1),IFNULL(files_bigfilechunking, -1),IFNULL(files_undelete, -1),IFNULL(files_versioning, -1) FROM ${ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME}" + "INSERT INTO `${ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME}2` SELECT id, account, version_mayor, version_minor," + + " version_micro, version_string, version_edition, core_pollinterval, '', IFNULL(sharing_api_enabled, -1)," + + " IFNULL(sharing_public_enabled, -1), IFNULL(sharing_public_password_enforced, -1)," + + "IFNULL(sharing_public_password_enforced_read_only, -1),IFNULL(sharing_public_password_enforced_read_write, -1)," + + "IFNULL(sharing_public_password_enforced_public_only, -1),IFNULL(sharing_public_expire_date_enabled, -1)," + + "IFNULL(sharing_public_expire_date_days, 0),IFNULL(sharing_public_expire_date_enforced, -1)," + + " IFNULL(sharing_public_upload, -1),IFNULL(sharing_public_multiple, -1), IFNULL(supports_upload_only, -1)," + + " IFNULL(sharing_resharing, -1),IFNULL(sharing_federation_outgoing, -1),IFNULL(sharing_federation_incoming, -1)," + + "IFNULL(files_bigfilechunking, -1),IFNULL(files_undelete, -1),IFNULL(files_versioning, -1) " + + "FROM ${ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME}" ) execSQL("DROP TABLE ${ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME}") - execSQL("ALTER TABLE ${ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME}2 RENAME TO ${ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME}") + execSQL("ALTER TABLE ${ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME}2 RENAME TO" + + " ${ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME}") } } diff --git a/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_32.kt b/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_32.kt index da58db549f2..fb9cde4f05d 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_32.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_32.kt @@ -24,6 +24,7 @@ import androidx.sqlite.db.SupportSQLiteDatabase val MIGRATION_31_32 = object : Migration(31, 32) { override fun migrate(database: SupportSQLiteDatabase) { - database.execSQL("CREATE TABLE IF NOT EXISTS `user_quotas` (`accountName` TEXT NOT NULL, `used` INTEGER NOT NULL, `available` INTEGER NOT NULL, PRIMARY KEY(`accountName`))") + database.execSQL("CREATE TABLE IF NOT EXISTS `user_quotas` (`accountName` TEXT NOT NULL, `used` INTEGER NOT NULL," + + " `available` INTEGER NOT NULL, PRIMARY KEY(`accountName`))") } } diff --git a/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_33.kt b/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_33.kt index 13ac1365bb0..c14dfa68146 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_33.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_33.kt @@ -31,7 +31,11 @@ val MIGRATION_32_33 = object : Migration(32, 33) { try { // 1. Create new OCShares table - database.execSQL("CREATE TABLE IF NOT EXISTS `${OCSHARES_TABLE_NAME}2` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `share_type` INTEGER NOT NULL, `share_with` TEXT, `path` TEXT NOT NULL, `permissions` INTEGER NOT NULL, `shared_date` INTEGER NOT NULL, `expiration_date` INTEGER NOT NULL, `token` TEXT, `shared_with_display_name` TEXT, `share_with_additional_info` TEXT, `is_directory` INTEGER NOT NULL, `id_remote_shared` TEXT NOT NULL, `owner_share` TEXT NOT NULL, `name` TEXT, `url` TEXT)") + database.execSQL("CREATE TABLE IF NOT EXISTS `${OCSHARES_TABLE_NAME}2` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + + " `share_type` INTEGER NOT NULL, `share_with` TEXT, `path` TEXT NOT NULL, `permissions` INTEGER NOT NULL, `shared_date`" + + " INTEGER NOT NULL, `expiration_date` INTEGER NOT NULL, `token` TEXT, `shared_with_display_name` TEXT," + + " `share_with_additional_info` TEXT, `is_directory` INTEGER NOT NULL, `id_remote_shared` TEXT NOT NULL, `owner_share`" + + " TEXT NOT NULL, `name` TEXT, `url` TEXT)") // 2. Get old OCShares and insert them into the new table val cursor = database.query("SELECT * FROM $OCSHARES_TABLE_NAME") diff --git a/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_34.kt b/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_34.kt index f58b2d83e4a..1c3500eceea 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_34.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_34.kt @@ -31,7 +31,9 @@ import java.io.File val MIGRATION_33_34 = object : Migration(33, 34) { override fun migrate(database: SupportSQLiteDatabase) { - database.execSQL("CREATE TABLE IF NOT EXISTS `$FOLDER_BACKUP_TABLE_NAME` (`accountName` TEXT NOT NULL, `behavior` TEXT NOT NULL, `sourcePath` TEXT NOT NULL, `uploadPath` TEXT NOT NULL, `wifiOnly` INTEGER NOT NULL, `name` TEXT NOT NULL, `lastSyncTimestamp` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)") + database.execSQL("CREATE TABLE IF NOT EXISTS `$FOLDER_BACKUP_TABLE_NAME` (`accountName` TEXT NOT NULL, `behavior` TEXT NOT NULL," + + " `sourcePath` TEXT NOT NULL, `uploadPath` TEXT NOT NULL, `wifiOnly` INTEGER NOT NULL, `name` TEXT NOT NULL," + + " `lastSyncTimestamp` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)") } } diff --git a/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_38.kt b/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_38.kt index e52800ade85..87039dedef4 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_38.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_38.kt @@ -26,7 +26,15 @@ import androidx.sqlite.db.SupportSQLiteDatabase val MIGRATION_37_38 = object : Migration(37, 38) { override fun migrate(database: SupportSQLiteDatabase) { - database.execSQL("CREATE TABLE IF NOT EXISTS `files` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `parentId` INTEGER, `owner` TEXT NOT NULL, `remotePath` TEXT NOT NULL, `remoteId` TEXT, `length` INTEGER NOT NULL, `creationTimestamp` INTEGER, `modificationTimestamp` INTEGER NOT NULL, `mimeType` TEXT NOT NULL, `etag` TEXT, `permissions` TEXT, `privateLink` TEXT, `storagePath` TEXT, `name` TEXT, `treeEtag` TEXT, `keepInSync` INTEGER, `lastSyncDateForData` INTEGER, `fileShareViaLink` INTEGER, `lastSyncDateForProperties` INTEGER, `needsToUpdateThumbnail` INTEGER NOT NULL, `modifiedAtLastSyncForData` INTEGER, `etagInConflict` TEXT, `fileIsDownloading` INTEGER, `sharedWithSharee` INTEGER, `sharedByLink` INTEGER NOT NULL)") - database.execSQL("CREATE TABLE IF NOT EXISTS `transfers` (`localPath` TEXT NOT NULL, `remotePath` TEXT NOT NULL, `accountName` TEXT NOT NULL, `fileSize` INTEGER NOT NULL, `status` INTEGER NOT NULL, `localBehaviour` INTEGER NOT NULL, `forceOverwrite` INTEGER NOT NULL, `transferEndTimestamp` INTEGER, `lastResult` INTEGER, `createdBy` INTEGER NOT NULL, `transferId` TEXT, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)") + database.execSQL("CREATE TABLE IF NOT EXISTS `files` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `parentId` INTEGER," + + " `owner` TEXT NOT NULL, `remotePath` TEXT NOT NULL, `remoteId` TEXT, `length` INTEGER NOT NULL, `creationTimestamp` INTEGER," + + " `modificationTimestamp` INTEGER NOT NULL, `mimeType` TEXT NOT NULL, `etag` TEXT, `permissions` TEXT, `privateLink` TEXT," + + " `storagePath` TEXT, `name` TEXT, `treeEtag` TEXT, `keepInSync` INTEGER, `lastSyncDateForData` INTEGER, `fileShareViaLink`" + + " INTEGER, `lastSyncDateForProperties` INTEGER, `needsToUpdateThumbnail` INTEGER NOT NULL, `modifiedAtLastSyncForData` INTEGER," + + " `etagInConflict` TEXT, `fileIsDownloading` INTEGER, `sharedWithSharee` INTEGER, `sharedByLink` INTEGER NOT NULL)") + database.execSQL("CREATE TABLE IF NOT EXISTS `transfers` (`localPath` TEXT NOT NULL, `remotePath` TEXT NOT NULL, `accountName`" + + " TEXT NOT NULL, `fileSize` INTEGER NOT NULL, `status` INTEGER NOT NULL, `localBehaviour` INTEGER NOT NULL, `forceOverwrite`" + + " INTEGER NOT NULL, `transferEndTimestamp` INTEGER, `lastResult` INTEGER, `createdBy` INTEGER NOT NULL, `transferId` TEXT," + + " `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)") } } diff --git a/owncloudData/src/test/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSourceTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSourceTest.kt index 55c6766443a..5c36eef73ff 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSourceTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSourceTest.kt @@ -296,7 +296,9 @@ class OCLocalFileDataSourceTest { @Test fun `getSearchAvailableOfflineFolderContent returns a list of OCFile`() { - every { fileDao.getSearchAvailableOfflineFolderContent(OC_FILE_AVAILABLE_OFFLINE_ENTITY.parentId!!, "test") } returns listOf(OC_FILE_AVAILABLE_OFFLINE_ENTITY) + every { + fileDao.getSearchAvailableOfflineFolderContent(OC_FILE_AVAILABLE_OFFLINE_ENTITY.parentId!!, "test") + } returns listOf(OC_FILE_AVAILABLE_OFFLINE_ENTITY) val result = ocLocalFileDataSource.getSearchAvailableOfflineFolderContent(OC_FILE_AVAILABLE_OFFLINE_ENTITY.parentId!!, "test") @@ -384,7 +386,9 @@ class OCLocalFileDataSourceTest { @Test fun `getSharedByLinkWithSyncInfoForAccountAsFlow returns a Flow with a list of OCFileWithSyncInfo`() = runTest { - val fileAndFileSyncEntitySharedByLink = OC_FILE_AND_FILE_SYNC.copy(file = OC_FILE_ENTITY.copy(sharedByLink = true).apply { this.id = OC_FILE_ENTITY.id }) + val fileAndFileSyncEntitySharedByLink = OC_FILE_AND_FILE_SYNC.copy(file = OC_FILE_ENTITY.copy(sharedByLink = true).apply { + this.id = OC_FILE_ENTITY.id + }) val fileWithSyncInfoSharedByLink = OC_FILE_WITH_SYNC_INFO_AND_SPACE.copy(file = OC_FILE.copy(sharedByLink = true)) @@ -411,14 +415,18 @@ class OCLocalFileDataSourceTest { @Test fun `getFilesWithSyncInfoAvailableOfflineFromAccountAsFlow returns a Flow with a list of OCFileWithSyncInfo`() = runTest { val fileAndFileSyncEntityAvailableOffline = OC_FILE_AND_FILE_SYNC.copy( - file = OC_FILE_ENTITY.copy(availableOfflineStatus = AvailableOfflineStatus.AVAILABLE_OFFLINE.ordinal).apply { this.id = OC_FILE_ENTITY.id } + file = OC_FILE_ENTITY.copy(availableOfflineStatus = AvailableOfflineStatus.AVAILABLE_OFFLINE.ordinal).apply { + this.id = OC_FILE_ENTITY.id + } ) val fileWithSyncInfoAvailableOffline = OC_FILE_WITH_SYNC_INFO_AND_SPACE.copy( file = OC_FILE.copy(availableOfflineStatus = AvailableOfflineStatus.AVAILABLE_OFFLINE) ) - every { fileDao.getFilesWithSyncInfoAvailableOfflineFromAccountAsFlow(OC_ACCOUNT_NAME) } returns flowOf(listOf(fileAndFileSyncEntityAvailableOffline)) + every { + fileDao.getFilesWithSyncInfoAvailableOfflineFromAccountAsFlow(OC_ACCOUNT_NAME) + } returns flowOf(listOf(fileAndFileSyncEntityAvailableOffline)) val result = ocLocalFileDataSource.getFilesWithSyncInfoAvailableOfflineFromAccountAsFlow(OC_ACCOUNT_NAME).first() @@ -428,7 +436,8 @@ class OCLocalFileDataSourceTest { } @Test - fun `getFilesWithSyncInfoAvailableOfflineFromAccountAsFlow returns a Flow with an empty list when DAO returns a Flow with an empty list`() = runTest { + fun `getFilesWithSyncInfoAvailableOfflineFromAccountAsFlow returns a Flow with an empty list when DAO returns a Flow with an empty list`() + = runTest { every { fileDao.getFilesWithSyncInfoAvailableOfflineFromAccountAsFlow(OC_ACCOUNT_NAME) } returns flowOf(emptyList()) val result = ocLocalFileDataSource.getFilesWithSyncInfoAvailableOfflineFromAccountAsFlow(OC_ACCOUNT_NAME).first() diff --git a/owncloudData/src/test/java/com/owncloud/android/data/files/repository/OCFileRepositoryTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/files/repository/OCFileRepositoryTest.kt index f63a53c41aa..70929cc9cb6 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/files/repository/OCFileRepositoryTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/files/repository/OCFileRepositoryTest.kt @@ -131,6 +131,7 @@ class OCFileRepositoryTest { } } + @Suppress("MaxLineLength") @Test fun `copyFile returns a list with the OCFile in conflict (the copied OCFile) when replace parameter is empty and expected path already exists`() { every { @@ -341,6 +342,7 @@ class OCFileRepositoryTest { } } + @Suppress("MaxLineLength") @Test fun `copyFile removes target folder locally and throws a ConflictException when replace parameter is empty and expected path doesn't exist but target folder doesn't exist anymore`() { every { @@ -398,6 +400,7 @@ class OCFileRepositoryTest { } } + @Suppress("MaxLineLength") @Test fun `copyFile removes source file locally and throws a FileNotFoundException when replace parameter is empty and expected path doesn't exist but source file doesn't exist anymore`() { every { @@ -548,7 +551,11 @@ class OCFileRepositoryTest { ) } returns OC_FILE_WITH_SPACE_ID - val ocFile = ocFileRepository.getFileByRemotePath(OC_FILE_WITH_SPACE_ID.remotePath, OC_FOLDER_WITH_SPACE_ID.owner, OC_FOLDER_WITH_SPACE_ID.spaceId) + val ocFile = ocFileRepository.getFileByRemotePath( + OC_FILE_WITH_SPACE_ID.remotePath, + OC_FOLDER_WITH_SPACE_ID.owner, + OC_FOLDER_WITH_SPACE_ID.spaceId + ) assertEquals(OC_FILE_WITH_SPACE_ID, ocFile) verify(exactly = 1) { @@ -570,7 +577,11 @@ class OCFileRepositoryTest { ) } returns null - val ocFile = ocFileRepository.getFileByRemotePath(OC_FILE_WITH_SPACE_ID.remotePath, OC_FOLDER_WITH_SPACE_ID.owner, OC_FOLDER_WITH_SPACE_ID.spaceId) + val ocFile = ocFileRepository.getFileByRemotePath( + OC_FILE_WITH_SPACE_ID.remotePath, + OC_FOLDER_WITH_SPACE_ID.owner, + OC_FOLDER_WITH_SPACE_ID.spaceId + ) assertNull(ocFile) verify(exactly = 1) { @@ -1093,6 +1104,7 @@ class OCFileRepositoryTest { } } + @Suppress("MaxLineLength") @Test fun `moveFile returns an empty list with no OCFiles in conflict when replace parameter is empty, expected path doesn't exist and file has a conflict`() { every { @@ -1271,6 +1283,7 @@ class OCFileRepositoryTest { } } + @Suppress("MaxLineLength") @Test fun `moveFile removes target folder locally and throws a ConflictException when replace parameter is empty and expected path doesn't exist but target folder doesn't exist anymore`() { every { @@ -1334,6 +1347,7 @@ class OCFileRepositoryTest { } } + @Suppress("MaxLineLength") @Test fun `moveFile removes source file locally and throws a FileNotFoundException when replace parameter is empty and expected path doesn't exist but source file doesn't exist anymore`() { every { @@ -1449,7 +1463,12 @@ class OCFileRepositoryTest { ) } returns emptyList() - val listOfFiles = ocFileRepository.refreshFolder(OC_PARENT_FOLDER_WITH_SPACE_ID.remotePath, OC_PARENT_FOLDER_WITH_SPACE_ID.owner, OC_PARENT_FOLDER_WITH_SPACE_ID.spaceId, false) + val listOfFiles = ocFileRepository.refreshFolder( + OC_PARENT_FOLDER_WITH_SPACE_ID.remotePath, + OC_PARENT_FOLDER_WITH_SPACE_ID.owner, + OC_PARENT_FOLDER_WITH_SPACE_ID.spaceId, + false + ) assertEquals(emptyList(), listOfFiles) verify(exactly = 1) { @@ -1505,7 +1524,12 @@ class OCFileRepositoryTest { ) } returns emptyList() - val listOfFiles = ocFileRepository.refreshFolder(OC_PARENT_FOLDER_WITH_SPACE_ID.remotePath, OC_PARENT_FOLDER_WITH_SPACE_ID.owner, OC_PARENT_FOLDER_WITH_SPACE_ID.spaceId, false) + val listOfFiles = ocFileRepository.refreshFolder( + OC_PARENT_FOLDER_WITH_SPACE_ID.remotePath, + OC_PARENT_FOLDER_WITH_SPACE_ID.owner, + OC_PARENT_FOLDER_WITH_SPACE_ID.spaceId, + false + ) assertEquals(emptyList(), listOfFiles) verify(exactly = 1) { @@ -1533,6 +1557,7 @@ class OCFileRepositoryTest { } } + @Suppress("MaxLineLength") @Test fun `refreshFolder returns a list with the OCFile that changed when folder and its content already exists in database but needs to be updated`() { val ocParentFolderWithoutSpaceId = OC_PARENT_FOLDER_WITH_SPACE_ID.copy(spaceId = null) @@ -1563,7 +1588,12 @@ class OCFileRepositoryTest { ) } returns listOf(OC_FILE_WITH_SPACE_ID) - val listOfFiles = ocFileRepository.refreshFolder(OC_PARENT_FOLDER_WITH_SPACE_ID.remotePath, OC_PARENT_FOLDER_WITH_SPACE_ID.owner, OC_PARENT_FOLDER_WITH_SPACE_ID.spaceId, true) + val listOfFiles = ocFileRepository.refreshFolder( + OC_PARENT_FOLDER_WITH_SPACE_ID.remotePath, + OC_PARENT_FOLDER_WITH_SPACE_ID.owner, + OC_PARENT_FOLDER_WITH_SPACE_ID.spaceId, + true + ) assertEquals(listOf(OC_FILE_WITH_SPACE_ID), listOfFiles) verify(exactly = 1) { @@ -1591,6 +1621,7 @@ class OCFileRepositoryTest { } } + @Suppress("MaxLineLength") @Test fun `refreshFolder returns an empty list of OCFiles when folder and its content already exists in database updated and the action is not set folder available offline or synchronize`() { val ocParentFolderWithoutSpaceId = OC_PARENT_FOLDER_WITH_SPACE_ID.copy(spaceId = null) @@ -1621,7 +1652,12 @@ class OCFileRepositoryTest { ) } returns emptyList() - val listOfFiles = ocFileRepository.refreshFolder(OC_PARENT_FOLDER_WITH_SPACE_ID.remotePath, OC_PARENT_FOLDER_WITH_SPACE_ID.owner, OC_PARENT_FOLDER_WITH_SPACE_ID.spaceId, false) + val listOfFiles = ocFileRepository.refreshFolder( + OC_PARENT_FOLDER_WITH_SPACE_ID.remotePath, + OC_PARENT_FOLDER_WITH_SPACE_ID.owner, + OC_PARENT_FOLDER_WITH_SPACE_ID.spaceId, + false + ) assertEquals(emptyList(), listOfFiles) verify(exactly = 1) { @@ -1649,11 +1685,13 @@ class OCFileRepositoryTest { } } + @Suppress("MaxLineLength") @Test fun `refreshFolder returns an empty list of OCFiles when folder and its content already exists in database but there are additional files in conflict in local to be removed`() { val ocParentFolderWithoutSpaceId = OC_PARENT_FOLDER_WITH_SPACE_ID.copy(spaceId = null) val ocFileWithoutSpaceId = OC_FILE_WITH_SPACE_ID.copy(spaceId = null) - val additionalOcFile = OC_FILE_WITH_SPACE_ID.copy(id = 300, remotePath = "/Folder/image3.jpt", remoteId = "00000003oci9p7er2hox2", privateLink = "http://server.url/f/70", etagInConflict = etagInConflict) + val additionalOcFile = OC_FILE_WITH_SPACE_ID.copy(id = 300, remotePath = "/Folder/image3.jpt", + remoteId = "00000003oci9p7er2hox2", privateLink = "http://server.url/f/70", etagInConflict = etagInConflict) every { remoteFileDataSource.refreshFolder( remotePath = OC_PARENT_FOLDER_WITH_SPACE_ID.remotePath, @@ -1683,7 +1721,11 @@ class OCFileRepositoryTest { ) } returns emptyList() - val listOfFiles = ocFileRepository.refreshFolder(OC_PARENT_FOLDER_WITH_SPACE_ID.remotePath, OC_PARENT_FOLDER_WITH_SPACE_ID.owner, OC_PARENT_FOLDER_WITH_SPACE_ID.spaceId, false) + val listOfFiles = ocFileRepository.refreshFolder( + OC_PARENT_FOLDER_WITH_SPACE_ID.remotePath, + OC_PARENT_FOLDER_WITH_SPACE_ID.owner, + OC_PARENT_FOLDER_WITH_SPACE_ID.spaceId, + false) assertEquals(emptyList(), listOfFiles) verify(exactly = 1) { diff --git a/owncloudData/src/test/java/com/owncloud/android/data/transfers/datasources/implementation/OCLocalTransferDataSourceTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/transfers/datasources/implementation/OCLocalTransferDataSourceTest.kt index df3bcca4496..a1e36cdc435 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/transfers/datasources/implementation/OCLocalTransferDataSourceTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/transfers/datasources/implementation/OCLocalTransferDataSourceTest.kt @@ -108,7 +108,12 @@ class OCLocalTransferDataSourceTest { ocLocalTransferDataSource.updateTransferWhenFinished(OC_TRANSFER.id!!, TransferStatus.TRANSFER_SUCCEEDED, timestamp, TransferResult.UPLOADED) verify(exactly = 1) { - transferDao.updateTransferWhenFinished(OC_TRANSFER.id!!, TransferStatus.TRANSFER_SUCCEEDED.value, timestamp, TransferResult.UPLOADED.value) + transferDao.updateTransferWhenFinished( + OC_TRANSFER.id!!, + TransferStatus.TRANSFER_SUCCEEDED.value, + timestamp, + TransferResult.UPLOADED.value + ) } } From 9e999436c3f5bc05c0418b74439ef04a4f995a45 Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Tue, 10 Dec 2024 11:09:20 +0100 Subject: [PATCH 14/74] style: wrap lines more than 150 characters in module `owncloudDomain` --- .../GetFilesAvailableOfflineFromAccountAsStreamUseCase.kt | 3 ++- .../domain/server/usecases/GetServerInfoAsyncUseCaseTest.kt | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/availableoffline/usecases/GetFilesAvailableOfflineFromAccountAsStreamUseCase.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/availableoffline/usecases/GetFilesAvailableOfflineFromAccountAsStreamUseCase.kt index a100b186325..a6e71d852af 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/availableoffline/usecases/GetFilesAvailableOfflineFromAccountAsStreamUseCase.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/availableoffline/usecases/GetFilesAvailableOfflineFromAccountAsStreamUseCase.kt @@ -26,7 +26,8 @@ class GetFilesAvailableOfflineFromAccountAsStreamUseCase( private val fileRepository: FileRepository ) : BaseUseCase>, GetFilesAvailableOfflineFromAccountAsStreamUseCase.Params>() { - override fun run(params: Params): Flow> = fileRepository.getFilesWithSyncInfoAvailableOfflineFromAccountAsFlow(params.owner) + override fun run(params: Params): Flow> = + fileRepository.getFilesWithSyncInfoAvailableOfflineFromAccountAsFlow(params.owner) data class Params( val owner: String diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/server/usecases/GetServerInfoAsyncUseCaseTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/server/usecases/GetServerInfoAsyncUseCaseTest.kt index f39c7977b7d..c266e4e4ff7 100644 --- a/owncloudDomain/src/test/java/com/owncloud/android/domain/server/usecases/GetServerInfoAsyncUseCaseTest.kt +++ b/owncloudDomain/src/test/java/com/owncloud/android/domain/server/usecases/GetServerInfoAsyncUseCaseTest.kt @@ -78,6 +78,7 @@ class GetServerInfoAsyncUseCaseTest { verify(exactly = 1) { repository.getServerInfo(useCaseParams.serverPath, false, false) } } + @Suppress("MaxLineLength") @Test fun `Should throw SSLErrorException when secureConnectionEnforced is true and ServerInfoRepository returns ServerInfo with isSecureConnection returning false`() { every { repository.getServerInfo(useCaseParams.serverPath, false, false) } returns OC_INSECURE_SERVER_INFO_BASIC_AUTH @@ -90,6 +91,7 @@ class GetServerInfoAsyncUseCaseTest { verify(exactly = 1) { repository.getServerInfo(useCaseParams.serverPath, false, false) } } + @Suppress("MaxLineLength") @Test fun `Should work correctly when secureConnectionEnforced is true and ServerInfoRepository returns ServerInfo with isSecureConnection returning true`() { every { repository.getServerInfo(useCaseParams.serverPath, false, false) } returns OC_SECURE_SERVER_INFO_BASIC_AUTH From 3763025fcd9f78f8fde710b5018a85c71c331897 Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Tue, 10 Dec 2024 11:11:22 +0100 Subject: [PATCH 15/74] style: wrap lines more than 150 characters in module `owncloudTestUtil` --- .../src/main/java/com/owncloud/android/testutil/OCSpace.kt | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCSpace.kt b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCSpace.kt index 26ff75cd45a..36c0d6ccbae 100644 --- a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCSpace.kt +++ b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCSpace.kt @@ -55,7 +55,8 @@ val OC_SPACE_SPECIAL_README = SpaceSpecial( specialFolder = SpaceSpecialFolder( name = "readme" ), - webDavUrl = "https://server.com/dav/spaces/8871f4f3-fc6f-4a66-8bed-62f175f76f38$0aa0e03c-ec36-498c-bb9f-857315568199%210aa0e03c-ec36-498c-bb9f-857315568199/.space/readme.md" + webDavUrl = "https://server.com/dav/spaces/8871f4f3-fc6f-4a66-8bed-62f175f76f38$" + + "0aa0e03c-ec36-498c-bb9f-857315568199%210aa0e03c-ec36-498c-bb9f-857315568199/.space/readme.md" ) val OC_SPACE_SPECIAL_IMAGE = SpaceSpecial( @@ -70,7 +71,8 @@ val OC_SPACE_SPECIAL_IMAGE = SpaceSpecial( specialFolder = SpaceSpecialFolder( name = "image" ), - webDavUrl = "https://server.com/dav/spaces/8871f4f3-fc6f-4a66-8bed-62f175f76f38$0aa0e03c-ec36-498c-bb9f-857315568199%210aa0e03c-ec36-498c-bb9f-857315568199/.space/image.jpg" + webDavUrl = "https://server.com/dav/spaces/8871f4f3-fc6f-4a66-8bed-62f175f76f38$" + + "0aa0e03c-ec36-498c-bb9f-857315568199%210aa0e03c-ec36-498c-bb9f-857315568199/.space/image.jpg" ) val OC_SPACE_PROJECT_WITH_IMAGE = OCSpace( From 88ff2ac6f7de2618e49c8a138de3150e6070157e Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Wed, 11 Dec 2024 13:42:08 +0100 Subject: [PATCH 16/74] refactor: refactor methods with more than 100 lines --- .../files/filelist/FileListAdapter.kt | 137 +++--- .../files/filelist/MainFileListFragment.kt | 425 ++++++++++-------- .../security/SettingsSecurityFragment.kt | 9 +- .../sharees/UsersAndGroupsSearchProvider.kt | 29 +- .../transfers/TransfersAdapter.kt | 266 +++++------ .../android/providers/FileContentProvider.kt | 1 + 6 files changed, 465 insertions(+), 402 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt index cba5cdf369e..d84a1a6a467 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt @@ -207,71 +207,7 @@ class FileListAdapter( holder.itemView.findViewById(R.id.shared_via_users_icon).isVisible = file.sharedWithSharee == true || file.isSharedWithMe - when (viewType) { - ViewType.LIST_ITEM.ordinal -> { - val view = holder as ListViewHolder - view.binding.let { - it.fileListConstraintLayout.filterTouchesWhenObscured = PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(context) - it.Filename.text = file.fileName - it.fileListSize.text = DisplayUtils.bytesToHumanReadable(file.length, context, true) - it.fileListLastMod.text = DisplayUtils.getRelativeTimestamp(context, file.modificationTimestamp) - it.threeDotMenu.isVisible = getCheckedItems().isEmpty() - it.threeDotMenu.contentDescription = context.getString(R.string.content_description_file_operations, file.fileName) - if (fileListOption.isAvailableOffline() || (fileListOption.isSharedByLink() && fileWithSyncInfo.space == null)) { - it.spacePathLine.path.apply { - text = file.getParentRemotePath() - isVisible = true - } - fileWithSyncInfo.space?.let { space -> - it.spacePathLine.spaceIcon.isVisible = true - it.spacePathLine.spaceName.isVisible = true - if (space.isPersonal) { - it.spacePathLine.spaceIcon.setImageResource(R.drawable.ic_folder) - it.spacePathLine.spaceName.setText(R.string.bottom_nav_personal) - } else { - it.spacePathLine.spaceName.text = space.name - } - } - } else { - it.spacePathLine.path.isVisible = false - it.spacePathLine.spaceIcon.isVisible = false - it.spacePathLine.spaceName.isVisible = false - } - it.threeDotMenu.setOnClickListener { - listener.onThreeDotButtonClick(fileWithSyncInfo = fileWithSyncInfo) - } - } - } - - ViewType.GRID_ITEM.ordinal -> { - // Filename - val view = holder as GridViewHolder - view.binding.Filename.text = file.fileName - } - - ViewType.GRID_IMAGE.ordinal -> { - val view = holder as GridImageViewHolder - val layoutParams = fileIcon.layoutParams as ViewGroup.MarginLayoutParams - - if (thumbnail == null) { - view.binding.Filename.text = file.fileName - // Reset layout params values default - manageGridLayoutParams( - layoutParams = layoutParams, - marginVertical = 0, - height = context.resources.getDimensionPixelSize(R.dimen.item_file_grid_height), - width = context.resources.getDimensionPixelSize(R.dimen.item_file_grid_width), - ) - } else { - manageGridLayoutParams( - layoutParams = layoutParams, - marginVertical = context.resources.getDimensionPixelSize(R.dimen.item_file_image_grid_margin), - height = ViewGroup.LayoutParams.MATCH_PARENT, - width = ViewGroup.LayoutParams.MATCH_PARENT, - ) - } - } - } + setSpecificViewHolder(viewType, holder, fileWithSyncInfo, thumbnail) setIconPinAccordingToFilesLocalState(holder.itemView.findViewById(R.id.localFileIndicator), fileWithSyncInfo) @@ -342,6 +278,77 @@ class FileListAdapter( } } + private fun setSpecificViewHolder(viewType: Int, holder: RecyclerView.ViewHolder, fileWithSyncInfo: OCFileWithSyncInfo, thumbnail: Bitmap?) { + val file = fileWithSyncInfo.file + + when (viewType) { + ViewType.LIST_ITEM.ordinal -> { + val view = holder as ListViewHolder + view.binding.let { + it.fileListConstraintLayout.filterTouchesWhenObscured = PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(context) + it.Filename.text = file.fileName + it.fileListSize.text = DisplayUtils.bytesToHumanReadable(file.length, context, true) + it.fileListLastMod.text = DisplayUtils.getRelativeTimestamp(context, file.modificationTimestamp) + it.threeDotMenu.isVisible = getCheckedItems().isEmpty() + it.threeDotMenu.contentDescription = context.getString(R.string.content_description_file_operations, file.fileName) + if (fileListOption.isAvailableOffline() || (fileListOption.isSharedByLink() && fileWithSyncInfo.space == null)) { + it.spacePathLine.path.apply { + text = file.getParentRemotePath() + isVisible = true + } + fileWithSyncInfo.space?.let { space -> + it.spacePathLine.spaceIcon.isVisible = true + it.spacePathLine.spaceName.isVisible = true + if (space.isPersonal) { + it.spacePathLine.spaceIcon.setImageResource(R.drawable.ic_folder) + it.spacePathLine.spaceName.setText(R.string.bottom_nav_personal) + } else { + it.spacePathLine.spaceName.text = space.name + } + } + } else { + it.spacePathLine.path.isVisible = false + it.spacePathLine.spaceIcon.isVisible = false + it.spacePathLine.spaceName.isVisible = false + } + it.threeDotMenu.setOnClickListener { + listener.onThreeDotButtonClick(fileWithSyncInfo = fileWithSyncInfo) + } + } + } + + ViewType.GRID_ITEM.ordinal -> { + // Filename + val view = holder as GridViewHolder + view.binding.Filename.text = file.fileName + } + + ViewType.GRID_IMAGE.ordinal -> { + val view = holder as GridImageViewHolder + val fileIcon = holder.itemView.findViewById(R.id.thumbnail) + val layoutParams = fileIcon.layoutParams as ViewGroup.MarginLayoutParams + + if (thumbnail == null) { + view.binding.Filename.text = file.fileName + // Reset layout params values default + manageGridLayoutParams( + layoutParams = layoutParams, + marginVertical = 0, + height = context.resources.getDimensionPixelSize(R.dimen.item_file_grid_height), + width = context.resources.getDimensionPixelSize(R.dimen.item_file_grid_width), + ) + } else { + manageGridLayoutParams( + layoutParams = layoutParams, + marginVertical = context.resources.getDimensionPixelSize(R.dimen.item_file_image_grid_margin), + height = ViewGroup.LayoutParams.MATCH_PARENT, + width = ViewGroup.LayoutParams.MATCH_PARENT, + ) + } + } + } + } + private fun manageGridLayoutParams(layoutParams: ViewGroup.MarginLayoutParams, marginVertical: Int, height: Int, width: Int) { val marginHorizontal = context.resources.getDimensionPixelSize(R.dimen.item_file_image_grid_margin) layoutParams.setMargins(marginHorizontal, marginVertical, marginHorizontal, marginVertical) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt index 097480b0133..255d8417281 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt @@ -323,6 +323,50 @@ class MainFileListFragment : Fragment(), private fun subscribeToViewModels() { /* MainFileListViewModel observables */ // Observe the current folder displayed + observeCurrentFolderDisplayed() + + // Observe the current space to update the toolbar + // We can't rely exclusively on the [currentFolderDisplayed] because sometimes retrieving the space takes more time + observeSpace() + + // Observe the list of app registries that allow creating new files + observeAppRegistryToCreateFiles() + + // Observe the open in web action to trigger browser + observeOpenInWebFlow() + + // Observe the menu filtered options in multiselection + observeMenuOptions() + + // Observe the app registry in multiselection + observeAppRegistryMimeType() + + // Observe the menu filtered options for a single file + observeMenuOptionsSingleFile() + + // Observe the app registry for a single file + observeAppRegistryMimeTypeSingleFile() + + // Observe the file list UI state + observeFileListUiState() + + /* FileOperationsViewModel observables */ + // Observe the refresh folder operation + observeRefreshFolder() + + // Observe the create file with app provider operation + observeCreateFileWithAppProvider() + + // Observe the check if file is local and not available offline operation + observeCheckIfFileIsLocalAndNotAvailableOffline() + + /* TransfersViewModel observables */ + // Observe transfers + observeTransfers() + + } + + private fun observeCurrentFolderDisplayed() { collectLatestLifecycleFlow(mainFileListViewModel.currentFolderDisplayed) { currentFolderDisplayed: OCFile -> fileActions?.onCurrentFolderUpdated(currentFolderDisplayed, mainFileListViewModel.getSpace()) val fileListOption = mainFileListViewModel.fileListOption.value @@ -345,22 +389,23 @@ class MainFileListFragment : Fragment(), numberOfUploadsRefreshed = 0 hideRefreshFab() } + } - // Observe the current space to update the toolbar - // We can't rely exclusively on the [currentFolderDisplayed] because sometimes retrieving the space takes more time + private fun observeSpace() { collectLatestLifecycleFlow(mainFileListViewModel.space) { currentSpace: OCSpace? -> currentSpace?.let { fileActions?.onCurrentFolderUpdated(mainFileListViewModel.getFile(), currentSpace) } } - - // Observe the list of app registries that allow creating new files + } + private fun observeAppRegistryToCreateFiles() { collectLatestLifecycleFlow(mainFileListViewModel.appRegistryToCreateFiles) { listAppRegistry -> binding.fabNewfile.isVisible = listAppRegistry.isNotEmpty() registerFabNewFileListener(listAppRegistry) } + } - // Observe the open in web action to trigger browser + private fun observeOpenInWebFlow() { collectLatestLifecycleFlow(mainFileListViewModel.openInWebFlow) { if (it != null) { val uiResult = it.peekContent() @@ -391,8 +436,9 @@ class MainFileListFragment : Fragment(), currentDefaultApplication = null } } + } - // Observe the menu filtered options in multiselection + private fun observeMenuOptions() { collectLatestLifecycleFlow(mainFileListViewModel.menuOptions) { menuOptions -> val hasWritePermission = if (checkedFiles.size == 1) { checkedFiles.first().hasWritePermission @@ -401,16 +447,18 @@ class MainFileListFragment : Fragment(), } menu?.filterMenuOptions(menuOptions, hasWritePermission) } + } - // Observe the app registry in multiselection + private fun observeAppRegistryMimeType() { collectLatestLifecycleFlow(mainFileListViewModel.appRegistryMimeType) { appRegistryMimeType -> val appProviders = appRegistryMimeType?.appProviders menu?.let { openInWebProviders = addOpenInWebMenuOptions(it, openInWebProviders, appProviders) } } + } - // Observe the menu filtered options for a single file + private fun observeMenuOptionsSingleFile() { collectLatestLifecycleFlow(mainFileListViewModel.menuOptionsSingleFile) { menuOptions -> fileSingleFile?.let { file -> val fileOptionsBottomSheetSingleFile = layoutInflater.inflate(R.layout.file_options_bottom_sheet_fragment, null) @@ -471,119 +519,124 @@ class MainFileListFragment : Fragment(), fileOptionsBottomSheetSingleFileLayout = fileOptionsBottomSheetSingleFile.findViewById(R.id.file_options_bottom_sheet_layout) menuOptions.forEach { menuOption -> - val fileOptionItemView = BottomSheetFragmentItemView(requireContext()) - fileOptionItemView.apply { - title = if (menuOption.toResId() == R.id.action_open_file_with && !file.hasWritePermission) { - getString(R.string.actionbar_open_with_read_only) - } else { - getString(menuOption.toStringResId()) + setMenuOption(menuOption, file, dialog) + } + // Disable drag gesture + fileOptionsBottomSheetSingleFileBehavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() { + override fun onStateChanged(bottomSheet: View, newState: Int) { + if (newState == BottomSheetBehavior.STATE_DRAGGING) { + fileOptionsBottomSheetSingleFileBehavior.state = BottomSheetBehavior.STATE_EXPANDED } - itemIcon = ResourcesCompat.getDrawable(resources, menuOption.toDrawableResId(), null) - setOnClickListener { - when (menuOption) { - FileMenuOption.SELECT_ALL -> { - // Not applicable here - } + } - FileMenuOption.SELECT_INVERSE -> { - // Not applicable here - } + override fun onSlide(bottomSheet: View, slideOffset: Float) {} + }) + dialog.setOnShowListener { fileOptionsBottomSheetSingleFileBehavior.peekHeight = fileOptionsBottomSheetSingleFile.measuredHeight } + dialog.show() + mainFileListViewModel.getAppRegistryForMimeType(file.mimeType, isMultiselection = false) + } + } + } - FileMenuOption.DOWNLOAD, FileMenuOption.SYNC -> { - syncFiles(listOf(file)) - } + private fun setMenuOption(menuOption: FileMenuOption, file: OCFile, dialog: BottomSheetDialog) { + val fileOptionItemView = BottomSheetFragmentItemView(requireContext()) + fileOptionItemView.apply { + title = if (menuOption.toResId() == R.id.action_open_file_with && !file.hasWritePermission) { + getString(R.string.actionbar_open_with_read_only) + } else { + getString(menuOption.toStringResId()) + } + itemIcon = ResourcesCompat.getDrawable(resources, menuOption.toDrawableResId(), null) + setOnClickListener { + when (menuOption) { + FileMenuOption.SELECT_ALL -> { + // Not applicable here + } - FileMenuOption.RENAME -> { - val dialogRename = RenameFileDialogFragment.newInstance(file) - dialogRename.show(requireActivity().supportFragmentManager, FRAGMENT_TAG_RENAME_FILE) - } + FileMenuOption.SELECT_INVERSE -> { + // Not applicable here + } - FileMenuOption.MOVE -> { - val action = Intent(activity, FolderPickerActivity::class.java) - action.putParcelableArrayListExtra(FolderPickerActivity.EXTRA_FILES, arrayListOf(file)) - action.putExtra(FolderPickerActivity.EXTRA_PICKER_MODE, FolderPickerActivity.PickerMode.MOVE) - requireActivity().startActivityForResult(action, FileDisplayActivity.REQUEST_CODE__MOVE_FILES) - } + FileMenuOption.DOWNLOAD, FileMenuOption.SYNC -> { + syncFiles(listOf(file)) + } - FileMenuOption.COPY -> { - val action = Intent(activity, FolderPickerActivity::class.java) - action.putParcelableArrayListExtra(FolderPickerActivity.EXTRA_FILES, arrayListOf(file)) - action.putExtra(FolderPickerActivity.EXTRA_PICKER_MODE, FolderPickerActivity.PickerMode.COPY) - requireActivity().startActivityForResult(action, FileDisplayActivity.REQUEST_CODE__COPY_FILES) - } + FileMenuOption.RENAME -> { + val dialogRename = RenameFileDialogFragment.newInstance(file) + dialogRename.show(requireActivity().supportFragmentManager, FRAGMENT_TAG_RENAME_FILE) + } - FileMenuOption.REMOVE -> { - filesToRemove = listOf(file) - fileOperationsViewModel.showRemoveDialog(filesToRemove) - } + FileMenuOption.MOVE -> { + val action = Intent(activity, FolderPickerActivity::class.java) + action.putParcelableArrayListExtra(FolderPickerActivity.EXTRA_FILES, arrayListOf(file)) + action.putExtra(FolderPickerActivity.EXTRA_PICKER_MODE, FolderPickerActivity.PickerMode.MOVE) + requireActivity().startActivityForResult(action, FileDisplayActivity.REQUEST_CODE__MOVE_FILES) + } - FileMenuOption.OPEN_WITH -> { - fileActions?.openFile(file) - } + FileMenuOption.COPY -> { + val action = Intent(activity, FolderPickerActivity::class.java) + action.putParcelableArrayListExtra(FolderPickerActivity.EXTRA_FILES, arrayListOf(file)) + action.putExtra(FolderPickerActivity.EXTRA_PICKER_MODE, FolderPickerActivity.PickerMode.COPY) + requireActivity().startActivityForResult(action, FileDisplayActivity.REQUEST_CODE__COPY_FILES) + } - FileMenuOption.CANCEL_SYNC -> { - fileActions?.cancelFileTransference(arrayListOf(file)) - } + FileMenuOption.REMOVE -> { + filesToRemove = listOf(file) + fileOperationsViewModel.showRemoveDialog(filesToRemove) + } - FileMenuOption.SHARE -> { - fileActions?.onShareFileClicked(file) - } + FileMenuOption.OPEN_WITH -> { + fileActions?.openFile(file) + } - FileMenuOption.DETAILS -> { - fileActions?.showDetails(file) - } + FileMenuOption.CANCEL_SYNC -> { + fileActions?.cancelFileTransference(arrayListOf(file)) + } - FileMenuOption.SEND -> { - if (!file.isAvailableLocally) { // Download the file - Timber.d("${file.remotePath} : File must be downloaded") - fileActions?.initDownloadForSending(file) - } else { - fileActions?.sendDownloadedFile(file) - } - } + FileMenuOption.SHARE -> { + fileActions?.onShareFileClicked(file) + } - FileMenuOption.SET_AV_OFFLINE -> { - fileOperationsViewModel.performOperation(FileOperation.SetFilesAsAvailableOffline(listOf(file))) - if (file.isFolder) { - fileOperationsViewModel.performOperation( - FileOperation.SynchronizeFolderOperation( - folderToSync = file, - accountName = file.owner, - isActionSetFolderAvailableOfflineOrSynchronize = true, - ) - ) - } else { - fileOperationsViewModel.performOperation(FileOperation.SynchronizeFileOperation(file, file.owner)) - } - } + FileMenuOption.DETAILS -> { + fileActions?.showDetails(file) + } - FileMenuOption.UNSET_AV_OFFLINE -> { - fileOperationsViewModel.performOperation(FileOperation.UnsetFilesAsAvailableOffline(listOf(file))) - } - } - dialog.hide() - dialog.dismiss() + FileMenuOption.SEND -> { + if (!file.isAvailableLocally) { // Download the file + Timber.d("${file.remotePath} : File must be downloaded") + fileActions?.initDownloadForSending(file) + } else { + fileActions?.sendDownloadedFile(file) } } - fileOptionsBottomSheetSingleFileLayout!!.addView(fileOptionItemView) - } - // Disable drag gesture - fileOptionsBottomSheetSingleFileBehavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() { - override fun onStateChanged(bottomSheet: View, newState: Int) { - if (newState == BottomSheetBehavior.STATE_DRAGGING) { - fileOptionsBottomSheetSingleFileBehavior.state = BottomSheetBehavior.STATE_EXPANDED + + FileMenuOption.SET_AV_OFFLINE -> { + fileOperationsViewModel.performOperation(FileOperation.SetFilesAsAvailableOffline(listOf(file))) + if (file.isFolder) { + fileOperationsViewModel.performOperation( + FileOperation.SynchronizeFolderOperation( + folderToSync = file, + accountName = file.owner, + isActionSetFolderAvailableOfflineOrSynchronize = true, + ) + ) + } else { + fileOperationsViewModel.performOperation(FileOperation.SynchronizeFileOperation(file, file.owner)) } } - override fun onSlide(bottomSheet: View, slideOffset: Float) {} - }) - dialog.setOnShowListener { fileOptionsBottomSheetSingleFileBehavior.peekHeight = fileOptionsBottomSheetSingleFile.measuredHeight } - dialog.show() - mainFileListViewModel.getAppRegistryForMimeType(file.mimeType, isMultiselection = false) + FileMenuOption.UNSET_AV_OFFLINE -> { + fileOperationsViewModel.performOperation(FileOperation.UnsetFilesAsAvailableOffline(listOf(file))) + } + } + dialog.hide() + dialog.dismiss() } } + fileOptionsBottomSheetSingleFileLayout!!.addView(fileOptionItemView) + } - // Observe the app registry for a single file + private fun observeAppRegistryMimeTypeSingleFile() { collectLatestLifecycleFlow(mainFileListViewModel.appRegistryMimeTypeSingleFile) { appRegistryMimeType -> fileSingleFile?.let { file -> val appProviders = appRegistryMimeType?.appProviders @@ -609,8 +662,19 @@ class MainFileListFragment : Fragment(), } fileSingleFile = null } + } - // Observe the file list UI state + private suspend fun getDrawableFromUrl(context: Context, url: String): Drawable? { + return withContext(Dispatchers.IO) { + Glide.with(context) + .load(url) + .fitCenter() + .submit() + .get() + } + } + + private fun observeFileListUiState() { collectLatestLifecycleFlow(mainFileListViewModel.fileListUiState) { fileListUiState -> if (fileListUiState !is MainFileListViewModel.FileListUiState.Success) return@collectLatestLifecycleFlow @@ -645,9 +709,9 @@ class MainFileListFragment : Fragment(), actionMode?.invalidate() } + } - /* FileOperationsViewModel observables */ - // Observe the refresh folder operation + private fun observeRefreshFolder() { fileOperationsViewModel.refreshFolderLiveData.observe(viewLifecycleOwner) { binding.syncProgressBar.isIndeterminate = it.peekContent().isLoading binding.swipeRefreshMainFileList.isRefreshing = it.peekContent().isLoading @@ -657,8 +721,9 @@ class MainFileListFragment : Fragment(), hideRefreshFab() } + } - // Observe the create file with app provider operation + private fun observeCreateFileWithAppProvider() { collectLatestLifecycleFlow(fileOperationsViewModel.createFileWithAppProviderFlow) { val uiResult = it?.peekContent() if (uiResult is UIResult.Error) { @@ -675,7 +740,9 @@ class MainFileListFragment : Fragment(), } } } + } + private fun observeCheckIfFileIsLocalAndNotAvailableOffline() { collectLatestLifecycleFlow(fileOperationsViewModel.checkIfFileIsLocalAndNotAvailableOfflineSharedFlow) { val fileActivity = (requireActivity() as FileActivity) when (it) { @@ -691,20 +758,6 @@ class MainFileListFragment : Fragment(), } } } - - /* TransfersViewModel observables */ - observeTransfers() - - } - - private suspend fun getDrawableFromUrl(context: Context, url: String): Drawable? { - return withContext(Dispatchers.IO) { - Glide.with(context) - .load(url) - .fitCenter() - .submit() - .get() - } } private fun observeTransfers() { @@ -1157,91 +1210,102 @@ class MainFileListFragment : Fragment(), */ @SuppressLint("UseRequireInsteadOfGet") private fun onFileActionChosen(menuId: Int?): Boolean { + var handled: Boolean val checkedFilesWithSyncInfo = fileListAdapter.getCheckedItems() as ArrayList if (checkedFilesWithSyncInfo.isEmpty()) { return false } else if (checkedFilesWithSyncInfo.size == 1) { - /// action only possible on a single file + /// Action possible on a single file val singleFile = checkedFilesWithSyncInfo.first().file + handled = onSingleFileActionChosen(menuId, singleFile) + } - openInWebProviders.forEach { (openInWebProviderName, menuItemId) -> - if (menuItemId == menuId) { - mainFileListViewModel.openInWeb(singleFile.remoteId!!, openInWebProviderName) - return true - } + /// Actions possible on a batch of files + val checkedFiles = checkedFilesWithSyncInfo.map { it.file } as ArrayList + handled = onCheckedFilesActionChosen(menuId, checkedFiles) + return handled + } + + private fun onSingleFileActionChosen(menuId: Int?, singleFile: OCFile): Boolean { + openInWebProviders.forEach { (openInWebProviderName, menuItemId) -> + if (menuItemId == menuId) { + mainFileListViewModel.openInWeb(singleFile.remoteId!!, openInWebProviderName) + return true } + } - when (menuId) { - R.id.action_share_file -> { - fileActions?.onShareFileClicked(singleFile) - fileListAdapter.clearSelection() - updateActionModeAfterTogglingSelected() - return true - } + when (menuId) { + R.id.action_share_file -> { + fileActions?.onShareFileClicked(singleFile) + fileListAdapter.clearSelection() + updateActionModeAfterTogglingSelected() + return true + } - R.id.action_open_file_with -> { - fileActions?.openFile(singleFile) - fileListAdapter.clearSelection() - updateActionModeAfterTogglingSelected() - return true - } + R.id.action_open_file_with -> { + fileActions?.openFile(singleFile) + fileListAdapter.clearSelection() + updateActionModeAfterTogglingSelected() + return true + } - R.id.action_rename_file -> { - val dialog = RenameFileDialogFragment.newInstance(singleFile) - dialog.show(requireActivity().supportFragmentManager, FRAGMENT_TAG_RENAME_FILE) - fileListAdapter.clearSelection() - updateActionModeAfterTogglingSelected() - return true - } + R.id.action_rename_file -> { + val dialog = RenameFileDialogFragment.newInstance(singleFile) + dialog.show(requireActivity().supportFragmentManager, FRAGMENT_TAG_RENAME_FILE) + fileListAdapter.clearSelection() + updateActionModeAfterTogglingSelected() + return true + } - R.id.action_see_details -> { - fileListAdapter.clearSelection() - updateActionModeAfterTogglingSelected() - fileActions?.showDetails(singleFile) - return true - } + R.id.action_see_details -> { + fileListAdapter.clearSelection() + updateActionModeAfterTogglingSelected() + fileActions?.showDetails(singleFile) + return true + } - R.id.action_sync_file -> { - syncFiles(listOf(singleFile)) - return true - } + R.id.action_sync_file -> { + syncFiles(listOf(singleFile)) + return true + } - R.id.action_send_file -> { - //Obtain the file - if (!singleFile.isAvailableLocally) { // Download the file - Timber.d("%s : File must be downloaded", singleFile.remotePath) - fileActions?.initDownloadForSending(singleFile) - } else { - fileActions?.sendDownloadedFile(singleFile) - } - return true + R.id.action_send_file -> { + //Obtain the file + if (!singleFile.isAvailableLocally) { // Download the file + Timber.d("%s : File must be downloaded", singleFile.remotePath) + fileActions?.initDownloadForSending(singleFile) + } else { + fileActions?.sendDownloadedFile(singleFile) } + return true + } - R.id.action_set_available_offline -> { - fileOperationsViewModel.performOperation(FileOperation.SetFilesAsAvailableOffline(listOf(singleFile))) - if (singleFile.isFolder) { - fileOperationsViewModel.performOperation( - FileOperation.SynchronizeFolderOperation( - folderToSync = singleFile, - accountName = singleFile.owner, - isActionSetFolderAvailableOfflineOrSynchronize = true, - ) + R.id.action_set_available_offline -> { + fileOperationsViewModel.performOperation(FileOperation.SetFilesAsAvailableOffline(listOf(singleFile))) + if (singleFile.isFolder) { + fileOperationsViewModel.performOperation( + FileOperation.SynchronizeFolderOperation( + folderToSync = singleFile, + accountName = singleFile.owner, + isActionSetFolderAvailableOfflineOrSynchronize = true, ) - } else { - fileOperationsViewModel.performOperation(FileOperation.SynchronizeFileOperation(singleFile, singleFile.owner)) - } - return true + ) + } else { + fileOperationsViewModel.performOperation(FileOperation.SynchronizeFileOperation(singleFile, singleFile.owner)) } + return true + } - R.id.action_unset_available_offline -> { - fileOperationsViewModel.performOperation(FileOperation.UnsetFilesAsAvailableOffline(listOf(singleFile))) - } + R.id.action_unset_available_offline -> { + fileOperationsViewModel.performOperation(FileOperation.UnsetFilesAsAvailableOffline(listOf(singleFile))) + return true } } + return false + } - /// Actions possible on a batch of files - val checkedFiles = checkedFilesWithSyncInfo.map { it.file } as ArrayList + private fun onCheckedFilesActionChosen(menuId: Int?, checkedFiles: ArrayList): Boolean { when (menuId) { R.id.file_action_select_all -> { fileListAdapter.selectAll() @@ -1313,7 +1377,6 @@ class MainFileListFragment : Fragment(), return true } } - return false } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/security/SettingsSecurityFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/security/SettingsSecurityFragment.kt index a883999ac51..6a84ed1e116 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/security/SettingsSecurityFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/security/SettingsSecurityFragment.kt @@ -107,7 +107,6 @@ class SettingsSecurityFragment : PreferenceFragmentCompat() { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.settings_security, rootKey) - screenSecurity = findPreference(SCREEN_SECURITY) prefPasscode = findPreference(PassCodeActivity.PREFERENCE_SET_PASSCODE) prefPattern = findPreference(PatternActivity.PREFERENCE_SET_PATTERN) @@ -173,9 +172,7 @@ class SettingsSecurityFragment : PreferenceFragmentCompat() { screenSecurity?.removePreferenceFromScreen(prefBiometric) } else { // Disable biometric lock if Passcode or Pattern locks are disabled - if (prefPasscode?.isChecked == false && prefPattern?.isChecked == false) { - disableBiometric() - } + if (prefPasscode?.isChecked == false && prefPattern?.isChecked == false) { disableBiometric() } prefBiometric?.setOnPreferenceChangeListener { _: Preference?, newValue: Any -> val incomingValue = newValue as Boolean @@ -191,9 +188,7 @@ class SettingsSecurityFragment : PreferenceFragmentCompat() { } // Lock application - if (prefPasscode?.isChecked == false && prefPattern?.isChecked == false) { - prefLockApplication?.isEnabled = false - } + if (prefPasscode?.isChecked == false && prefPattern?.isChecked == false) { prefLockApplication?.isEnabled = false } // Lock access from document provider prefLockAccessDocumentProvider?.setOnPreferenceChangeListener { _: Preference?, newValue: Any -> diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/UsersAndGroupsSearchProvider.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/UsersAndGroupsSearchProvider.kt index a5a3d9d3011..82b46a959b0 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/UsersAndGroupsSearchProvider.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/UsersAndGroupsSearchProvider.kt @@ -167,15 +167,9 @@ class UsersAndGroupsSearchProvider : ContentProvider() { var dataUri: Uri? = null var count = 0 - val userBaseUri = Uri.Builder().scheme(CONTENT).authority( - suggestAuthority!! + DATA_USER_SUFFIX - ).build() - val groupBaseUri = Uri.Builder().scheme(CONTENT).authority( - suggestAuthority!! + DATA_GROUP_SUFFIX - ).build() - val remoteBaseUri = Uri.Builder().scheme(CONTENT).authority( - suggestAuthority!! + DATA_REMOTE_SUFFIX - ).build() + val userBaseUri = Uri.Builder().scheme(CONTENT).authority(suggestAuthority!! + DATA_USER_SUFFIX).build() + val groupBaseUri = Uri.Builder().scheme(CONTENT).authority(suggestAuthority!! + DATA_GROUP_SUFFIX).build() + val remoteBaseUri = Uri.Builder().scheme(CONTENT).authority(suggestAuthority!! + DATA_REMOTE_SUFFIX).build() val federatedShareAllowed = capabilities?.filesSharingFederationOutgoing?.isTrue ?: false @@ -184,9 +178,7 @@ class UsersAndGroupsSearchProvider : ContentProvider() { val fullName = AccountManager.get(context).getUserData(account, KEY_DISPLAY_NAME) while (namesIt.hasNext()) { item = namesIt.next() - if (item.label == userName || item.label == fullName && item.shareType == ShareType.USER) { - continue - } + if (item.label == userName || item.label == fullName && item.shareType == ShareType.USER) { continue } var userName = item.label val type = item.shareType val shareWith = item.shareWith @@ -212,15 +204,10 @@ class UsersAndGroupsSearchProvider : ContentProvider() { ShareType.FEDERATED -> { if (federatedShareAllowed) { icon = R.drawable.ic_user - displayName = if (userName == shareWith) { - context?.getString(R.string.share_remote_clarification, userName) - } else { - val uriSplitted = - shareWith.split("@".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() - context?.getString( - R.string.share_known_remote_clarification, userName, - uriSplitted[uriSplitted.size - 1] - ) + displayName = if (userName == shareWith) { context?.getString(R.string.share_remote_clarification, userName) } + else { + val uriSplitted = shareWith.split("@".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + context?.getString(R.string.share_known_remote_clarification, userName, uriSplitted[uriSplitted.size - 1]) } dataUri = Uri.withAppendedPath(remoteBaseUri, shareWith) } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/transfers/TransfersAdapter.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/transfers/TransfersAdapter.kt index 0c163464b0a..cd50af79117 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/transfers/TransfersAdapter.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/transfers/TransfersAdapter.kt @@ -77,137 +77,11 @@ class TransfersAdapter( when (holder) { is TransferItemViewHolder -> { val transferItem = getItem(position) as TransferItem - holder.binding.apply { - val remoteFile = File(transferItem.transfer.remotePath) - - var fileName = remoteFile.name - if (fileName.isEmpty()) { - fileName = File.separator - } - uploadName.text = fileName - - transferItem.space?.let { - spacePathLine.spaceName.isVisible = true - spacePathLine.spaceIcon.isVisible = true - if (it.isPersonal) { - spacePathLine.spaceIcon.setImageResource(R.drawable.ic_folder) - spacePathLine.spaceName.setText(R.string.bottom_nav_personal) - } else { - spacePathLine.spaceName.text = it.name - } - } - - remoteFile.parent?.let { - spacePathLine.path.text = if (it.endsWith("${OCFile.PATH_SEPARATOR}")) it else "$it${OCFile.PATH_SEPARATOR}" - } - - uploadFileSize.text = DisplayUtils.bytesToHumanReadable(transferItem.transfer.fileSize, holder.itemView.context, true) - - uploadDate.isVisible = - transferItem.transfer.transferEndTimestamp != null && transferItem.transfer.status != TransferStatus.TRANSFER_FAILED - transferItem.transfer.transferEndTimestamp?.let { - val dateString = DisplayUtils.getRelativeDateTimeString( - holder.itemView.context, - it, - DateUtils.SECOND_IN_MILLIS, - DateUtils.WEEK_IN_MILLIS, - 0 - ) - uploadDate.text = ", $dateString" - } - - try { - val account = AccountUtils.getOwnCloudAccountByName(holder.itemView.context, transferItem.transfer.accountName) - val oca = OwnCloudAccount(account, holder.itemView.context) - val accountName = oca.displayName + " @ " + - DisplayUtils.convertIdn(account.name.substring(account.name.lastIndexOf("@") + 1), false) - uploadAccount.text = accountName - } catch (e: Exception) { - Timber.w("Couldn't get display name for account, using old style") - uploadAccount.text = transferItem.transfer.accountName - } - - uploadStatus.isVisible = transferItem.transfer.status != TransferStatus.TRANSFER_SUCCEEDED - uploadStatus.text = " — " + holder.itemView.context.getString(transferItem.transfer.statusToStringRes()) - - Glide.with(holder.itemView) - .load(transferItem.transfer.localPath) - .diskCacheStrategy(DiskCacheStrategy.ALL) - .placeholder( - MimetypeIconUtil.getFileTypeIconId( - MimetypeIconUtil.getBestMimeTypeByFilename(transferItem.transfer.localPath), - fileName - ) - ) - .into(thumbnail) - - uploadRightButton.isVisible = transferItem.transfer.status != TransferStatus.TRANSFER_SUCCEEDED - - uploadProgressBar.isVisible = transferItem.transfer.status == TransferStatus.TRANSFER_IN_PROGRESS - - holder.itemView.setOnClickListener(null) - - when (transferItem.transfer.status) { - TransferStatus.TRANSFER_IN_PROGRESS, TransferStatus.TRANSFER_QUEUED -> { - uploadRightButton.apply { - setImageResource(R.drawable.ic_action_cancel_grey) - setOnClickListener { - cancel(transferItem.transfer) - } - } - } - TransferStatus.TRANSFER_FAILED -> { - uploadRightButton.apply { - setImageResource(R.drawable.ic_action_delete_grey) - setOnClickListener { - cancel(transferItem.transfer) - } - } - holder.itemView.setOnClickListener { - retry(transferItem.transfer) - } - holder.binding.ListItemLayout.isClickable = true - holder.binding.ListItemLayout.isFocusable = true - } - TransferStatus.TRANSFER_SUCCEEDED -> { - // Nothing to do - } - } - } + onBindTransferItemViewHolder(holder, transferItem) } is HeaderItemViewHolder -> { val headerItem = getItem(position) as HeaderItem - holder.binding.apply { - uploadListGroupName.text = holder.itemView.context.getString(headerTitleStringRes(headerItem.status)) - - val stringResFileCount = - if (headerItem.numberTransfers == 1) R.string.uploads_view_group_file_count_single else R.string.uploads_view_group_file_count - val fileCountText: String = String.format(holder.itemView.context.getString(stringResFileCount), headerItem.numberTransfers) - textViewFileCount.text = fileCountText - - uploadListGroupButtonClear.isVisible = headerItem.status == TransferStatus.TRANSFER_FAILED || - headerItem.status == TransferStatus.TRANSFER_SUCCEEDED - uploadListGroupButtonRetry.isVisible = headerItem.status == TransferStatus.TRANSFER_FAILED - - when (headerItem.status) { - TransferStatus.TRANSFER_FAILED -> { - uploadListGroupButtonClear.setOnClickListener { - clearFailed() - } - uploadListGroupButtonRetry.setOnClickListener { - retryFailed() - } - } - TransferStatus.TRANSFER_SUCCEEDED -> { - uploadListGroupButtonClear.setOnClickListener { - clearSuccessful() - } - } - TransferStatus.TRANSFER_QUEUED, TransferStatus.TRANSFER_IN_PROGRESS -> { - // Nothing to do - } - } - } + onBindHeaderItemViewHolder(holder, headerItem) } } @@ -226,6 +100,142 @@ class TransfersAdapter( } + private fun onBindTransferItemViewHolder(holder: TransferItemViewHolder, transferItem: TransferItem) { + holder.binding.apply { + val remoteFile = File(transferItem.transfer.remotePath) + + var fileName = remoteFile.name + if (fileName.isEmpty()) { + fileName = File.separator + } + uploadName.text = fileName + + transferItem.space?.let { + spacePathLine.spaceName.isVisible = true + spacePathLine.spaceIcon.isVisible = true + if (it.isPersonal) { + spacePathLine.spaceIcon.setImageResource(R.drawable.ic_folder) + spacePathLine.spaceName.setText(R.string.bottom_nav_personal) + } else { + spacePathLine.spaceName.text = it.name + } + } + + remoteFile.parent?.let { + spacePathLine.path.text = if (it.endsWith("${OCFile.PATH_SEPARATOR}")) it else "$it${OCFile.PATH_SEPARATOR}" + } + + uploadFileSize.text = DisplayUtils.bytesToHumanReadable(transferItem.transfer.fileSize, holder.itemView.context, true) + + uploadDate.isVisible = + transferItem.transfer.transferEndTimestamp != null && transferItem.transfer.status != TransferStatus.TRANSFER_FAILED + transferItem.transfer.transferEndTimestamp?.let { + val dateString = DisplayUtils.getRelativeDateTimeString( + holder.itemView.context, + it, + DateUtils.SECOND_IN_MILLIS, + DateUtils.WEEK_IN_MILLIS, + 0 + ) + uploadDate.text = ", $dateString" + } + + try { + val account = AccountUtils.getOwnCloudAccountByName(holder.itemView.context, transferItem.transfer.accountName) + val oca = OwnCloudAccount(account, holder.itemView.context) + val accountName = oca.displayName + " @ " + + DisplayUtils.convertIdn(account.name.substring(account.name.lastIndexOf("@") + 1), false) + uploadAccount.text = accountName + } catch (e: Exception) { + Timber.w("Couldn't get display name for account, using old style") + uploadAccount.text = transferItem.transfer.accountName + } + + uploadStatus.isVisible = transferItem.transfer.status != TransferStatus.TRANSFER_SUCCEEDED + uploadStatus.text = " — " + holder.itemView.context.getString(transferItem.transfer.statusToStringRes()) + + Glide.with(holder.itemView) + .load(transferItem.transfer.localPath) + .diskCacheStrategy(DiskCacheStrategy.ALL) + .placeholder( + MimetypeIconUtil.getFileTypeIconId( + MimetypeIconUtil.getBestMimeTypeByFilename(transferItem.transfer.localPath), + fileName + ) + ) + .into(thumbnail) + + uploadRightButton.isVisible = transferItem.transfer.status != TransferStatus.TRANSFER_SUCCEEDED + + uploadProgressBar.isVisible = transferItem.transfer.status == TransferStatus.TRANSFER_IN_PROGRESS + + holder.itemView.setOnClickListener(null) + + when (transferItem.transfer.status) { + TransferStatus.TRANSFER_IN_PROGRESS, TransferStatus.TRANSFER_QUEUED -> { + uploadRightButton.apply { + setImageResource(R.drawable.ic_action_cancel_grey) + setOnClickListener { + cancel(transferItem.transfer) + } + } + } + + TransferStatus.TRANSFER_FAILED -> { + uploadRightButton.apply { + setImageResource(R.drawable.ic_action_delete_grey) + setOnClickListener { + cancel(transferItem.transfer) + } + } + holder.itemView.setOnClickListener { + retry(transferItem.transfer) + } + holder.binding.ListItemLayout.isClickable = true + holder.binding.ListItemLayout.isFocusable = true + } + + TransferStatus.TRANSFER_SUCCEEDED -> { + // Nothing to do + } + } + } + } + + private fun onBindHeaderItemViewHolder(holder: HeaderItemViewHolder, headerItem: HeaderItem) { + holder.binding.apply { + uploadListGroupName.text = holder.itemView.context.getString(headerTitleStringRes(headerItem.status)) + + val stringResFileCount = + if (headerItem.numberTransfers == 1) R.string.uploads_view_group_file_count_single else R.string.uploads_view_group_file_count + val fileCountText: String = String.format(holder.itemView.context.getString(stringResFileCount), headerItem.numberTransfers) + textViewFileCount.text = fileCountText + + uploadListGroupButtonClear.isVisible = headerItem.status == TransferStatus.TRANSFER_FAILED || + headerItem.status == TransferStatus.TRANSFER_SUCCEEDED + uploadListGroupButtonRetry.isVisible = headerItem.status == TransferStatus.TRANSFER_FAILED + + when (headerItem.status) { + TransferStatus.TRANSFER_FAILED -> { + uploadListGroupButtonClear.setOnClickListener { + clearFailed() + } + uploadListGroupButtonRetry.setOnClickListener { + retryFailed() + } + } + TransferStatus.TRANSFER_SUCCEEDED -> { + uploadListGroupButtonClear.setOnClickListener { + clearSuccessful() + } + } + TransferStatus.TRANSFER_QUEUED, TransferStatus.TRANSFER_IN_PROGRESS -> { + // Nothing to do + } + } + } + } + private fun headerTitleStringRes(status: TransferStatus): Int { return when (status) { TransferStatus.TRANSFER_IN_PROGRESS -> R.string.uploads_view_group_current_uploads diff --git a/owncloudApp/src/main/java/com/owncloud/android/providers/FileContentProvider.kt b/owncloudApp/src/main/java/com/owncloud/android/providers/FileContentProvider.kt index f00709fa4f8..db8409ebdba 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/providers/FileContentProvider.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/providers/FileContentProvider.kt @@ -482,6 +482,7 @@ class FileContentProvider(val executors: Executors = Executors()) : ContentProvi createCameraUploadsSyncTable(db) } + @Suppress("LongMethod") override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { Timber.i("SQL : Entering in onUpgrade") var upgraded = false From 2de9701096cd16541dda1d69a7fd097e7b09575f Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Wed, 11 Dec 2024 14:30:44 +0100 Subject: [PATCH 17/74] refactor: fix for KtLint report --- .../implementation/OCLocalFileDataSourceTest.kt | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/owncloudData/src/test/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSourceTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSourceTest.kt index 5c36eef73ff..45d50196eb3 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSourceTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSourceTest.kt @@ -436,16 +436,16 @@ class OCLocalFileDataSourceTest { } @Test - fun `getFilesWithSyncInfoAvailableOfflineFromAccountAsFlow returns a Flow with an empty list when DAO returns a Flow with an empty list`() - = runTest { - every { fileDao.getFilesWithSyncInfoAvailableOfflineFromAccountAsFlow(OC_ACCOUNT_NAME) } returns flowOf(emptyList()) + fun `getFilesWithSyncInfoAvailableOfflineFromAccountAsFlow returns a Flow with an empty list when DAO returns a Flow with an empty list`() = + runTest { + every { fileDao.getFilesWithSyncInfoAvailableOfflineFromAccountAsFlow(OC_ACCOUNT_NAME) } returns flowOf(emptyList()) - val result = ocLocalFileDataSource.getFilesWithSyncInfoAvailableOfflineFromAccountAsFlow(OC_ACCOUNT_NAME).first() + val result = ocLocalFileDataSource.getFilesWithSyncInfoAvailableOfflineFromAccountAsFlow(OC_ACCOUNT_NAME).first() - assertEquals(emptyList(), result) + assertEquals(emptyList(), result) - verify(exactly = 1) { fileDao.getFilesWithSyncInfoAvailableOfflineFromAccountAsFlow(OC_ACCOUNT_NAME) } - } + verify(exactly = 1) { fileDao.getFilesWithSyncInfoAvailableOfflineFromAccountAsFlow(OC_ACCOUNT_NAME) } + } @Test fun `getFilesAvailableOfflineFromAccount returns a list of OCFile`() { From dc888b828776a3c83ecd8b68d51ea029eb5fd5b1 Mon Sep 17 00:00:00 2001 From: joragua Date: Wed, 11 Dec 2024 14:44:31 +0100 Subject: [PATCH 18/74] refactor: remove unused private members --- .../renamefile/RenameFileDialogFragment.kt | 12 --------- .../sharees/UsersAndGroupsSearchProvider.kt | 4 +-- .../android/workers/DownloadFileWorker.kt | 25 ------------------- 3 files changed, 2 insertions(+), 39 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/renamefile/RenameFileDialogFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/renamefile/RenameFileDialogFragment.kt index 1a284c06b94..b8ff0d8a7f9 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/renamefile/RenameFileDialogFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/renamefile/RenameFileDialogFragment.kt @@ -34,7 +34,6 @@ import com.google.android.material.textfield.TextInputLayout import com.owncloud.android.R import com.owncloud.android.domain.files.model.OCFile import com.owncloud.android.extensions.avoidScreenshotsIfNeeded -import com.owncloud.android.extensions.showMessageInSnackbar import com.owncloud.android.presentation.files.operations.FileOperation import com.owncloud.android.presentation.files.operations.FileOperationsViewModel import com.owncloud.android.utils.PreferenceUtils @@ -141,17 +140,6 @@ class RenameFileDialogFragment : DialogFragment(), DialogInterface.OnClickListen } } - /** - * Show a temporary message in a Snackbar bound to the content view of the parent Activity - * - * @param messageResource Message to show. - */ - private fun showSnackMessage(messageResource: Int) { - showMessageInSnackbar( - message = getString(messageResource) - ) - } - companion object { const val FRAGMENT_TAG_RENAME_FILE = "RENAME_FILE_FRAGMENT" private const val ARG_TARGET_FILE = "TARGET_FILE" diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/UsersAndGroupsSearchProvider.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/UsersAndGroupsSearchProvider.kt index 82b46a959b0..08bae7336e4 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/UsersAndGroupsSearchProvider.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/UsersAndGroupsSearchProvider.kt @@ -204,8 +204,8 @@ class UsersAndGroupsSearchProvider : ContentProvider() { ShareType.FEDERATED -> { if (federatedShareAllowed) { icon = R.drawable.ic_user - displayName = if (userName == shareWith) { context?.getString(R.string.share_remote_clarification, userName) } - else { + displayName = if (userName == shareWith) { context?.getString(R.string.share_remote_clarification, userName) + } else { val uriSplitted = shareWith.split("@".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() context?.getString(R.string.share_known_remote_clarification, userName, uriSplitted[uriSplitted.size - 1]) } diff --git a/owncloudApp/src/main/java/com/owncloud/android/workers/DownloadFileWorker.kt b/owncloudApp/src/main/java/com/owncloud/android/workers/DownloadFileWorker.kt index b8fdb94208d..e6ac9b0497f 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/workers/DownloadFileWorker.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/workers/DownloadFileWorker.kt @@ -53,11 +53,7 @@ import com.owncloud.android.presentation.authentication.EXTRA_ACCOUNT import com.owncloud.android.presentation.authentication.EXTRA_ACTION import com.owncloud.android.presentation.authentication.LoginActivity import com.owncloud.android.presentation.transfers.TransferOperation.Download -import com.owncloud.android.ui.activity.FileActivity -import com.owncloud.android.ui.activity.FileDisplayActivity import com.owncloud.android.ui.errorhandling.ErrorMessageAdapter -import com.owncloud.android.ui.preview.PreviewImageActivity -import com.owncloud.android.ui.preview.PreviewImageFragment.Companion.canBePreviewed import com.owncloud.android.utils.DOWNLOAD_NOTIFICATION_CHANNEL_ID import com.owncloud.android.utils.DOWNLOAD_NOTIFICATION_ID_DEFAULT import com.owncloud.android.utils.FileStorageUtils @@ -309,27 +305,6 @@ class DownloadFileWorker( ) } - private fun composePendingIntentToPreviewFile(): PendingIntent { - /// includes a pending intent in the notification showing the details view of the file - val showDetailsIntent: Intent = - if (canBePreviewed(ocFile)) { - Intent(appContext, PreviewImageActivity::class.java) - } else { - Intent(appContext, FileDisplayActivity::class.java) - }.apply { - putExtra(FileActivity.EXTRA_FILE, ocFile) - putExtra(FileActivity.EXTRA_ACCOUNT, account) - flags = Intent.FLAG_ACTIVITY_CLEAR_TOP - } - - return PendingIntent.getActivity( - appContext, - System.currentTimeMillis().toInt(), - showDetailsIntent, - PendingIntent.FLAG_IMMUTABLE - ) - } - private fun getClientForThisDownload(): OwnCloudClient = SingleSessionManager.getDefaultSingleton() .getClientFor(OwnCloudAccount(AccountUtils.getOwnCloudAccountByName(appContext, account.name), appContext), appContext) From 8ee550b9a9e8f8b510911ac8c179a9e7f2ab56d5 Mon Sep 17 00:00:00 2001 From: joragua Date: Wed, 11 Dec 2024 16:54:04 +0100 Subject: [PATCH 19/74] refactor: remove unused private properties in module `owncloudApp` --- .../presentation/files/filelist/MainFileListFragment.kt | 1 - .../presentation/sharing/PublicLinkPasswordUtils.kt | 8 ++++---- .../sharing/sharees/UsersAndGroupsSearchProvider.kt | 1 - .../com/owncloud/android/ui/activity/DrawerActivity.kt | 1 - .../owncloud/android/ui/activity/FileDisplayActivity.kt | 1 - .../presentation/sharing/PublicLinkPasswordUtilsTest.kt | 2 +- 6 files changed, 5 insertions(+), 9 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt index 255d8417281..c64b602906d 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt @@ -1620,7 +1620,6 @@ class MainFileListFragment : Fragment(), private const val DIALOG_CREATE_FOLDER = "DIALOG_CREATE_FOLDER" private const val DIALOG_CREATE_SHORTCUT = "DIALOG_CREATE_SHORTCUT" - private const val TAG_SECOND_FRAGMENT = "SECOND_FRAGMENT" private const val FILE_DOCXF_EXTENSION = "docxf" @JvmStatic diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtils.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtils.kt index b64730ba364..2890587b927 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtils.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtils.kt @@ -53,22 +53,22 @@ fun generatePassword( val passwordChars = mutableListOf() // Include the minimum number of digits established by the policy - for (i in 1..minDigits) { + repeat (minDigits) { passwordChars.add(charsetDigits[secureRandom.nextInt(charsetDigits.size)]) } // Include the minimum number of lowercase chars established by the policy - for (i in 1..minLowercaseCharacters) { + repeat (minLowercaseCharacters) { passwordChars.add(charsetLowercase[secureRandom.nextInt(charsetLowercase.size)]) } // Include the minimum number of uppercase chars established by the policy - for (i in 1..minUppercaseCharacters) { + repeat (minUppercaseCharacters) { passwordChars.add(charsetUppercase[secureRandom.nextInt(charsetUppercase.size)]) } // Include the minimum number of special chars established by the policy - for (i in 1..minSpecialCharacters) { + repeat (minSpecialCharacters) { passwordChars.add(charsetSpecial[secureRandom.nextInt(charsetSpecial.size)]) } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/UsersAndGroupsSearchProvider.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/UsersAndGroupsSearchProvider.kt index 08bae7336e4..b7b7e6b4b8c 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/UsersAndGroupsSearchProvider.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/UsersAndGroupsSearchProvider.kt @@ -283,7 +283,6 @@ class UsersAndGroupsSearchProvider : ContentProvider() { private const val SEARCH = 1 - private const val DEFAULT_MIN_CHARACTERS_TO_SEARCH = 4 private const val RESULTS_PER_PAGE = 30 private const val REQUESTED_PAGE = 1 diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.kt index c2aabdddc29..61b0888a6fa 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.kt @@ -613,7 +613,6 @@ abstract class DrawerActivity : ToolbarActivity() { const val TALK_MOBILE_URL = "https://talk.owncloud.com/channel/mobile" const val GITHUB_URL = "https://github.com/owncloud/android/issues/new/choose" const val SURVEY_URL = "https://owncloud.com/android-app-feedback" - private const val KEY_IS_ACCOUNT_CHOOSER_ACTIVE = "IS_ACCOUNT_CHOOSER_ACTIVE" private const val KEY_CHECKED_MENU_ITEM = "CHECKED_MENU_ITEM" } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt index f25f33b00b6..309b1ad24be 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt @@ -2037,7 +2037,6 @@ class FileDisplayActivity : FileActivity(), private const val KEY_WAITING_TO_SEND = "WAITING_TO_SEND" private const val KEY_UPLOAD_HELPER = "FILE_UPLOAD_HELPER" private const val KEY_FILE_LIST_OPTION = "FILE_LIST_OPTION" - private const val MAX_URL_LENGTH = 90 const val MIMETYPE_TEXT_URI_LIST = "text/uri-list" const val KEY_DEEP_LINK_ACCOUNTS_CHECKED = "DEEP_LINK_ACCOUNTS_CHECKED" diff --git a/owncloudApp/src/test/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtilsTest.kt b/owncloudApp/src/test/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtilsTest.kt index c4a2471b72f..ec2d88def49 100644 --- a/owncloudApp/src/test/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtilsTest.kt +++ b/owncloudApp/src/test/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtilsTest.kt @@ -40,7 +40,7 @@ class PublicLinkPasswordUtilsTest { @Test fun `generatePassword creates password fulfilling all policies`() { - for (i in 1..1000) { + repeat (1000) { val password = generatePassword( minChars = minCharacters, maxChars = maxCharacters, From 0f6755c5d14489551031ebf0b572c71f5629acba Mon Sep 17 00:00:00 2001 From: joragua Date: Wed, 11 Dec 2024 16:55:38 +0100 Subject: [PATCH 20/74] refactor: remove unused private properties in module `owncloudComLibrary` --- .../lib/resources/webfinger/responses/WebFingerResponseTest.kt | 2 -- 1 file changed, 2 deletions(-) diff --git a/owncloudComLibrary/src/test/java/com/owncloud/android/lib/resources/webfinger/responses/WebFingerResponseTest.kt b/owncloudComLibrary/src/test/java/com/owncloud/android/lib/resources/webfinger/responses/WebFingerResponseTest.kt index 4b275cd73b7..7b14da998ee 100644 --- a/owncloudComLibrary/src/test/java/com/owncloud/android/lib/resources/webfinger/responses/WebFingerResponseTest.kt +++ b/owncloudComLibrary/src/test/java/com/owncloud/android/lib/resources/webfinger/responses/WebFingerResponseTest.kt @@ -41,9 +41,7 @@ class WebFingerResponseTest { companion object { private const val RESOURCES_PATH = "src/test/responses/com.owncloud.android.lib.resources.webfinger.responses" - private const val EXAMPLE_RESPONSE_JSON = "$RESOURCES_PATH/simple_response.json" private const val TOO_MUCH_INFORMATION_JSON = "$RESOURCES_PATH/to_much_information_response.json" private const val BROKEN_JSON = "$RESOURCES_PATH/broken_response.json" - private const val NOT_CONTAINING_RELEVANT_INFORMATION_JSON = "$RESOURCES_PATH/not_containing_relevant_info_response.json" } } From 14977818bb9485893962a880b2c1c58ab5b0f089 Mon Sep 17 00:00:00 2001 From: joragua Date: Wed, 11 Dec 2024 17:44:07 +0100 Subject: [PATCH 21/74] refactor: replace when by if for binary conditions in module `owncloudApp` --- .../android/extensions/ThrowableExt.kt | 9 +++--- .../authentication/LoginActivity.kt | 26 ++++++++--------- .../android/presentation/common/UIResult.kt | 7 +++-- .../presentation/security/SecurityEnforced.kt | 7 +++-- .../security/passcode/PassCodeActivity.kt | 7 +++-- .../privacypolicy/PrivacyPolicyActivity.kt | 7 +++-- .../presentation/sharing/ShareActivity.kt | 20 ++++++------- .../sharees/UsersAndGroupsSearchProvider.kt | 7 +++-- .../ui/activity/FileDisplayActivity.kt | 13 ++++----- .../PreviewFormatTextFragmentStateAdapter.kt | 7 +++-- .../ui/preview/PreviewImageActivity.kt | 28 +++++++++---------- 11 files changed, 69 insertions(+), 69 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/extensions/ThrowableExt.kt b/owncloudApp/src/main/java/com/owncloud/android/extensions/ThrowableExt.kt index 5dd0282e5f6..c2feb639f63 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/extensions/ThrowableExt.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/extensions/ThrowableExt.kt @@ -106,11 +106,10 @@ fun Throwable.parseError( else -> resources.getString(R.string.common_error_unknown) } - return when { - showJustReason -> { - reason - } - else -> "$genericErrorMessage ${resources.getString(R.string.error_reason)} ${reason.lowercase(Locale.getDefault())}" + return if (showJustReason) { + reason + } else { + "$genericErrorMessage ${resources.getString(R.string.error_reason)} ${reason.lowercase(Locale.getDefault())}" } } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/LoginActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/LoginActivity.kt index 81889dac1c7..0c6cd7850cd 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/LoginActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/LoginActivity.kt @@ -298,13 +298,13 @@ class LoginActivity : AppCompatActivity(), SslUntrustedCertDialog.OnSslUntrusted } private fun getLegacyWebfingerIsError(uiResult: UIResult.Error) { - when (uiResult.error) { - is NoNetworkConnectionException -> binding.webfingerStatusText.run { + if (uiResult.error is NoNetworkConnectionException) { + binding.webfingerStatusText.run { text = getString(R.string.error_no_network_connection) setCompoundDrawablesWithIntrinsicBounds(R.drawable.no_network, 0, 0, 0) } - - else -> binding.webfingerStatusText.run { + } else { + binding.webfingerStatusText.run { text = uiResult.getThrowableOrNull()?.parseError("", resources, true) setCompoundDrawablesWithIntrinsicBounds(R.drawable.common_error, 0, 0, 0) } @@ -616,17 +616,15 @@ class LoginActivity : AppCompatActivity(), SslUntrustedCertDialog.OnSslUntrusted var clientId: String? = null var clientSecret: String? = null - when (val serverInfo = authenticationViewModel.serverInfo.value?.peekContent()?.getStoredData()) { - is ServerInfo.OIDCServer -> { - tokenEndPoint = serverInfo.oidcServerConfiguration.tokenEndpoint - if (serverInfo.oidcServerConfiguration.isTokenEndpointAuthMethodSupportedClientSecretPost()) { - clientId = clientRegistrationInfo?.clientId ?: contextProvider.getString(R.string.oauth2_client_id) - clientSecret = clientRegistrationInfo?.clientSecret ?: contextProvider.getString(R.string.oauth2_client_secret) - } - } - else -> { - tokenEndPoint = "$serverBaseUrl${File.separator}${contextProvider.getString(R.string.oauth2_url_endpoint_access)}" + val serverInfo = authenticationViewModel.serverInfo.value?.peekContent()?.getStoredData() + if (serverInfo is ServerInfo.OIDCServer) { + tokenEndPoint = serverInfo.oidcServerConfiguration.tokenEndpoint + if (serverInfo.oidcServerConfiguration.isTokenEndpointAuthMethodSupportedClientSecretPost()) { + clientId = clientRegistrationInfo?.clientId ?: contextProvider.getString(R.string.oauth2_client_id) + clientSecret = clientRegistrationInfo?.clientSecret ?: contextProvider.getString(R.string.oauth2_client_secret) } + } else { + tokenEndPoint = "$serverBaseUrl${File.separator}${contextProvider.getString(R.string.oauth2_url_endpoint_access)}" } val scope = resources.getString(R.string.oauth2_openid_scope) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/common/UIResult.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/common/UIResult.kt index 8e8c8f19774..c94df13a9ed 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/common/UIResult.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/common/UIResult.kt @@ -37,9 +37,10 @@ sealed class UIResult { } fun getThrowableOrNull(): Throwable? = - when (this) { - is Error -> error - else -> null + if (this is Error) { + error + } else { + null } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/SecurityEnforced.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/SecurityEnforced.kt index b8af17c0159..5561888737a 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/SecurityEnforced.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/SecurityEnforced.kt @@ -29,9 +29,10 @@ enum class LockType { companion object { fun parseFromInteger(value: Int): LockType { - return when (value) { - 0 -> PASSCODE - else -> PATTERN + return if (value == 0) { + PASSCODE + } else { + PATTERN } } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt index 5dcda2ba161..ea1e6589dd7 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt @@ -215,9 +215,10 @@ class PassCodeActivity : AppCompatActivity(), NumberKeyboardListener, EnableBiom } PasscodeAction.REMOVE -> { - when (status.type) { - PasscodeType.OK -> actionRemoveOk() - else -> actionRemoveError() + if (status.type == PasscodeType.OK) { + actionRemoveOk() + } else { + actionRemoveError() } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/privacypolicy/PrivacyPolicyActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/privacypolicy/PrivacyPolicyActivity.kt index 509f9b192f6..fc74f139ddd 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/privacypolicy/PrivacyPolicyActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/privacypolicy/PrivacyPolicyActivity.kt @@ -91,9 +91,10 @@ class PrivacyPolicyActivity : AppCompatActivity() { override fun onOptionsItemSelected(item: MenuItem): Boolean { var retval = true - when (item.itemId) { - android.R.id.home -> finish() - else -> retval = super.onOptionsItemSelected(item) + if (item.itemId == android.R.id.home) { + finish() + } else { + retval = super.onOptionsItemSelected(item) } return retval } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareActivity.kt index 530ba94b22f..9d009b33bc8 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareActivity.kt @@ -294,11 +294,12 @@ class ShareActivity : FileActivity(), ShareFragmentListener { override fun onOptionsItemSelected(item: MenuItem): Boolean { var retval = true - when (item.itemId) { - android.R.id.home -> if (!supportFragmentManager.popBackStackImmediate()) { + if (item.itemId == android.R.id.home) { + if (!supportFragmentManager.popBackStackImmediate()) { finish() } - else -> retval = super.onOptionsItemSelected(item) + } else { + retval = super.onOptionsItemSelected(item) } return retval } @@ -317,14 +318,13 @@ class ShareActivity : FileActivity(), ShareFragmentListener { } override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean { - return when (keyCode) { - KeyEvent.KEYCODE_DPAD_DOWN -> { - if (findViewById(R.id.owncloud_app_bar).hasFocus()) { - findViewById(R.id.share_fragment_container).requestFocus() - } - true + return if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { + if (findViewById(R.id.owncloud_app_bar).hasFocus()) { + findViewById(R.id.share_fragment_container).requestFocus() } - else -> super.onKeyUp(keyCode, event) + true + } else { + super.onKeyUp(keyCode, event) } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/UsersAndGroupsSearchProvider.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/UsersAndGroupsSearchProvider.kt index b7b7e6b4b8c..014e393771d 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/UsersAndGroupsSearchProvider.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/UsersAndGroupsSearchProvider.kt @@ -112,9 +112,10 @@ class UsersAndGroupsSearchProvider : ContentProvider() { sortOrder: String? ): Cursor? { Timber.d("query received in thread ${Thread.currentThread().name}") - return when (uriMatcher.match(uri)) { - SEARCH -> searchForUsersOrGroups(uri) - else -> null + return if (uriMatcher.match(uri) == SEARCH) { + searchForUsersOrGroups(uri) + } else { + null } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt index 309b1ad24be..88d271c6e45 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt @@ -2016,14 +2016,13 @@ class FileDisplayActivity : FileActivity(), } override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean { - return when (keyCode) { - KeyEvent.KEYCODE_DPAD_DOWN -> { - if (findViewById(R.id.owncloud_app_bar).hasFocus()) { - findViewById(R.id.left_fragment_container).requestFocus() - } - true + return if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { + if (findViewById(R.id.owncloud_app_bar).hasFocus()) { + findViewById(R.id.left_fragment_container).requestFocus() } - else -> super.onKeyUp(keyCode, event) + true + } else { + super.onKeyUp(keyCode, event) } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewFormatTextFragmentStateAdapter.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewFormatTextFragmentStateAdapter.kt index 4c7f44b3fa7..27fd5f69b72 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewFormatTextFragmentStateAdapter.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewFormatTextFragmentStateAdapter.kt @@ -47,9 +47,10 @@ class PreviewFormatTextFragmentStateAdapter( override fun getItemCount(): Int = 2 override fun createFragment(position: Int): Fragment { - return when (position) { - 0 -> PreviewFormatTextFragment.newInstance(text, mimeType) - else -> PreviewFormatTextFragment.newInstance(text) + return if (position == 0) { + PreviewFormatTextFragment.newInstance(text, mimeType) + } else { + PreviewFormatTextFragment.newInstance(text) } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.kt index 06fe6316acb..e8c1a7bb3ec 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.kt @@ -253,16 +253,15 @@ class PreviewImageActivity : FileActivity(), } override fun onOptionsItemSelected(item: MenuItem): Boolean { - return when (item.itemId) { - android.R.id.home -> { - if (isDrawerOpen()) { - closeDrawer() - } else { - backToDisplayActivity() - } - true + return if (item.itemId == android.R.id.home) { + if (isDrawerOpen()) { + closeDrawer() + } else { + backToDisplayActivity() } - else -> super.onOptionsItemSelected(item) + true + } else { + super.onOptionsItemSelected(item) } } @@ -411,12 +410,11 @@ class PreviewImageActivity : FileActivity(), } override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean { - return when (keyCode) { - KeyEvent.KEYCODE_TAB -> { - showSystemUI(fullScreenAnchorView) - true - } - else -> super.onKeyUp(keyCode, event) + return if (keyCode == KeyEvent.KEYCODE_TAB) { + showSystemUI(fullScreenAnchorView) + true + } else { + super.onKeyUp(keyCode, event) } } From de8f58461cad0744e36b93fdd55ce1a109ecd000 Mon Sep 17 00:00:00 2001 From: joragua Date: Wed, 11 Dec 2024 17:49:30 +0100 Subject: [PATCH 22/74] refactor: replace when by if for binary conditions in module `owncloudDomain` --- .../com/owncloud/android/domain/UseCaseResult.kt | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/UseCaseResult.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/UseCaseResult.kt index 3b836ccfe17..575bc6f7b26 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/UseCaseResult.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/UseCaseResult.kt @@ -27,14 +27,16 @@ sealed class UseCaseResult { val isError get() = this is Error fun getDataOrNull(): T? = - when (this) { - is Success -> data - else -> null + if (this is Success) { + data + } else { + null } fun getThrowableOrNull(): Throwable? = - when (this) { - is Error -> throwable - else -> null + if (this is Error) { + throwable + } else { + null } } From 720a484eb010a8fa30d7680ce742773f8884fe76 Mon Sep 17 00:00:00 2001 From: joragua Date: Wed, 11 Dec 2024 18:08:14 +0100 Subject: [PATCH 23/74] refactor: replace if/else condition with a null block by let in module `owncloudApp` --- .../presentation/files/filelist/FileListAdapter.kt | 6 +----- .../android/ui/activity/FileDisplayActivity.kt | 10 ++-------- .../sharing/PublicLinkPasswordUtilsTest.kt | 2 +- 3 files changed, 4 insertions(+), 14 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt index d84a1a6a467..b095463b895 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt @@ -188,11 +188,7 @@ class FileListAdapter( val fileIcon = holder.itemView.findViewById(R.id.thumbnail).apply { tag = file.id } - val thumbnail: Bitmap? = if (file.remoteId != null) { - ThumbnailsCacheManager.getBitmapFromDiskCache(file.remoteId) - } else { - null - } + val thumbnail: Bitmap? = file.remoteId?.let { ThumbnailsCacheManager.getBitmapFromDiskCache(file.remoteId) } holder.itemView.findViewById(R.id.ListItemLayout)?.apply { contentDescription = "LinearLayout-$name" diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt index 88d271c6e45..9842c1a7745 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt @@ -865,14 +865,8 @@ class FileDisplayActivity : FileActivity(), syncInProgress = true } else { - var currentFile: OCFile? = if (file == null) - null - else - storageManager.getFileByPath(file.remotePath, file.spaceId) - val currentDir = if (currentDir == null) - null - else - storageManager.getFileByPath(currentDir!!.remotePath, currentDir.spaceId) + var currentFile: OCFile? = file?.let { storageManager.getFileByPath(file.remotePath, file.spaceId) } + val currentDir = currentDir?.let { storageManager.getFileByPath(currentDir!!.remotePath, currentDir.spaceId) } if (currentDir == null) { // current folder was removed from the server diff --git a/owncloudApp/src/test/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtilsTest.kt b/owncloudApp/src/test/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtilsTest.kt index ec2d88def49..bf1ba92319d 100644 --- a/owncloudApp/src/test/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtilsTest.kt +++ b/owncloudApp/src/test/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtilsTest.kt @@ -40,7 +40,7 @@ class PublicLinkPasswordUtilsTest { @Test fun `generatePassword creates password fulfilling all policies`() { - repeat (1000) { + repeat(1000) { val password = generatePassword( minChars = minCharacters, maxChars = maxCharacters, From 01b9803e48d19c88ccce98949b95f707f8ebf19b Mon Sep 17 00:00:00 2001 From: joragua Date: Wed, 11 Dec 2024 18:10:42 +0100 Subject: [PATCH 24/74] refactor: replace if/else condition with a null block by let in module `owncloudComLibrary` --- .../android/lib/common/http/logging/LogInterceptor.kt | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/logging/LogInterceptor.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/logging/LogInterceptor.kt index 862846f521f..ecce97d7ea7 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/logging/LogInterceptor.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/logging/LogInterceptor.kt @@ -136,14 +136,7 @@ class LogInterceptor : Interceptor { LogResponse( Response( headers = logHeaders(response.headers), - body = if (responseBody == null) { - null - } else { - Body( - data = responseBody, - length = bodyLength, - ) - }, + body = responseBody?.let { Body(data = responseBody, length = bodyLength) }, info = ResponseInfo( id = requestId, method = request.method, From 0584ffad984fa2030d15b1e8ce8ee079cfeb2f13 Mon Sep 17 00:00:00 2001 From: joragua Date: Wed, 11 Dec 2024 18:16:14 +0100 Subject: [PATCH 25/74] refactor: fix for KtLint report --- .../presentation/sharing/PublicLinkPasswordUtils.kt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtils.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtils.kt index 2890587b927..c71ab1ab24e 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtils.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/PublicLinkPasswordUtils.kt @@ -53,22 +53,22 @@ fun generatePassword( val passwordChars = mutableListOf() // Include the minimum number of digits established by the policy - repeat (minDigits) { + repeat(minDigits) { passwordChars.add(charsetDigits[secureRandom.nextInt(charsetDigits.size)]) } // Include the minimum number of lowercase chars established by the policy - repeat (minLowercaseCharacters) { + repeat(minLowercaseCharacters) { passwordChars.add(charsetLowercase[secureRandom.nextInt(charsetLowercase.size)]) } // Include the minimum number of uppercase chars established by the policy - repeat (minUppercaseCharacters) { + repeat(minUppercaseCharacters) { passwordChars.add(charsetUppercase[secureRandom.nextInt(charsetUppercase.size)]) } // Include the minimum number of special chars established by the policy - repeat (minSpecialCharacters) { + repeat(minSpecialCharacters) { passwordChars.add(charsetSpecial[secureRandom.nextInt(charsetSpecial.size)]) } From e3a5f3f1ac816b286d77f2a60510bbd17e2a8421 Mon Sep 17 00:00:00 2001 From: joragua Date: Thu, 12 Dec 2024 09:30:55 +0100 Subject: [PATCH 26/74] refactor: remove unnecessary spaces between packages and imports --- .../android/presentation/files/filelist/MainEmptyListFragment.kt | 1 - .../android/lib/resources/status/services/ServerInfoService.kt | 1 - 2 files changed, 2 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainEmptyListFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainEmptyListFragment.kt index 01a3595105a..237c363fa4f 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainEmptyListFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainEmptyListFragment.kt @@ -29,7 +29,6 @@ import android.widget.TextView import com.owncloud.android.R import com.owncloud.android.databinding.MainEmptyListFragmentBinding - class MainEmptyListFragment : Fragment() { private var _binding: MainEmptyListFragmentBinding? = null diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/services/ServerInfoService.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/services/ServerInfoService.kt index b1eb2871e39..e960f62cd06 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/services/ServerInfoService.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/services/ServerInfoService.kt @@ -23,7 +23,6 @@ */ package com.owncloud.android.lib.resources.status.services - import com.owncloud.android.lib.common.OwnCloudClient import com.owncloud.android.lib.common.operations.RemoteOperationResult import com.owncloud.android.lib.resources.status.RemoteServerInfo From 58c0dc3674c293a6127eba55b0133f5ddbd4c272 Mon Sep 17 00:00:00 2001 From: joragua Date: Thu, 12 Dec 2024 09:50:30 +0100 Subject: [PATCH 27/74] refactor: remove explicit `it` in lambda functions --- .../owncloud/android/data/capabilities/db/OCCapabilityEntity.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/owncloudData/src/main/java/com/owncloud/android/data/capabilities/db/OCCapabilityEntity.kt b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/db/OCCapabilityEntity.kt index 5eca4788088..d44bf2324de 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/capabilities/db/OCCapabilityEntity.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/db/OCCapabilityEntity.kt @@ -132,7 +132,7 @@ data class OCCapabilityEntity( @PrimaryKey(autoGenerate = true) var id: Int = 0 companion object { - fun fromCursor(cursor: Cursor): OCCapabilityEntity = cursor.use { it -> + fun fromCursor(cursor: Cursor): OCCapabilityEntity = cursor.use { OCCapabilityEntity( it.getString(it.getColumnIndexOrThrow(CAPABILITIES_ACCOUNT_NAME)), it.getInt(it.getColumnIndexOrThrow(CAPABILITIES_VERSION_MAJOR)), From a2606fc2f742d994d3d07d960f17b68fab496f2e Mon Sep 17 00:00:00 2001 From: joragua Date: Thu, 12 Dec 2024 10:49:19 +0100 Subject: [PATCH 28/74] refactor: collapse if statements --- .../files/filelist/FileListAdapter.kt | 16 ++++++-------- .../files/filelist/MainFileListFragment.kt | 22 +++++++++---------- .../workers/UploadFileFromContentUriWorker.kt | 6 ++--- .../lib/common/utils/OCFileLoggingTree.kt | 5 ++--- 4 files changed, 21 insertions(+), 28 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt index b095463b895..00f668f74fc 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt @@ -243,18 +243,16 @@ class FileListAdapter( if (thumbnail != null) { fileIcon.setImageBitmap(thumbnail) } - if (file.needsToUpdateThumbnail) { + if (file.needsToUpdateThumbnail && ThumbnailsCacheManager.cancelPotentialThumbnailWork(file, fileIcon)) { // generate new Thumbnail - if (ThumbnailsCacheManager.cancelPotentialThumbnailWork(file, fileIcon)) { - val task = ThumbnailsCacheManager.ThumbnailGenerationTask(fileIcon, account) - val asyncDrawable = ThumbnailsCacheManager.AsyncThumbnailDrawable(context.resources, thumbnail, task) + val task = ThumbnailsCacheManager.ThumbnailGenerationTask(fileIcon, account) + val asyncDrawable = ThumbnailsCacheManager.AsyncThumbnailDrawable(context.resources, thumbnail, task) - // If drawable is not visible, do not update it. - if (asyncDrawable.minimumHeight > 0 && asyncDrawable.minimumWidth > 0) { - fileIcon.setImageDrawable(asyncDrawable) - } - task.execute(file) + // If drawable is not visible, do not update it. + if (asyncDrawable.minimumHeight > 0 && asyncDrawable.minimumWidth > 0) { + fileIcon.setImageDrawable(asyncDrawable) } + task.execute(file) } if (file.mimeType == "image/png") { diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt index c64b602906d..d0fa535ba45 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt @@ -485,21 +485,19 @@ class MainFileListFragment : Fragment(), if (thumbnail != null) { thumbnailBottomSheet.setImageBitmap(thumbnail) } - if (file.needsToUpdateThumbnail) { + if (file.needsToUpdateThumbnail && ThumbnailsCacheManager.cancelPotentialThumbnailWork(file, thumbnailBottomSheet)) { // generate new Thumbnail - if (ThumbnailsCacheManager.cancelPotentialThumbnailWork(file, thumbnailBottomSheet)) { - val task = ThumbnailsCacheManager.ThumbnailGenerationTask( - thumbnailBottomSheet, - AccountUtils.getCurrentOwnCloudAccount(requireContext()) - ) - val asyncDrawable = ThumbnailsCacheManager.AsyncThumbnailDrawable(resources, thumbnail, task) + val task = ThumbnailsCacheManager.ThumbnailGenerationTask( + thumbnailBottomSheet, + AccountUtils.getCurrentOwnCloudAccount(requireContext()) + ) + val asyncDrawable = ThumbnailsCacheManager.AsyncThumbnailDrawable(resources, thumbnail, task) - // If drawable is not visible, do not update it. - if (asyncDrawable.minimumHeight > 0 && asyncDrawable.minimumWidth > 0) { - thumbnailBottomSheet.setImageDrawable(asyncDrawable) - } - task.execute(file) + // If drawable is not visible, do not update it. + if (asyncDrawable.minimumHeight > 0 && asyncDrawable.minimumWidth > 0) { + thumbnailBottomSheet.setImageDrawable(asyncDrawable) } + task.execute(file) } if (file.mimeType == "image/png") { diff --git a/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromContentUriWorker.kt b/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromContentUriWorker.kt index a655a2c97ce..363cdec24a4 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromContentUriWorker.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromContentUriWorker.kt @@ -180,10 +180,8 @@ class UploadFileFromContentUriWorker( private fun copyFileToLocalStorage() { val cacheFile = File(cachePath) val cacheDir = cacheFile.parentFile - if (cacheDir != null) { - if (!cacheDir.exists()) { - cacheDir.mkdirs() - } + if (cacheDir != null && !cacheDir.exists()) { + cacheDir.mkdirs() } cacheFile.createNewFile() diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/utils/OCFileLoggingTree.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/utils/OCFileLoggingTree.kt index 03f854c874b..03b95ef0b60 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/utils/OCFileLoggingTree.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/utils/OCFileLoggingTree.kt @@ -48,9 +48,8 @@ class OCFileLoggingTree( init { externalCacheDir.let { - if (!it.exists()) { - if (!it.mkdirs()) - Log.e(LOG_TAG, "couldn't create ${it.absoluteFile}") + if (!it.exists() && !it.mkdirs()) { + Log.e(LOG_TAG, "couldn't create ${it.absoluteFile}") } var fileNameTimestamp = SimpleDateFormat(LOG_FILE_TIME_FORMAT, Locale.getDefault()).format(Date()) From 1025c3f5cb42de1bcc868053c6c7cfa7b964e70e Mon Sep 17 00:00:00 2001 From: joragua Date: Thu, 12 Dec 2024 11:13:24 +0100 Subject: [PATCH 29/74] refactor: remove unused parameters --- .../android/extensions/WorkManagerExt.kt | 10 ----- .../DocumentsStorageProvider.kt | 1 - .../presentation/sharing/ShareFileFragment.kt | 4 +- .../android/ui/activity/FileActivity.java | 2 +- .../ui/activity/FileDisplayActivity.kt | 38 +++---------------- .../ui/errorhandling/ErrorMessageAdapter.kt | 7 +--- .../synchronization/SynchronizeFileUseCase.kt | 4 +- .../android/utils/NotificationUtils.kt | 2 +- 8 files changed, 14 insertions(+), 54 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/extensions/WorkManagerExt.kt b/owncloudApp/src/main/java/com/owncloud/android/extensions/WorkManagerExt.kt index e4685b24327..6217218b233 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/extensions/WorkManagerExt.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/extensions/WorkManagerExt.kt @@ -62,16 +62,6 @@ fun WorkManager.getRunningWorkInfosLiveData(tags: List): LiveData - if (isFolder) { - startSyncFolderOperation(file, false) - } - } val syncProfileOperation = SyncProfileOperation(account) syncProfileOperation.syncUserProfile() val workManagerProvider = WorkManagerProvider(context = baseContext) @@ -606,7 +600,7 @@ class FileDisplayActivity : FileActivity(), // Handle calls form internal activities. if (requestCode == REQUEST_CODE__SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK || resultCode == RESULT_OK_AND_MOVE)) { - requestUploadOfContentFromApps(data, resultCode) + requestUploadOfContentFromApps(data) } else if (requestCode == REQUEST_CODE__UPLOAD_FROM_CAMERA) { if (resultCode == RESULT_OK || resultCode == RESULT_OK_AND_MOVE) { @@ -620,7 +614,7 @@ class FileDisplayActivity : FileActivity(), capturedFilePaths: Array ) { if (hasEnoughSpace) { - requestUploadOfFilesFromFileSystem(capturedFilePaths, UploadBehavior.MOVE.toLegacyLocalBehavior()) + requestUploadOfFilesFromFileSystem(capturedFilePaths) } } }) @@ -642,7 +636,7 @@ class FileDisplayActivity : FileActivity(), } } - private fun requestUploadOfFilesFromFileSystem(filePaths: Array?, behaviour: Int) { + private fun requestUploadOfFilesFromFileSystem(filePaths: Array?) { if (filePaths != null) { val remotePaths = arrayOfNulls(filePaths.size) val remotePathBase = currentDir?.remotePath @@ -663,7 +657,7 @@ class FileDisplayActivity : FileActivity(), } } - private fun requestUploadOfContentFromApps(contentIntent: Intent?, resultCode: Int) { + private fun requestUploadOfContentFromApps(contentIntent: Intent?) { val streamsToUpload = ArrayList() if (contentIntent!!.clipData != null && contentIntent.clipData!!.itemCount > 0) { @@ -923,7 +917,6 @@ class FileDisplayActivity : FileActivity(), val root = storageManager.getRootPersonalFolder() listOfFiles.navigateToFolder(root!!) file = root - startSyncFolderOperation(root, false) } cleanSecondFragment() } @@ -1521,26 +1514,7 @@ class FileDisplayActivity : FileActivity(), } override fun onSavedCertificate() { - startSyncFolderOperation(currentDir, false) - } - - /** - * Starts an operation to refresh the requested folder. - * - * - * The operation is run in a new background thread created on the fly. - * - * - * The refresh updates is a "light sync": properties of regular files in folder are updated (including - * associated shares), but not their contents. Only the contents of files marked to be kept-in-sync are - * synchronized too. - * - * @param folder Folder to refresh. - * @param ignoreETag If 'true', the data from the server will be fetched and synced even if the eTag - * didn't change. - */ - fun startSyncFolderOperation(folder: OCFile?, ignoreETag: Boolean) { - // TODO: SYNC FOLDER + // Nothing to do } private fun requestForDownload(file: OCFile) { @@ -1921,7 +1895,7 @@ class FileDisplayActivity : FileActivity(), } override fun uploadShortcutFileFromApp(shortcutFilePath: Array) { - requestUploadOfFilesFromFileSystem(shortcutFilePath, UploadBehavior.MOVE.toLegacyLocalBehavior()) + requestUploadOfFilesFromFileSystem(shortcutFilePath) } override fun uploadFromFileSystem() { diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/errorhandling/ErrorMessageAdapter.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/errorhandling/ErrorMessageAdapter.kt index ac06ea4c962..90242cb1f1f 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/errorhandling/ErrorMessageAdapter.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/errorhandling/ErrorMessageAdapter.kt @@ -156,7 +156,6 @@ class ErrorMessageAdapter { */ fun getResultMessage( result: RemoteOperationResult<*>, - operation: RemoteOperation<*>?, resources: Resources ): String { val formatter = Formatter(resources) @@ -184,7 +183,7 @@ class ErrorMessageAdapter { ResultCode.CONFLICT -> formatter.format(R.string.move_file_error) ResultCode.INVALID_COPY_INTO_DESCENDANT -> formatter.format(R.string.copy_file_invalid_into_descendent) - else -> getCommonMessageForResult(operation, result, resources) + else -> getCommonMessageForResult(result, resources) } } @@ -197,7 +196,6 @@ class ErrorMessageAdapter { * @return User message corresponding to 'result'. */ private fun getCommonMessageForResult( - operation: RemoteOperation<*>?, result: RemoteOperationResult<*>, res: Resources ): String { @@ -226,7 +224,7 @@ class ErrorMessageAdapter { ResultCode.ACCOUNT_NOT_THE_SAME -> formatter.format(R.string.auth_account_not_the_same) ResultCode.OK_REDIRECT_TO_NON_SECURE_CONNECTION -> formatter.format(R.string.auth_redirect_non_secure_connection_title) else -> if (result.httpPhrase != null && result.httpPhrase.isNotEmpty()) - result.httpPhrase else getGenericErrorMessageForOperation(operation, result, res) + result.httpPhrase else getGenericErrorMessageForOperation(result, res) } } @@ -238,7 +236,6 @@ class ErrorMessageAdapter { * @return User message corresponding to a generic error of 'operation'. */ private fun getGenericErrorMessageForOperation( - operation: RemoteOperation<*>?, result: RemoteOperationResult<*>, res: Resources ): String { diff --git a/owncloudApp/src/main/java/com/owncloud/android/usecases/synchronization/SynchronizeFileUseCase.kt b/owncloudApp/src/main/java/com/owncloud/android/usecases/synchronization/SynchronizeFileUseCase.kt index 543930d9b01..1a1181b3e62 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/usecases/synchronization/SynchronizeFileUseCase.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/usecases/synchronization/SynchronizeFileUseCase.kt @@ -102,7 +102,7 @@ class SynchronizeFileUseCase( } else if (changedLocally) { // 5.3 File has change ONLY locally -> upload new version Timber.i("File ${fileToSynchronize.fileName} has changed locally. Let's upload the new version") - val uuid = requestForUpload(accountName, fileToSynchronize, fileToSynchronize.etag!!) + val uuid = requestForUpload(accountName, fileToSynchronize) return SyncType.UploadEnqueued(uuid) } else { // 5.4 File has not change locally not remotely -> do nothing @@ -121,7 +121,7 @@ class SynchronizeFileUseCase( ) } - private fun requestForUpload(accountName: String, ocFile: OCFile, etagInConflict: String): UUID? { + private fun requestForUpload(accountName: String, ocFile: OCFile): UUID? { return uploadFileInConflictUseCase( UploadFileInConflictUseCase.Params( accountName = accountName, diff --git a/owncloudApp/src/main/java/com/owncloud/android/utils/NotificationUtils.kt b/owncloudApp/src/main/java/com/owncloud/android/utils/NotificationUtils.kt index b7872b282a8..74d72d666dc 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/utils/NotificationUtils.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/utils/NotificationUtils.kt @@ -157,7 +157,7 @@ object NotificationUtils { * @param account account which the file in conflict belongs to */ @JvmStatic - fun notifyConflict(fileInConflict: OCFile, account: Account?, context: Context) { + fun notifyConflict(fileInConflict: OCFile, context: Context) { val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notificationBuilder = newNotificationBuilder(context, FILE_SYNC_CONFLICT_NOTIFICATION_CHANNEL_ID) notificationBuilder From 47586474357daa4456329966c62dd30e790c66f7 Mon Sep 17 00:00:00 2001 From: joragua Date: Thu, 12 Dec 2024 11:30:58 +0100 Subject: [PATCH 30/74] refactor: rename invalid package declaration --- .../java/com/owncloud/android/extensions/FragmentActivityExt.kt | 2 +- .../com/owncloud/android/presentation/sharing/ShareActivity.kt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/extensions/FragmentActivityExt.kt b/owncloudApp/src/main/java/com/owncloud/android/extensions/FragmentActivityExt.kt index a063c429968..15f5aca1183 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/extensions/FragmentActivityExt.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/extensions/FragmentActivityExt.kt @@ -18,7 +18,7 @@ * along with this program. If not, see //www.gnu.org/licenses/>. */ -package com.owncloud.android.ui.utils +package com.owncloud.android.extensions import androidx.fragment.app.DialogFragment import androidx.fragment.app.FragmentActivity diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareActivity.kt index 9d009b33bc8..328919f80d4 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareActivity.kt @@ -47,7 +47,7 @@ import com.owncloud.android.presentation.sharing.sharees.SearchShareesFragment import com.owncloud.android.presentation.sharing.sharees.UsersAndGroupsSearchProvider import com.owncloud.android.presentation.sharing.shares.PublicShareDialogFragment import com.owncloud.android.ui.activity.FileActivity -import com.owncloud.android.ui.utils.showDialogFragment +import com.owncloud.android.extensions.showDialogFragment import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.core.parameter.parametersOf import timber.log.Timber From 2f40c2d1015e6e998a682ba93dcc470b29dff52d Mon Sep 17 00:00:00 2001 From: Jesus Recio Date: Tue, 17 Dec 2024 12:34:25 +0100 Subject: [PATCH 31/74] feat: set up to run detekt over all the modules in parallel --- .github/workflows/detekt.yml | 74 ++++++++++++++++++++++++++++++++++-- 1 file changed, 71 insertions(+), 3 deletions(-) diff --git a/.github/workflows/detekt.yml b/.github/workflows/detekt.yml index efc259ff36b..79445c53c7c 100644 --- a/.github/workflows/detekt.yml +++ b/.github/workflows/detekt.yml @@ -21,6 +21,7 @@ on: push: branches: - feature/detekt + - feature/run_actions_parallel pull_request: branches: - "master" @@ -30,11 +31,9 @@ on: # A workflow run is made up of one or more jobs that can run sequentially or in parallel jobs: # This workflow contains a single job called "greet" - run: + owncloudApp: # The type of runner that the job will run on runs-on: ubuntu-latest - - # Steps represent a sequence of tasks that will be executed as part of the job steps: - uses: actions/checkout@v4 @@ -50,11 +49,80 @@ jobs: uses: gradle/actions/setup-gradle@v4 - name: module owncloudApp run: ./gradlew detekt + + owncloudDomain: + # The type of runner that the job will run on + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: '17' + distribution: 'temurin' + + # Configure Gradle for optimal use in GitHub Actions, including caching of downloaded dependencies. + # See: https://github.com/gradle/actions/blob/main/setup-gradle/README.md + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4 - name: module owncloudDomain run: ./gradlew owncloudDomain:detekt + + owncloudData: + # The type of runner that the job will run on + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: '17' + distribution: 'temurin' + + # Configure Gradle for optimal use in GitHub Actions, including caching of downloaded dependencies. + # See: https://github.com/gradle/actions/blob/main/setup-gradle/README.md + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4 - name: module owncloudData run: ./gradlew owncloudData:detekt + + owncloudComLibrary: + # The type of runner that the job will run on + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: '17' + distribution: 'temurin' + + # Configure Gradle for optimal use in GitHub Actions, including caching of downloaded dependencies. + # See: https://github.com/gradle/actions/blob/main/setup-gradle/README.md + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4 - name: module owncloudComLibrary run: ./gradlew owncloudComLibrary:detekt + + + owncloudTestUtil: + # The type of runner that the job will run on + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: '17' + distribution: 'temurin' + + # Configure Gradle for optimal use in GitHub Actions, including caching of downloaded dependencies. + # See: https://github.com/gradle/actions/blob/main/setup-gradle/README.md + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4 - name: module owncloudTestUtil run: ./gradlew owncloudTestUtil:detekt From dba515b52e5cb30546a61ce347169ca4502b9718 Mon Sep 17 00:00:00 2001 From: joragua Date: Wed, 8 Jan 2025 10:51:21 +0100 Subject: [PATCH 32/74] refactor: remove unnecessary function and join two if conditions --- .../owncloud/android/presentation/sharing/ShareActivity.kt | 6 ++---- .../com/owncloud/android/ui/activity/FileDisplayActivity.kt | 4 ---- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareActivity.kt index 328919f80d4..f66cdd5fdb5 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareActivity.kt @@ -294,10 +294,8 @@ class ShareActivity : FileActivity(), ShareFragmentListener { override fun onOptionsItemSelected(item: MenuItem): Boolean { var retval = true - if (item.itemId == android.R.id.home) { - if (!supportFragmentManager.popBackStackImmediate()) { - finish() - } + if (item.itemId == android.R.id.home && !supportFragmentManager.popBackStackImmediate()) { + finish() } else { retval = super.onOptionsItemSelected(item) } diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt index 53587626e1f..05bb09b3e72 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt @@ -1513,10 +1513,6 @@ class FileDisplayActivity : FileActivity(), } } - override fun onSavedCertificate() { - // Nothing to do - } - private fun requestForDownload(file: OCFile) { val downloadFileUseCase: DownloadFileUseCase by inject() From 8ab3345ff4fa800bf37091f49dfbd576500a1225 Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Thu, 9 Jan 2025 14:42:36 +0100 Subject: [PATCH 33/74] style: changed functions with just return to expression body in module `owncloudApp` --- .../main/java/com/owncloud/android/MainApp.kt | 5 ++- .../datamodel/FileDataStorageManager.kt | 5 ++- .../android/extensions/OCTransferExt.kt | 10 +++--- .../android/extensions/WorkManagerExt.kt | 10 +++--- .../accounts/ManageAccountsAdapter.kt | 5 ++- .../accounts/ManageAccountsViewModel.kt | 15 ++++---- .../presentation/common/DrawerViewModel.kt | 10 +++--- .../ConflictsResolveDialogFragment.kt | 5 ++- .../CreateFolderDialogFragment.kt | 5 ++- .../CreateShortcutDialogFragment.kt | 5 ++- .../files/filelist/FileListAdapter.kt | 10 +++--- .../files/filelist/MainFileListFragment.kt | 20 +++++------ .../files/filelist/MainFileListViewModel.kt | 15 ++++---- .../files/filelist/SelectableAdapter.kt | 5 ++- .../removefile/RemoveFilesDialogFragment.kt | 5 ++- .../presentation/logging/LogListViewModel.kt | 5 ++- .../migration/StorageMigrationActivity.kt | 5 ++- .../releasenotes/ReleaseNotesActivity.kt | 5 ++- .../releasenotes/ReleaseNotesViewModel.kt | 10 +++--- .../presentation/security/SecurityEnforced.kt | 5 ++- .../presentation/security/SecurityUtils.kt | 10 +++--- .../security/biometric/BiometricManager.kt | 15 ++++---- .../security/biometric/BiometricViewModel.kt | 5 ++- .../security/passcode/PassCodeActivity.kt | 5 ++- .../security/passcode/PassCodeManager.kt | 5 ++- .../security/pattern/PatternManager.kt | 5 ++- .../advanced/AdvancedSettingsUtils.kt | 5 ++- .../advanced/SettingsAdvancedViewModel.kt | 5 ++- .../SettingsPictureUploadsViewModel.kt | 5 ++- .../SettingsVideoUploadsViewModel.kt | 5 ++- .../presentation/sharing/ShareActivity.kt | 10 +++--- .../sharing/sharees/SearchShareesFragment.kt | 5 ++- .../sharees/UsersAndGroupsSearchProvider.kt | 25 ++++++------- .../transfers/TransfersAdapter.kt | 10 +++--- .../android/providers/FileContentProvider.kt | 15 ++++---- .../android/providers/WorkManagerProvider.kt | 5 ++- .../implementation/OCContextProvider.kt | 4 +-- .../android/ui/activity/DrawerActivity.kt | 5 ++- .../ui/activity/FileDisplayActivity.kt | 5 ++- .../ui/activity/FolderPickerActivity.kt | 5 ++- .../ui/errorhandling/ErrorMessageAdapter.kt | 35 ++++++++----------- .../ui/preview/PreviewAudioFragment.kt | 5 ++- .../PreviewFormatTextFragmentStateAdapter.kt | 10 +++--- .../ui/preview/PreviewImageActivity.kt | 15 ++++---- .../ui/preview/PreviewImageFragment.kt | 15 ++++---- .../android/ui/preview/PreviewTextFragment.kt | 5 ++- .../ui/preview/PreviewVideoActivity.kt | 15 ++++---- .../synchronization/SynchronizeFileUseCase.kt | 10 +++--- .../RetryFailedUploadsForAccountUseCase.kt | 5 ++- .../android/utils/NotificationUtils.kt | 5 ++- .../owncloud/android/utils/SortFilesUtils.kt | 15 ++++---- .../workers/AvailableOfflinePeriodicWorker.kt | 6 ++-- .../android/workers/OldLogsCollectorWorker.kt | 5 ++- ...esWithLastUsageOlderThanGivenTimeWorker.kt | 11 +++--- .../workers/UploadFileFromContentUriWorker.kt | 10 +++--- .../workers/UploadFileFromFileSystemWorker.kt | 10 +++--- 56 files changed, 195 insertions(+), 296 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/MainApp.kt b/owncloudApp/src/main/java/com/owncloud/android/MainApp.kt index afc5132ab74..5d5db83472b 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/MainApp.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/MainApp.kt @@ -339,15 +339,14 @@ class MainApp : Application() { get() = appContext.resources.getString(R.string.account_type) val versionCode: Int - get() { - return try { + get() = + try { val pInfo: PackageInfo = appContext.packageManager.getPackageInfo(appContext.packageName, 0) val longVersionCode: Long = PackageInfoCompat.getLongVersionCode(pInfo) longVersionCode.toInt() } catch (e: PackageManager.NameNotFoundException) { 0 } - } val authority: String get() = appContext.resources.getString(R.string.authority) diff --git a/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt b/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt index dca870423ec..29a7c0cd960 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt @@ -92,14 +92,13 @@ class FileDataStorageManager( fun fileExists(path: String): Boolean = getFileByPath(path) != null - fun getFolderContent(f: OCFile?): List { - return if (f != null && f.isFolder && f.id != -1L) { + fun getFolderContent(f: OCFile?): List = + if (f != null && f.isFolder && f.id != -1L) { // TODO: Remove !! getFolderContent(f.id!!) } else { listOf() } - } // TODO: New_arch: Remove this and call usecase inside FilesViewModel fun getFolderImages(folder: OCFile?): List = runBlocking(CoroutinesDispatcherProvider().io) { diff --git a/owncloudApp/src/main/java/com/owncloud/android/extensions/OCTransferExt.kt b/owncloudApp/src/main/java/com/owncloud/android/extensions/OCTransferExt.kt index 4a466b7929d..59c0fa4deda 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/extensions/OCTransferExt.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/extensions/OCTransferExt.kt @@ -30,8 +30,8 @@ import com.owncloud.android.domain.transfers.model.TransferResult import com.owncloud.android.domain.transfers.model.TransferStatus @StringRes -fun OCTransfer.statusToStringRes(): Int { - return when (status) { +fun OCTransfer.statusToStringRes(): Int = + when (status) { TransferStatus.TRANSFER_IN_PROGRESS -> R.string.uploader_upload_in_progress_ticker TransferStatus.TRANSFER_SUCCEEDED -> R.string.uploads_view_upload_status_succeeded TransferStatus.TRANSFER_QUEUED -> R.string.uploads_view_upload_status_queued @@ -63,8 +63,6 @@ fun OCTransfer.statusToStringRes(): Int { null -> R.string.uploads_view_upload_status_unknown_fail } } -} -fun OCTransfer.isContentUri(context: Context): Boolean { - return DocumentFile.isDocumentUri(context, Uri.parse(localPath)) -} +fun OCTransfer.isContentUri(context: Context): Boolean = + DocumentFile.isDocumentUri(context, Uri.parse(localPath)) diff --git a/owncloudApp/src/main/java/com/owncloud/android/extensions/WorkManagerExt.kt b/owncloudApp/src/main/java/com/owncloud/android/extensions/WorkManagerExt.kt index 6217218b233..5e4d1fcb0a5 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/extensions/WorkManagerExt.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/extensions/WorkManagerExt.kt @@ -41,16 +41,14 @@ fun WorkManager.getWorkInfoByTags(tags: List): List = /** * Get a list of WorkInfo of running workers that matches EVERY tag. */ -fun WorkManager.getRunningWorkInfosByTags(tags: List): List { - return getWorkInfos(buildWorkQuery(tags = tags, states = listOf(WorkInfo.State.RUNNING))).get().filter { it.tags.containsAll(tags) } -} +fun WorkManager.getRunningWorkInfosByTags(tags: List): List = + getWorkInfos(buildWorkQuery(tags = tags, states = listOf(WorkInfo.State.RUNNING))).get().filter { it.tags.containsAll(tags) } /** * Get a list of WorkInfo of running workers as LiveData that matches at least one of the tags. */ -fun WorkManager.getRunningWorkInfosLiveData(tags: List): LiveData> { - return getWorkInfosLiveData(buildWorkQuery(tags = tags, states = listOf(WorkInfo.State.RUNNING))) -} +fun WorkManager.getRunningWorkInfosLiveData(tags: List): LiveData> = + getWorkInfosLiveData(buildWorkQuery(tags = tags, states = listOf(WorkInfo.State.RUNNING))) /** * Check if a download is pending. It could be enqueued, downloading or blocked. diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/accounts/ManageAccountsAdapter.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/accounts/ManageAccountsAdapter.kt index e2b550c093a..eaaf9b4ba03 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/accounts/ManageAccountsAdapter.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/accounts/ManageAccountsAdapter.kt @@ -212,12 +212,11 @@ class ManageAccountsAdapter( val binding = AccountActionBinding.bind(itemView) } - override fun getItemViewType(position: Int): Int { - return when (getItem(position)) { + override fun getItemViewType(position: Int): Int = + when (getItem(position)) { is AccountRecyclerItem.AccountItem -> AccountManagementRecyclerItemViewType.ITEM_VIEW_ACCOUNT.ordinal is AccountRecyclerItem.NewAccount -> AccountManagementRecyclerItemViewType.ITEM_VIEW_ADD.ordinal } - } enum class AccountManagementRecyclerItemViewType { ITEM_VIEW_ACCOUNT, ITEM_VIEW_ADD diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/accounts/ManageAccountsViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/accounts/ManageAccountsViewModel.kt index 283918cc137..8b520fa90fc 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/accounts/ManageAccountsViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/accounts/ManageAccountsViewModel.kt @@ -66,13 +66,11 @@ class ManageAccountsViewModel( } } - fun getLoggedAccounts(): Array { - return accountProvider.getLoggedAccounts() - } + fun getLoggedAccounts(): Array = + accountProvider.getLoggedAccounts() - fun getCurrentAccount(): Account? { - return accountProvider.getCurrentOwnCloudAccount() - } + fun getCurrentAccount(): Account? = + accountProvider.getCurrentOwnCloudAccount() fun cleanAccountLocalStorage(accountName: String) { runUseCaseWithResult( @@ -84,10 +82,9 @@ class ManageAccountsViewModel( ) } - fun hasAutomaticUploadsAttached(accountName: String): Boolean { - return accountName == automaticUploadsConfiguration?.pictureUploadsConfiguration?.accountName || + fun hasAutomaticUploadsAttached(accountName: String): Boolean = + accountName == automaticUploadsConfiguration?.pictureUploadsConfiguration?.accountName || accountName == automaticUploadsConfiguration?.videoUploadsConfiguration?.accountName - } fun checkUserLight(accountName: String): Boolean = runBlocking(CoroutinesDispatcherProvider().io) { val quota = withContext(CoroutinesDispatcherProvider().io) { diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/common/DrawerViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/common/DrawerViewModel.kt index 3d080cde62d..0e7acd21f10 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/common/DrawerViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/common/DrawerViewModel.kt @@ -67,13 +67,11 @@ class DrawerViewModel( ) } - fun getAccounts(context: Context): List { - return AccountUtils.getAccounts(context).asList() - } + fun getAccounts(context: Context): List = + AccountUtils.getAccounts(context).asList() - fun getUsernameOfAccount(accountName: String): String { - return AccountUtils.getUsernameOfAccount(accountName) - } + fun getUsernameOfAccount(accountName: String): String = + AccountUtils.getUsernameOfAccount(accountName) fun getFeedbackMail() = contextProvider.getString(R.string.mail_feedback) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/conflicts/ConflictsResolveDialogFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/conflicts/ConflictsResolveDialogFragment.kt index 8ef414bc050..cab7392613a 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/conflicts/ConflictsResolveDialogFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/conflicts/ConflictsResolveDialogFragment.kt @@ -84,10 +84,9 @@ class ConflictsResolveDialogFragment : DialogFragment() { } companion object { - fun newInstance(onConflictDecisionMadeListener: OnConflictDecisionMadeListener): ConflictsResolveDialogFragment { - return ConflictsResolveDialogFragment().apply { + fun newInstance(onConflictDecisionMadeListener: OnConflictDecisionMadeListener): ConflictsResolveDialogFragment = + ConflictsResolveDialogFragment().apply { listener = onConflictDecisionMadeListener } - } } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/createfolder/CreateFolderDialogFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/createfolder/CreateFolderDialogFragment.kt index a96258bb6ee..8d840fc671d 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/createfolder/CreateFolderDialogFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/createfolder/CreateFolderDialogFragment.kt @@ -146,11 +146,10 @@ class CreateFolderDialogFragment : DialogFragment() { * @return Dialog ready to show. */ @JvmStatic - fun newInstance(parent: OCFile, listener: CreateFolderListener): CreateFolderDialogFragment { - return CreateFolderDialogFragment().apply { + fun newInstance(parent: OCFile, listener: CreateFolderListener): CreateFolderDialogFragment = + CreateFolderDialogFragment().apply { createFolderListener = listener parentFolder = parent } - } } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/createshortcut/CreateShortcutDialogFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/createshortcut/CreateShortcutDialogFragment.kt index 95239b84767..bec7c13cb62 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/createshortcut/CreateShortcutDialogFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/createshortcut/CreateShortcutDialogFragment.kt @@ -138,11 +138,10 @@ class CreateShortcutDialogFragment : DialogFragment() { companion object { - fun newInstance(parentFolder: OCFile, listener: CreateShortcutListener): CreateShortcutDialogFragment { - return CreateShortcutDialogFragment().apply { + fun newInstance(parentFolder: OCFile, listener: CreateShortcutListener): CreateShortcutDialogFragment = + CreateShortcutDialogFragment().apply { createShortcutListener = listener this.parentFolder = parentFolder } - } } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt index 00f668f74fc..2748c1b49d6 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt @@ -85,8 +85,8 @@ class FileListAdapter( diffResult.dispatchUpdatesTo(this) } - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { - return when (viewType) { + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder = + when (viewType) { ViewType.LIST_ITEM.ordinal -> { val binding = ItemFileListBinding.inflate(LayoutInflater.from(parent.context), parent, false) binding.root.apply { @@ -123,7 +123,6 @@ class FileListAdapter( FooterViewHolder(binding) } } - } override fun getItemCount(): Int = files.size @@ -131,9 +130,9 @@ class FileListAdapter( private fun isFooter(position: Int) = position == files.size.minus(1) - override fun getItemViewType(position: Int): Int { + override fun getItemViewType(position: Int): Int = - return if (isFooter(position)) { + if (isFooter(position)) { ViewType.FOOTER.ordinal } else { when { @@ -150,7 +149,6 @@ class FileListAdapter( } } } - } fun getCheckedItems(): List { val checkedItems = mutableListOf() diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt index d0fa535ba45..c9f9bd35bb4 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt @@ -662,15 +662,14 @@ class MainFileListFragment : Fragment(), } } - private suspend fun getDrawableFromUrl(context: Context, url: String): Drawable? { - return withContext(Dispatchers.IO) { + private suspend fun getDrawableFromUrl(context: Context, url: String): Drawable? = + withContext(Dispatchers.IO) { Glide.with(context) .load(url) .fitCenter() .submit() .get() } - } private fun observeFileListUiState() { collectLatestLifecycleFlow(mainFileListViewModel.fileListUiState) { fileListUiState -> @@ -1188,13 +1187,11 @@ class MainFileListFragment : Fragment(), * * @return The currently viewed OCFile */ - fun getCurrentFile(): OCFile { - return mainFileListViewModel.getFile() - } + fun getCurrentFile(): OCFile = + mainFileListViewModel.getFile() - fun getCurrentSpace(): OCSpace? { - return mainFileListViewModel.getSpace() - } + fun getCurrentSpace(): OCSpace? = + mainFileListViewModel.getSpace() private fun setDrawerStatus(enabled: Boolean) { (activity as FileActivity).setDrawerLockMode(if (enabled) DrawerLayout.LOCK_MODE_UNLOCKED else DrawerLayout.LOCK_MODE_LOCKED_CLOSED) @@ -1537,9 +1534,8 @@ class MainFileListFragment : Fragment(), } } - override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean { - return onFileActionChosen(item?.itemId) - } + override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean = + onFileActionChosen(item?.itemId) override fun onDestroyActionMode(mode: ActionMode?) { setDrawerStatus(enabled = true) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListViewModel.kt index 37bdfd2ba31..c2dcb0924b3 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListViewModel.kt @@ -177,13 +177,11 @@ class MainFileListViewModel( } } - fun getFile(): OCFile { - return currentFolderDisplayed.value - } + fun getFile(): OCFile = + currentFolderDisplayed.value - fun getSpace(): OCSpace? { - return space.value - } + fun getSpace(): OCSpace? = + space.value fun setGridModeAsPreferred() { savePreferredLayoutManager(true) @@ -199,15 +197,14 @@ class MainFileListViewModel( fun isGridModeSetAsPreferred() = sharedPreferencesProvider.getBoolean(RECYCLER_VIEW_PREFERRED, false) - private fun sortList(filesWithSyncInfo: List, sortTypeAndOrder: Pair): List { - return sortFilesWithSyncInfoUseCase( + private fun sortList(filesWithSyncInfo: List, sortTypeAndOrder: Pair): List = + sortFilesWithSyncInfoUseCase( SortFilesWithSyncInfoUseCase.Params( listOfFiles = filesWithSyncInfo, sortType = SortTypeDomain.fromPreferences(sortTypeAndOrder.first.ordinal), ascending = sortTypeAndOrder.second == SortOrder.SORT_ORDER_ASCENDING ) ) - } fun manageBrowseUp() { viewModelScope.launch(coroutinesDispatcherProvider.io) { diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/SelectableAdapter.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/SelectableAdapter.kt index ee90fde050b..9c669546cb2 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/SelectableAdapter.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/SelectableAdapter.kt @@ -32,9 +32,8 @@ abstract class SelectableAdapter : * @param position Position of the item to check * @return true if the item is selected, false otherwise */ - fun isSelected(position: Int): Boolean { - return getSelectedItems().contains(position) - } + fun isSelected(position: Int): Boolean = + getSelectedItems().contains(position) /** * Toggle the selection status of the item at a given position diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/removefile/RemoveFilesDialogFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/removefile/RemoveFilesDialogFragment.kt index 96c7dcaa42f..8dac1d858cc 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/removefile/RemoveFilesDialogFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/removefile/RemoveFilesDialogFragment.kt @@ -156,8 +156,7 @@ class RemoveFilesDialogFragment : DialogFragment() { */ @JvmStatic @JvmName("newInstanceForSingleFile") - fun newInstance(file: OCFile): RemoveFilesDialogFragment { - return newInstance(files = arrayListOf(file), isAvailableLocallyAndNotAvailableOffline = file.isAvailableLocally) - } + fun newInstance(file: OCFile): RemoveFilesDialogFragment = + newInstance(files = arrayListOf(file), isAvailableLocallyAndNotAvailableOffline = file.isAvailableLocally) } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/logging/LogListViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/logging/LogListViewModel.kt index b5c566b2da1..212cc8fd82f 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/logging/LogListViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/logging/LogListViewModel.kt @@ -33,7 +33,6 @@ class LogListViewModel( return File(logsPath) } - fun getLogsFiles(): List { - return getLogsDirectory().listFiles()?.toList()?.sortedBy { it.name } ?: listOf() - } + fun getLogsFiles(): List = + getLogsDirectory().listFiles()?.toList()?.sortedBy { it.name } ?: listOf() } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/migration/StorageMigrationActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/migration/StorageMigrationActivity.kt index c5222493fc9..0e69bc62c6a 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/migration/StorageMigrationActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/migration/StorageMigrationActivity.kt @@ -94,8 +94,7 @@ class StorageMigrationActivity : AppCompatActivity() { } } - private fun shouldShow(context: Context): Boolean { - return !hasAlreadyMigratedToScopedStorage(context) && hasDataInLegacyStorage() && hasAccessToLegacyStorage() - } + private fun shouldShow(context: Context): Boolean = + !hasAlreadyMigratedToScopedStorage(context) && hasDataInLegacyStorage() && hasAccessToLegacyStorage() } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/releasenotes/ReleaseNotesActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/releasenotes/ReleaseNotesActivity.kt index 362324570c6..0397a21a406 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/releasenotes/ReleaseNotesActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/releasenotes/ReleaseNotesActivity.kt @@ -99,8 +99,7 @@ class ReleaseNotesActivity : AppCompatActivity() { (context is FileDisplayActivity || context is LoginActivity) } - private fun firstRunAfterUpdate(): Boolean { - return MainApp.getLastSeenVersionCode() != versionCode - } + private fun firstRunAfterUpdate(): Boolean = + MainApp.getLastSeenVersionCode() != versionCode } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/releasenotes/ReleaseNotesViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/releasenotes/ReleaseNotesViewModel.kt index d0247f18059..0da793efdf0 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/releasenotes/ReleaseNotesViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/releasenotes/ReleaseNotesViewModel.kt @@ -31,17 +31,15 @@ class ReleaseNotesViewModel( private val contextProvider: ContextProvider ) : ViewModel() { - fun getReleaseNotes(): List { - return releaseNotesList - } + fun getReleaseNotes(): List = + releaseNotesList fun updateVersionCode() { preferencesProvider.putInt(MainApp.PREFERENCE_KEY_LAST_SEEN_VERSION_CODE, versionCode) } - fun shouldWhatsNewSectionBeVisible(): Boolean { - return contextProvider.getBoolean(R.bool.release_notes_enabled) && getReleaseNotes().isNotEmpty() - } + fun shouldWhatsNewSectionBeVisible(): Boolean = + contextProvider.getBoolean(R.bool.release_notes_enabled) && getReleaseNotes().isNotEmpty() companion object { val releaseNotesList = listOf( diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/SecurityEnforced.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/SecurityEnforced.kt index 5561888737a..6fd886302a7 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/SecurityEnforced.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/SecurityEnforced.kt @@ -28,12 +28,11 @@ enum class LockType { PASSCODE, PATTERN; companion object { - fun parseFromInteger(value: Int): LockType { - return if (value == 0) { + fun parseFromInteger(value: Int): LockType = + if (value == 0) { PASSCODE } else { PATTERN } - } } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/SecurityUtils.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/SecurityUtils.kt index 4610293e413..3a646238fb7 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/SecurityUtils.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/SecurityUtils.kt @@ -33,25 +33,23 @@ const val PREFERENCE_LAST_UNLOCK_ATTEMPT_TIMESTAMP = "last_unlock_attempt_timest enum class LockTimeout { DISABLED, IMMEDIATELY, ONE_MINUTE, FIVE_MINUTES, THIRTY_MINUTES; - fun toMilliseconds(): Int { - return when (this) { + fun toMilliseconds(): Int = + when (this) { DISABLED, IMMEDIATELY -> 1_000 ONE_MINUTE -> 60_000 FIVE_MINUTES -> 300_000 THIRTY_MINUTES -> 1_800_000 } - } companion object { - fun parseFromInteger(int: Int): LockTimeout { - return when (int) { + fun parseFromInteger(int: Int): LockTimeout = + when (int) { 1 -> IMMEDIATELY 2 -> ONE_MINUTE 3 -> FIVE_MINUTES 4 -> THIRTY_MINUTES else -> DISABLED } - } } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/biometric/BiometricManager.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/biometric/BiometricManager.kt index ae5283c4a70..35f4c8da842 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/biometric/BiometricManager.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/biometric/BiometricManager.kt @@ -92,16 +92,13 @@ object BiometricManager { else false } - fun isBiometricEnabled(): Boolean { - return preferencesProvider.getBoolean(BiometricActivity.PREFERENCE_SET_BIOMETRIC, false) - } + fun isBiometricEnabled(): Boolean = + preferencesProvider.getBoolean(BiometricActivity.PREFERENCE_SET_BIOMETRIC, false) - fun isHardwareDetected(): Boolean { - return biometricManager.canAuthenticate(BIOMETRIC_WEAK) != BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE && + fun isHardwareDetected(): Boolean = + biometricManager.canAuthenticate(BIOMETRIC_WEAK) != BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE && biometricManager.canAuthenticate(BIOMETRIC_WEAK) != BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE - } - fun hasEnrolledBiometric(): Boolean { - return biometricManager.canAuthenticate(BIOMETRIC_WEAK) != BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED - } + fun hasEnrolledBiometric(): Boolean = + biometricManager.canAuthenticate(BIOMETRIC_WEAK) != BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/biometric/BiometricViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/biometric/BiometricViewModel.kt index 62d2a563208..43ab030df4c 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/biometric/BiometricViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/biometric/BiometricViewModel.kt @@ -146,11 +146,10 @@ class BiometricViewModel( return if (pinString.isEmpty()) null else pinString } - fun isBiometricLockAvailable(): Boolean { - return if (!BiometricManager.isHardwareDetected()) { // Biometric not supported + fun isBiometricLockAvailable(): Boolean = + if (!BiometricManager.isHardwareDetected()) { // Biometric not supported false } else BiometricManager.hasEnrolledBiometric() // Biometric not enrolled - } companion object { private const val ANDROID_KEY_STORE = "AndroidKeyStore" diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt index ea1e6589dd7..a8dbac100ed 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt @@ -431,8 +431,8 @@ class PassCodeActivity : AppCompatActivity(), NumberKeyboardListener, EnableBiom } } - override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean { - return when (keyCode) { + override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean = + when (keyCode) { in KeyEvent.KEYCODE_0..KeyEvent.KEYCODE_9 -> { val number = keyCode - KeyEvent.KEYCODE_0 @@ -454,7 +454,6 @@ class PassCodeActivity : AppCompatActivity(), NumberKeyboardListener, EnableBiom else -> super.onKeyUp(keyCode, event) } - } companion object { const val ACTION_CREATE = "ACTION_REQUEST_WITH_RESULT" diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeManager.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeManager.kt index 76be126d416..26e9dace002 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeManager.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeManager.kt @@ -83,9 +83,8 @@ object PassCodeManager { else false } - fun isPassCodeEnabled(): Boolean { - return preferencesProvider.getBoolean(PassCodeActivity.PREFERENCE_SET_PASSCODE, false) - } + fun isPassCodeEnabled(): Boolean = + preferencesProvider.getBoolean(PassCodeActivity.PREFERENCE_SET_PASSCODE, false) private fun askUserForPasscode(activity: Activity) { val i = Intent(appContext, PassCodeActivity::class.java).apply { diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/pattern/PatternManager.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/pattern/PatternManager.kt index 18a7a0d820e..63021b36851 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/pattern/PatternManager.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/pattern/PatternManager.kt @@ -76,9 +76,8 @@ object PatternManager { else false } - fun isPatternEnabled(): Boolean { - return preferencesProvider.getBoolean(PatternActivity.PREFERENCE_SET_PATTERN, false) - } + fun isPatternEnabled(): Boolean = + preferencesProvider.getBoolean(PatternActivity.PREFERENCE_SET_PATTERN, false) private fun askUserForPattern(activity: Activity) { val i = Intent(appContext, PatternActivity::class.java).apply { diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/advanced/AdvancedSettingsUtils.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/advanced/AdvancedSettingsUtils.kt index 60230781fe7..2a6753b7d47 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/advanced/AdvancedSettingsUtils.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/advanced/AdvancedSettingsUtils.kt @@ -25,13 +25,12 @@ const val PREFERENCE_REMOVE_LOCAL_FILES = "remove_local_files" enum class RemoveLocalFiles { NEVER, ONE_HOUR, TWELVE_HOURS, ONE_DAY, THIRTY_DAYS; - fun toMilliseconds(): Long { - return when (this) { + fun toMilliseconds(): Long = + when (this) { NEVER -> -1 ONE_HOUR -> 3_600_000 TWELVE_HOURS -> 43_200_000 ONE_DAY -> 86_400_000 THIRTY_DAYS -> 2_592_000_000 } - } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/advanced/SettingsAdvancedViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/advanced/SettingsAdvancedViewModel.kt index 537375bcec8..10f0a320f61 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/advanced/SettingsAdvancedViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/advanced/SettingsAdvancedViewModel.kt @@ -32,9 +32,8 @@ class SettingsAdvancedViewModel( private val workManagerProvider: WorkManagerProvider, ) : ViewModel() { - fun isHiddenFilesShown(): Boolean { - return preferencesProvider.getBoolean(PREF_SHOW_HIDDEN_FILES, false) - } + fun isHiddenFilesShown(): Boolean = + preferencesProvider.getBoolean(PREF_SHOW_HIDDEN_FILES, false) fun setShowHiddenFiles(hide: Boolean) { preferencesProvider.putBoolean(PREF_SHOW_HIDDEN_FILES, hide) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/automaticuploads/SettingsPictureUploadsViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/automaticuploads/SettingsPictureUploadsViewModel.kt index beedf878cc3..ae387a05428 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/automaticuploads/SettingsPictureUploadsViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/automaticuploads/SettingsPictureUploadsViewModel.kt @@ -212,13 +212,12 @@ class SettingsPictureUploadsViewModel( Timber.d("Picture uploads configuration updated. New configuration: $it") } - private fun handleSpaceName(spaceName: String?): String? { - return if (pictureUploadsSpace?.isPersonal == true) { + private fun handleSpaceName(spaceName: String?): String? = + if (pictureUploadsSpace?.isPersonal == true) { contextProvider.getString(R.string.bottom_nav_personal) } else { spaceName } - } fun getUploadPathString(): String { diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/automaticuploads/SettingsVideoUploadsViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/automaticuploads/SettingsVideoUploadsViewModel.kt index 89d88041c48..93bc09e2148 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/automaticuploads/SettingsVideoUploadsViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/automaticuploads/SettingsVideoUploadsViewModel.kt @@ -213,13 +213,12 @@ class SettingsVideoUploadsViewModel( Timber.d("Video uploads configuration updated. New configuration: $it") } - private fun handleSpaceName(spaceName: String?): String? { - return if (videoUploadsSpace?.isPersonal == true) { + private fun handleSpaceName(spaceName: String?): String? = + if (videoUploadsSpace?.isPersonal == true) { contextProvider.getString(R.string.bottom_nav_personal) } else { spaceName } - } fun getUploadPathString(): String { diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareActivity.kt index f66cdd5fdb5..7b776c9731b 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareActivity.kt @@ -311,12 +311,11 @@ class ShareActivity : FileActivity(), ShareFragmentListener { } // The main_menu won't be displayed - override fun onCreateOptionsMenu(menu: Menu): Boolean { - return false - } + override fun onCreateOptionsMenu(menu: Menu): Boolean = + false - override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean { - return if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { + override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean = + if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { if (findViewById(R.id.owncloud_app_bar).hasFocus()) { findViewById(R.id.share_fragment_container).requestFocus() } @@ -324,7 +323,6 @@ class ShareActivity : FileActivity(), ShareFragmentListener { } else { super.onKeyUp(keyCode, event) } - } companion object { const val TAG_SHARE_FRAGMENT = "SHARE_FRAGMENT" diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/SearchShareesFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/SearchShareesFragment.kt index f97a10181d4..d9d1de9f94e 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/SearchShareesFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/SearchShareesFragment.kt @@ -132,9 +132,8 @@ class SearchShareesFragment : Fragment(), // a user / group will be picked only if selected in the list of suggestions } - override fun onQueryTextChange(newText: String): Boolean { - return false // let it for the parent listener in the hierarchy / default behaviour - } + override fun onQueryTextChange(newText: String): Boolean = + false // let it for the parent listener in the hierarchy / default behaviour }) } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/UsersAndGroupsSearchProvider.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/UsersAndGroupsSearchProvider.kt index 014e393771d..4830d94b286 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/UsersAndGroupsSearchProvider.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/UsersAndGroupsSearchProvider.kt @@ -56,10 +56,9 @@ import java.util.Locale class UsersAndGroupsSearchProvider : ContentProvider() { private lateinit var uriMatcher: UriMatcher - override fun getType(uri: Uri): String? { + override fun getType(uri: Uri): String? = // TODO implement - return null - } + null override fun onCreate(): Boolean { try { @@ -240,20 +239,17 @@ class UsersAndGroupsSearchProvider : ContentProvider() { return response } - override fun insert(uri: Uri, values: ContentValues?): Uri? { + override fun insert(uri: Uri, values: ContentValues?): Uri? = // TODO implementation - return null - } + null - override fun delete(uri: Uri, selection: String?, selectionArgs: Array?): Int { + override fun delete(uri: Uri, selection: String?, selectionArgs: Array?): Int = // TODO implementation - return 0 - } + 0 - override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array?): Int { + override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array?): Int = // TODO implementation - return 0 - } + 0 /** * Show error genericErrorMessage @@ -298,8 +294,7 @@ class UsersAndGroupsSearchProvider : ContentProvider() { private set private val shareTypes = HashMap() - fun getShareType(authority: String?): ShareType? { - return shareTypes[authority] - } + fun getShareType(authority: String?): ShareType? = + shareTypes[authority] } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/transfers/TransfersAdapter.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/transfers/TransfersAdapter.kt index cd50af79117..c635ea91c8c 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/transfers/TransfersAdapter.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/transfers/TransfersAdapter.kt @@ -236,14 +236,13 @@ class TransfersAdapter( } } - private fun headerTitleStringRes(status: TransferStatus): Int { - return when (status) { + private fun headerTitleStringRes(status: TransferStatus): Int = + when (status) { TransferStatus.TRANSFER_IN_PROGRESS -> R.string.uploads_view_group_current_uploads TransferStatus.TRANSFER_FAILED -> R.string.uploads_view_group_failed_uploads TransferStatus.TRANSFER_SUCCEEDED -> R.string.uploads_view_group_finished_uploads TransferStatus.TRANSFER_QUEUED -> R.string.uploads_view_group_queued_uploads } - } fun setData(transfersWithSpace: List>) { val transfersGroupedByStatus = transfersWithSpace.groupBy { it.first.status } @@ -278,12 +277,11 @@ class TransfersAdapter( override fun getItemCount(): Int = transferItemsList.size - override fun getItemViewType(position: Int): Int { - return when (getItem(position)) { + override fun getItemViewType(position: Int): Int = + when (getItem(position)) { is TransferItem -> TransferRecyclerItemViewType.ITEM_VIEW_TRANSFER.ordinal is HeaderItem -> TransferRecyclerItemViewType.ITEM_VIEW_HEADER.ordinal } - } fun getItem(position: Int) = transferItemsList[position] diff --git a/owncloudApp/src/main/java/com/owncloud/android/providers/FileContentProvider.kt b/owncloudApp/src/main/java/com/owncloud/android/providers/FileContentProvider.kt index db8409ebdba..363ac937750 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/providers/FileContentProvider.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/providers/FileContentProvider.kt @@ -172,13 +172,12 @@ class FileContentProvider(val executors: Executors = Executors()) : ContentProvi return count } - override fun getType(uri: Uri): String { - return when (uriMatcher.match(uri)) { + override fun getType(uri: Uri): String = + when (uriMatcher.match(uri)) { ROOT_DIRECTORY -> ProviderTableMeta.CONTENT_TYPE SINGLE_FILE -> ProviderTableMeta.CONTENT_TYPE_ITEM else -> throw IllegalArgumentException("Unknown Uri id.$uri") } - } override fun insert(uri: Uri, values: ContentValues?): Uri? { val newUri: Uri? @@ -1309,14 +1308,12 @@ class FileContentProvider(val executors: Executors = Executors()) : ContentProvi } @Throws(FileNotFoundException::class) - override fun openFile(uri: Uri, mode: String, signal: CancellationSignal?): ParcelFileDescriptor? { - return super.openFile(uri, mode, signal) - } + override fun openFile(uri: Uri, mode: String, signal: CancellationSignal?): ParcelFileDescriptor? = + super.openFile(uri, mode, signal) @Throws(FileNotFoundException::class) - override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? { - return super.openFile(uri, mode) - } + override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? = + super.openFile(uri, mode) /** * Grants that total count of successful uploads stored is not greater than MAX_SUCCESSFUL_UPLOADS. diff --git a/owncloudApp/src/main/java/com/owncloud/android/providers/WorkManagerProvider.kt b/owncloudApp/src/main/java/com/owncloud/android/providers/WorkManagerProvider.kt index fac429a5949..fcdd00c71fd 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/providers/WorkManagerProvider.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/providers/WorkManagerProvider.kt @@ -119,14 +119,13 @@ class WorkManagerProvider( WorkManager.getInstance(context).enqueue(removeLocallyFilesWithLastUsageOlderThanGivenTimeWorker) } - fun getRunningUploadsWorkInfosLiveData(): LiveData> { - return WorkManager.getInstance(context).getRunningWorkInfosLiveData( + fun getRunningUploadsWorkInfosLiveData(): LiveData> = + WorkManager.getInstance(context).getRunningWorkInfosLiveData( listOf( UploadFileFromContentUriWorker::class.java.name, UploadFileFromFileSystemWorker::class.java.name ) ) - } fun cancelAllWorkByTag(tag: String) = WorkManager.getInstance(context).cancelAllWorkByTag(tag) diff --git a/owncloudApp/src/main/java/com/owncloud/android/providers/implementation/OCContextProvider.kt b/owncloudApp/src/main/java/com/owncloud/android/providers/implementation/OCContextProvider.kt index 20fe3f8d9be..9fdb07c3d50 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/providers/implementation/OCContextProvider.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/providers/implementation/OCContextProvider.kt @@ -35,7 +35,5 @@ class OCContextProvider(private val context: Context) : ContextProvider { override fun getContext(): Context = context - override fun isConnected(): Boolean { - return ConnectivityUtils.isAppConnected(context) - } + override fun isConnected(): Boolean = ConnectivityUtils.isAppConnected(context) } diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.kt index 61b0888a6fa..a4f61d56312 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.kt @@ -588,9 +588,8 @@ abstract class DrawerActivity : ToolbarActivity() { * @param id the view's id * @return The view if found or `null` otherwise. */ - private fun findNavigationViewChildById(id: Int): View { - return (findViewById(R.id.nav_view) as NavigationView).getHeaderView(0).findViewById(id) - } + private fun findNavigationViewChildById(id: Int): View = + (findViewById(R.id.nav_view) as NavigationView).getHeaderView(0).findViewById(id) /** * Adds other listeners to react on changes of the drawer layout. diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt index 05bb09b3e72..d1bdbfca5fd 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt @@ -1979,8 +1979,8 @@ class FileDisplayActivity : FileActivity(), } } - override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean { - return if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { + override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean = + if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { if (findViewById(R.id.owncloud_app_bar).hasFocus()) { findViewById(R.id.left_fragment_container).requestFocus() } @@ -1988,7 +1988,6 @@ class FileDisplayActivity : FileActivity(), } else { super.onKeyUp(keyCode, event) } - } companion object { private const val TAG_LIST_OF_FILES = "LIST_OF_FILES" diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FolderPickerActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FolderPickerActivity.kt index 775c9f7a03f..df437106b7d 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FolderPickerActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FolderPickerActivity.kt @@ -366,13 +366,12 @@ open class FolderPickerActivity : FileActivity(), MOVE, COPY, CAMERA_FOLDER; @StringRes - fun toStringRes(): Int { - return when (this) { + fun toStringRes(): Int = + when (this) { MOVE -> R.string.folder_picker_move_here_button_text COPY -> R.string.folder_picker_copy_here_button_text CAMERA_FOLDER -> R.string.folder_picker_choose_button_text } - } } companion object { diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/errorhandling/ErrorMessageAdapter.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/errorhandling/ErrorMessageAdapter.kt index 90242cb1f1f..9614d60e9bb 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/errorhandling/ErrorMessageAdapter.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/errorhandling/ErrorMessageAdapter.kt @@ -49,29 +49,23 @@ class ErrorMessageAdapter { private class Formatter(val resources: Resources) { - fun format(resId: Int): String { - return resources.getString(resId) - } + fun format(resId: Int): String = + resources.getString(resId) - fun format(resId: Int, m1: String?): String { - return String.format(resources.getString(resId), m1) - } + fun format(resId: Int, m1: String?): String = + String.format(resources.getString(resId), m1) - fun format(resId: Int, m1: Int): String { - return String.format(resources.getString(resId), resources.getString(m1)) - } + fun format(resId: Int, m1: Int): String = + String.format(resources.getString(resId), resources.getString(m1)) - fun format(resId: Int, m1: String, m2: String): String { - return String.format(resources.getString(resId), m1, m2) - } + fun format(resId: Int, m1: String, m2: String): String = + String.format(resources.getString(resId), m1, m2) - fun format(resId: Int, m1: String?, m2: Int): String { - return String.format(resources.getString(resId), m1, resources.getString(m2)) - } + fun format(resId: Int, m1: String?, m2: Int): String = + String.format(resources.getString(resId), m1, resources.getString(m2)) - fun forbidden(resId1: Int): String { - return String.format(resources.getString(R.string.forbidden_permissions), resources.getString(resId1)) - } + fun forbidden(resId1: Int): String = + String.format(resources.getString(R.string.forbidden_permissions), resources.getString(resId1)) } companion object { @@ -114,8 +108,8 @@ class ErrorMessageAdapter { formatter: Formatter, throwable: Throwable, transferOperation: TransferOperation.Upload - ): String { - return when (throwable) { + ): String = + when (throwable) { is LocalStorageFullException -> formatter.format( R.string.error__upload__local_file_not_copied, transferOperation.fileName, R.string.app_name @@ -143,7 +137,6 @@ class ErrorMessageAdapter { else -> formatter.format(R.string.uploader_upload_failed_content_single, transferOperation.fileName) } - } /** * Return an internationalized user message corresponding to an operation result diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewAudioFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewAudioFragment.kt index a02d50d26d0..ad07c8fe194 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewAudioFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewAudioFragment.kt @@ -267,8 +267,8 @@ class PreviewAudioFragment : FileFragment() { /** * {@inheritDoc} */ - override fun onOptionsItemSelected(item: MenuItem): Boolean { - return when (item.itemId) { + override fun onOptionsItemSelected(item: MenuItem): Boolean = + when (item.itemId) { R.id.action_share_file -> { mContainerActivity.fileOperationsHelper.showShareFile(file) true @@ -314,7 +314,6 @@ class PreviewAudioFragment : FileFragment() { else -> super.onOptionsItemSelected(item) } - } private fun seeDetails() { mContainerActivity.showDetails(file) diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewFormatTextFragmentStateAdapter.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewFormatTextFragmentStateAdapter.kt index 27fd5f69b72..0740e39edad 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewFormatTextFragmentStateAdapter.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewFormatTextFragmentStateAdapter.kt @@ -46,18 +46,16 @@ class PreviewFormatTextFragmentStateAdapter( override fun getItemCount(): Int = 2 - override fun createFragment(position: Int): Fragment { - return if (position == 0) { + override fun createFragment(position: Int): Fragment = + if (position == 0) { PreviewFormatTextFragment.newInstance(text, mimeType) } else { PreviewFormatTextFragment.newInstance(text) } - } class PreviewFormatTextFragment : Fragment() { - override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { - return inflater.inflate(R.layout.preview_format_text_fragment, container, false) - } + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = + inflater.inflate(R.layout.preview_format_text_fragment, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.kt index e8c1a7bb3ec..bef837cf6f5 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.kt @@ -252,8 +252,8 @@ class PreviewImageActivity : FileActivity(), } } - override fun onOptionsItemSelected(item: MenuItem): Boolean { - return if (item.itemId == android.R.id.home) { + override fun onOptionsItemSelected(item: MenuItem): Boolean = + if (item.itemId == android.R.id.home) { if (isDrawerOpen()) { closeDrawer() } else { @@ -263,7 +263,6 @@ class PreviewImageActivity : FileActivity(), } else { super.onOptionsItemSelected(item) } - } override fun onResume() { super.onResume() @@ -405,18 +404,16 @@ class PreviewImageActivity : FileActivity(), } // The main_menu won't be displayed - override fun onCreateOptionsMenu(menu: Menu): Boolean { - return false - } + override fun onCreateOptionsMenu(menu: Menu): Boolean = + false - override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean { - return if (keyCode == KeyEvent.KEYCODE_TAB) { + override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean = + if (keyCode == KeyEvent.KEYCODE_TAB) { showSystemUI(fullScreenAnchorView) true } else { super.onKeyUp(keyCode, event) } - } companion object { private const val INITIAL_HIDE_DELAY = 0 // immediate hide diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageFragment.kt index a3e0bdd3dfc..77e1bd7411a 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageFragment.kt @@ -214,8 +214,8 @@ class PreviewImageFragment : FileFragment() { /** * {@inheritDoc} */ - override fun onOptionsItemSelected(item: MenuItem): Boolean { - return when (item.itemId) { + override fun onOptionsItemSelected(item: MenuItem): Boolean = + when (item.itemId) { R.id.action_share_file -> { mContainerActivity.fileOperationsHelper.showShareFile(file) true @@ -261,7 +261,6 @@ class PreviewImageFragment : FileFragment() { else -> super.onOptionsItemSelected(item) } - } private fun seeDetails() { mContainerActivity.showDetails(file) @@ -345,9 +344,8 @@ class PreviewImageFragment : FileFragment() { private fun isSVGFile(file: OCFile): Boolean = file.mimeType == MIME_SVG - private fun getBackgroundColor(file: OCFile): Int { - return if (isSVGFile(file)) Color.WHITE else Color.BLACK - } + private fun getBackgroundColor(file: OCFile): Int = + if (isSVGFile(file)) Color.WHITE else Color.BLACK /** * Finishes the preview @@ -393,8 +391,7 @@ class PreviewImageFragment : FileFragment() { * @return 'True' if the file can be handled by the fragment. */ @JvmStatic - fun canBePreviewed(file: OCFile?): Boolean { - return file != null && file.isImage - } + fun canBePreviewed(file: OCFile?): Boolean = + file != null && file.isImage } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewTextFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewTextFragment.kt index b56c0ea2bf3..48124216a09 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewTextFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewTextFragment.kt @@ -135,8 +135,8 @@ class PreviewTextFragment : FileFragment() { } } - override fun onOptionsItemSelected(item: MenuItem): Boolean { - return when (item.itemId) { + override fun onOptionsItemSelected(item: MenuItem): Boolean = + when (item.itemId) { R.id.action_share_file -> { mContainerActivity.fileOperationsHelper.showShareFile(file) true @@ -187,7 +187,6 @@ class PreviewTextFragment : FileFragment() { super.onOptionsItemSelected(item) } } - } override fun onDestroyView() { super.onDestroyView() diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewVideoActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewVideoActivity.kt index 072ef4d7955..09ae1241779 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewVideoActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewVideoActivity.kt @@ -368,8 +368,8 @@ class PreviewVideoActivity : FileActivity(), Player.Listener, OnPrepareVideoPlay } } - override fun onMenuItemSelected(menuItem: MenuItem): Boolean { - return when (menuItem.itemId) { + override fun onMenuItemSelected(menuItem: MenuItem): Boolean = + when (menuItem.itemId) { R.id.action_share_file -> { fileOperationsHelper.showShareFile(file) true @@ -440,12 +440,10 @@ class PreviewVideoActivity : FileActivity(), Player.Listener, OnPrepareVideoPlay false } } - } // The main_menu won't be displayed - override fun onCreateOptionsMenu(menu: Menu): Boolean { - return false - } + override fun onCreateOptionsMenu(menu: Menu): Boolean = + false companion object { const val EXTRA_FILE = "FILE" @@ -470,8 +468,7 @@ class PreviewVideoActivity : FileActivity(), Player.Listener, OnPrepareVideoPlay * @param file File to test if can be previewed. * @return 'True' if the file can be handled by the fragment. */ - fun canBePreviewed(file: OCFile?): Boolean { - return file != null && file.isVideo - } + fun canBePreviewed(file: OCFile?): Boolean = + file != null && file.isVideo } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/usecases/synchronization/SynchronizeFileUseCase.kt b/owncloudApp/src/main/java/com/owncloud/android/usecases/synchronization/SynchronizeFileUseCase.kt index 1a1181b3e62..ff96526f3bd 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/usecases/synchronization/SynchronizeFileUseCase.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/usecases/synchronization/SynchronizeFileUseCase.kt @@ -112,17 +112,16 @@ class SynchronizeFileUseCase( } } - private fun requestForDownload(accountName: String, ocFile: OCFile): UUID? { - return downloadFileUseCase( + private fun requestForDownload(accountName: String, ocFile: OCFile): UUID? = + downloadFileUseCase( DownloadFileUseCase.Params( accountName = accountName, file = ocFile ) ) - } - private fun requestForUpload(accountName: String, ocFile: OCFile): UUID? { - return uploadFileInConflictUseCase( + private fun requestForUpload(accountName: String, ocFile: OCFile): UUID? = + uploadFileInConflictUseCase( UploadFileInConflictUseCase.Params( accountName = accountName, localPath = ocFile.storagePath!!, @@ -130,7 +129,6 @@ class SynchronizeFileUseCase( spaceId = ocFile.spaceId, ) ) - } data class Params( val fileToSynchronize: OCFile, diff --git a/owncloudApp/src/main/java/com/owncloud/android/usecases/transfers/uploads/RetryFailedUploadsForAccountUseCase.kt b/owncloudApp/src/main/java/com/owncloud/android/usecases/transfers/uploads/RetryFailedUploadsForAccountUseCase.kt index c820a021bdc..ae38a7b442e 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/usecases/transfers/uploads/RetryFailedUploadsForAccountUseCase.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/usecases/transfers/uploads/RetryFailedUploadsForAccountUseCase.kt @@ -54,9 +54,8 @@ class RetryFailedUploadsForAccountUseCase( } } - private fun isContentUri(context: Context, upload: OCTransfer): Boolean { - return DocumentFile.isDocumentUri(context, Uri.parse(upload.localPath)) - } + private fun isContentUri(context: Context, upload: OCTransfer): Boolean = + DocumentFile.isDocumentUri(context, Uri.parse(upload.localPath)) data class Params( val accountName: String diff --git a/owncloudApp/src/main/java/com/owncloud/android/utils/NotificationUtils.kt b/owncloudApp/src/main/java/com/owncloud/android/utils/NotificationUtils.kt index 74d72d666dc..a63c0b6f86f 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/utils/NotificationUtils.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/utils/NotificationUtils.kt @@ -49,12 +49,11 @@ object NotificationUtils { const val pendingIntentFlags = PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT @JvmStatic - fun newNotificationBuilder(context: Context, channelId: String): NotificationCompat.Builder { - return NotificationCompat.Builder(context, channelId).apply { + fun newNotificationBuilder(context: Context, channelId: String): NotificationCompat.Builder = + NotificationCompat.Builder(context, channelId).apply { color = ContextCompat.getColor(context, R.color.primary) setSmallIcon(R.drawable.notification_icon) } - } fun createBasicNotification( context: Context, diff --git a/owncloudApp/src/main/java/com/owncloud/android/utils/SortFilesUtils.kt b/owncloudApp/src/main/java/com/owncloud/android/utils/SortFilesUtils.kt index 7e1498e1598..063db23cecc 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/utils/SortFilesUtils.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/utils/SortFilesUtils.kt @@ -26,13 +26,12 @@ class SortFilesUtils { listOfFiles: List, sortTypeValue: Int, ascending: Boolean, - ): List { - return when (SortType.fromPreference(sortTypeValue)) { + ): List = + when (SortType.fromPreference(sortTypeValue)) { SortType.SORT_TYPE_BY_NAME -> sortByName(listOfFiles, ascending) SortType.SORT_TYPE_BY_SIZE -> sortBySize(listOfFiles, ascending) SortType.SORT_TYPE_BY_DATE -> sortByDate(listOfFiles, ascending) } - } private fun sortByName(listOfFiles: List, ascending: Boolean): List { val newListOfFiles = @@ -43,13 +42,11 @@ class SortFilesUtils { return newListOfFiles.sortedByDescending { it.isFolder } } - private fun sortBySize(listOfFiles: List, ascending: Boolean): List { - return if (ascending) listOfFiles.sortedBy { it.length } + private fun sortBySize(listOfFiles: List, ascending: Boolean): List = + if (ascending) listOfFiles.sortedBy { it.length } else listOfFiles.sortedByDescending { it.length } - } - private fun sortByDate(listOfFiles: List, ascending: Boolean): List { - return if (ascending) listOfFiles.sortedBy { it.modificationTimestamp } + private fun sortByDate(listOfFiles: List, ascending: Boolean): List = + if (ascending) listOfFiles.sortedBy { it.modificationTimestamp } else listOfFiles.sortedByDescending { it.modificationTimestamp } - } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/workers/AvailableOfflinePeriodicWorker.kt b/owncloudApp/src/main/java/com/owncloud/android/workers/AvailableOfflinePeriodicWorker.kt index 16652490fe2..9695db105bf 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/workers/AvailableOfflinePeriodicWorker.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/workers/AvailableOfflinePeriodicWorker.kt @@ -42,9 +42,8 @@ class AvailableOfflinePeriodicWorker( private val synchronizeFileUseCase: SynchronizeFileUseCase by inject() private val synchronizeFolderUseCase: SynchronizeFolderUseCase by inject() - override suspend fun doWork(): Result { - - return try { + override suspend fun doWork(): Result = + try { val availableOfflineFiles = getFilesAvailableOfflineFromEveryAccountUseCase(Unit) Timber.i("Available offline files that needs to be synced: ${availableOfflineFiles.size}") @@ -54,7 +53,6 @@ class AvailableOfflinePeriodicWorker( } catch (exception: Exception) { Result.failure() } - } private fun syncAvailableOfflineFiles(availableOfflineFiles: List) { availableOfflineFiles.forEach { diff --git a/owncloudApp/src/main/java/com/owncloud/android/workers/OldLogsCollectorWorker.kt b/owncloudApp/src/main/java/com/owncloud/android/workers/OldLogsCollectorWorker.kt index e632c79e50c..08889d6a82a 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/workers/OldLogsCollectorWorker.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/workers/OldLogsCollectorWorker.kt @@ -58,9 +58,8 @@ class OldLogsCollectorWorker( return File(logsPath) } - private fun getLogsFiles(logsFolder: File): List { - return logsFolder.listFiles()?.toList() ?: listOf() - } + private fun getLogsFiles(logsFolder: File): List = + logsFolder.listFiles()?.toList() ?: listOf() private fun removeOldLogs(logFiles: List) { logFiles.forEach { log -> diff --git a/owncloudApp/src/main/java/com/owncloud/android/workers/RemoveLocallyFilesWithLastUsageOlderThanGivenTimeWorker.kt b/owncloudApp/src/main/java/com/owncloud/android/workers/RemoveLocallyFilesWithLastUsageOlderThanGivenTimeWorker.kt index 0c762d73be7..5b94e3be523 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/workers/RemoveLocallyFilesWithLastUsageOlderThanGivenTimeWorker.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/workers/RemoveLocallyFilesWithLastUsageOlderThanGivenTimeWorker.kt @@ -41,9 +41,8 @@ class RemoveLocallyFilesWithLastUsageOlderThanGivenTimeWorker( ), KoinComponent { private val removeLocallyFilesWithLastUsageOlderThanGivenTimeUseCase: RemoveLocallyFilesWithLastUsageOlderThanGivenTimeUseCase by inject() - override suspend fun doWork(): Result { - - return try { + override suspend fun doWork(): Result = + try { removeLocallyFilesWithLastUsageOlderThanGivenTimeUseCase( RemoveLocallyFilesWithLastUsageOlderThanGivenTimeUseCase.Params( idFilePreviewing = filePreviewing(), @@ -53,17 +52,15 @@ class RemoveLocallyFilesWithLastUsageOlderThanGivenTimeWorker( } catch (exception: Exception) { Result.failure() } - } - private fun filePreviewing(): String? { - return when { + private fun filePreviewing(): String? = + when { PreviewVideoActivity.isOpen -> PreviewVideoActivity.currentFilePreviewing?.remoteId PreviewTextFragment.isOpen -> PreviewTextFragment.currentFilePreviewing?.remoteId PreviewImageFragment.isOpen -> PreviewImageFragment.currentFilePreviewing?.remoteId PreviewAudioFragment.isOpen -> PreviewAudioFragment.currentFilePreviewing?.remoteId else -> null } - } companion object { const val DELETE_FILES_OLDER_GIVEN_TIME_WORKER = "DELETE_FILES_OLDER_GIVEN_TIME_WORKER" diff --git a/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromContentUriWorker.kt b/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromContentUriWorker.kt index 363cdec24a4..33cbeb94064 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromContentUriWorker.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromContentUriWorker.kt @@ -149,8 +149,8 @@ class UploadFileFromContentUriWorker( return true } - private fun retrieveUploadInfoFromDatabase(): OCTransfer? { - return transferRepository.getTransferById(uploadIdInStorageManager).also { + private fun retrieveUploadInfoFromDatabase(): OCTransfer? = + transferRepository.getTransferById(uploadIdInStorageManager).also { if (it != null) { Timber.d("Upload with id ($uploadIdInStorageManager) has been found in database.") Timber.d("Upload info: $it") @@ -159,7 +159,6 @@ class UploadFileFromContentUriWorker( Timber.w("$uploadPath won't be uploaded") } } - } private fun checkDocumentFileExists() { val documentFile = DocumentFile.fromSingleUri(appContext, contentUri) @@ -324,13 +323,12 @@ class UploadFileFromContentUriWorker( ) } - private fun getUploadStatusForThrowable(throwable: Throwable?): TransferStatus { - return if (throwable == null) { + private fun getUploadStatusForThrowable(throwable: Throwable?): TransferStatus = + if (throwable == null) { TransferStatus.TRANSFER_SUCCEEDED } else { TransferStatus.TRANSFER_FAILED } - } private fun showNotification(throwable: Throwable) { // check credentials error diff --git a/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromFileSystemWorker.kt b/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromFileSystemWorker.kt index 3fb62cf9a00..7bd883ef8a5 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromFileSystemWorker.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromFileSystemWorker.kt @@ -147,8 +147,8 @@ class UploadFileFromFileSystemWorker( return true } - private fun retrieveUploadInfoFromDatabase(): OCTransfer? { - return transferRepository.getTransferById(uploadIdInStorageManager).also { + private fun retrieveUploadInfoFromDatabase(): OCTransfer? = + transferRepository.getTransferById(uploadIdInStorageManager).also { if (it != null) { Timber.d("Upload with id ($uploadIdInStorageManager) has been found in database.") Timber.d("Upload info: $it") @@ -157,7 +157,6 @@ class UploadFileFromFileSystemWorker( Timber.w("$uploadPath won't be uploaded") } } - } private fun checkPermissionsToReadDocumentAreGranted() { val fileInFileSystem = File(fileSystemPath) @@ -312,13 +311,12 @@ class UploadFileFromFileSystemWorker( ) } - private fun getUploadStatusForThrowable(throwable: Throwable?): TransferStatus { - return if (throwable == null) { + private fun getUploadStatusForThrowable(throwable: Throwable?): TransferStatus = + if (throwable == null) { TransferStatus.TRANSFER_SUCCEEDED } else { TransferStatus.TRANSFER_FAILED } - } /** * Update the database with latest details about this file. From 855a40fdcdfc63b9ffe89b29fec220cc9fcc3281 Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Thu, 9 Jan 2025 15:02:18 +0100 Subject: [PATCH 34/74] style: changed functions with just return to expression body in module `owncloudComLibrary` --- .../lib/common/http/logging/LogInterceptor.kt | 5 ++--- .../lib/common/http/methods/HttpBaseMethod.kt | 20 ++++++++----------- .../common/http/methods/webdav/DavMethod.kt | 5 ++--- .../network/ChunkFromFileRequestBody.kt | 5 ++--- .../common/network/ContentUriRequestBody.kt | 5 ++--- .../android/lib/common/utils/AnyExt.kt | 5 ++--- ...reateRemoteFileWithAppProviderOperation.kt | 5 ++--- .../GetUrlToOpenInWebRemoteOperation.kt | 5 ++--- .../files/GetBaseUrlRemoteOperation.kt | 5 ++--- .../android/lib/resources/files/RemoteFile.kt | 5 ++--- .../UploadFileFromContentUriOperation.kt | 5 ++--- .../UploadFileFromFileSystemOperation.kt | 5 ++--- .../spaces/services/OCSpacesService.kt | 5 ++--- .../lib/resources/status/OwnCloudVersion.kt | 10 ++++------ .../lib/resources/status/RemoteCapability.kt | 10 ++++------ .../lib/resources/status/StatusRequester.kt | 5 ++--- 16 files changed, 42 insertions(+), 63 deletions(-) diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/logging/LogInterceptor.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/logging/LogInterceptor.kt index ecce97d7ea7..d8ab9ba89f9 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/logging/LogInterceptor.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/logging/LogInterceptor.kt @@ -156,15 +156,14 @@ class LogInterceptor : Interceptor { ) } - private fun getResponseBodyString(contentType: MediaType?, contentLength: Int, responseBody: String): String? { - return if (contentType?.isLoggable() == true) { + private fun getResponseBodyString(contentType: MediaType?, contentLength: Int, responseBody: String): String? = + if (contentType?.isLoggable() == true) { responseBody } else if (contentLength > 0) { "$BINARY_OMITTED $contentLength $BYTES" } else { null } - } private fun getDurationString(millis: Long): String { var auxMillis = millis diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/HttpBaseMethod.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/HttpBaseMethod.kt index d7a0d6ddef7..9974412ea11 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/HttpBaseMethod.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/HttpBaseMethod.kt @@ -85,9 +85,8 @@ abstract class HttpBaseMethod constructor(url: URL) { *** Requests *** ****************/ - fun getRequestHeader(name: String): String? { - return request.header(name) - } + fun getRequestHeader(name: String): String? = + request.header(name) fun getRequestHeadersAsHashMap(): HashMap { val headers: HashMap = HashMap() @@ -126,20 +125,17 @@ abstract class HttpBaseMethod constructor(url: URL) { get() = response.message // Headers - open fun getResponseHeaders(): Headers? { - return response.headers - } + open fun getResponseHeaders(): Headers? = + response.headers - open fun getResponseHeader(headerName: String): String? { - return response.header(headerName) - } + open fun getResponseHeader(headerName: String): String? = + response.header(headerName) // Body fun getResponseBodyAsString(): String = response.peekBody(Long.MAX_VALUE).string() - open fun getResponseBodyAsStream(): InputStream? { - return response.body?.byteStream() - } + open fun getResponseBodyAsStream(): InputStream? = + response.body?.byteStream() /** * returns the final url after following the last redirect. diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/DavMethod.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/DavMethod.kt index 100177ec50c..1f551d76a54 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/DavMethod.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/DavMethod.kt @@ -51,8 +51,8 @@ abstract class DavMethod protected constructor(url: URL) : HttpBaseMethod(url) { protected abstract fun onDavExecute(davResource: DavOCResource): Int @Throws(Exception::class) - override fun onExecute(okHttpClient: OkHttpClient): Int { - return try { + override fun onExecute(okHttpClient: OkHttpClient): Int = + try { davResource = DavOCResource( okHttpClient.newBuilder().followRedirects(false).build(), httpUrl, @@ -84,7 +84,6 @@ abstract class DavMethod protected constructor(url: URL) : HttpBaseMethod(url) { } httpException.code } - } ////////////////////////////// // Getter diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/network/ChunkFromFileRequestBody.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/network/ChunkFromFileRequestBody.kt index b1404b9c913..75d55685c3f 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/network/ChunkFromFileRequestBody.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/network/ChunkFromFileRequestBody.kt @@ -51,9 +51,8 @@ class ChunkFromFileRequestBody( require(chunkSize > 0) { "Chunk size must be greater than zero" } } - override fun contentLength(): Long { - return chunkSize.coerceAtMost(channel.size() - channel.position()) - } + override fun contentLength(): Long = + chunkSize.coerceAtMost(channel.size() - channel.position()) override fun writeTo(sink: BufferedSink) { var readCount: Int diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/network/ContentUriRequestBody.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/network/ContentUriRequestBody.kt index ca4e31a9cb2..b3dfd5cf1ca 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/network/ContentUriRequestBody.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/network/ContentUriRequestBody.kt @@ -54,9 +54,8 @@ class ContentUriRequestBody( return contentType.toMediaTypeOrNull() } - override fun contentLength(): Long { - return fileSize - } + override fun contentLength(): Long = + fileSize override fun writeTo(sink: BufferedSink) { val inputStream = contentResolver.openInputStream(contentUri) diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/utils/AnyExt.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/utils/AnyExt.kt index 462ca9759af..6b52c0d2bcf 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/utils/AnyExt.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/utils/AnyExt.kt @@ -24,6 +24,5 @@ package com.owncloud.android.lib.common.utils -fun Any.isOneOf(vararg values: Any): Boolean { - return this in values -} +fun Any.isOneOf(vararg values: Any): Boolean = + this in values diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/appregistry/CreateRemoteFileWithAppProviderOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/appregistry/CreateRemoteFileWithAppProviderOperation.kt index 9428b5c8c3e..04bcc798877 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/appregistry/CreateRemoteFileWithAppProviderOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/appregistry/CreateRemoteFileWithAppProviderOperation.kt @@ -47,8 +47,8 @@ class CreateRemoteFileWithAppProviderOperation( private val filename: String, ) : RemoteOperation() { - override fun run(client: OwnCloudClient): RemoteOperationResult { - return try { + override fun run(client: OwnCloudClient): RemoteOperationResult = + try { val createFileWithAppProviderRequestBody = CreateFileWithAppProviderParams(parentContainerId, filename) .toRequestBody() @@ -77,7 +77,6 @@ class CreateRemoteFileWithAppProviderOperation( Timber.e(e, "Create file $filename with app provider in folder with ID $parentContainerId failed") result } - } private fun isSuccess(status: Int) = status == HttpConstants.HTTP_OK diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/appregistry/GetUrlToOpenInWebRemoteOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/appregistry/GetUrlToOpenInWebRemoteOperation.kt index 84b325142b6..1dfe6ebb453 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/appregistry/GetUrlToOpenInWebRemoteOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/appregistry/GetUrlToOpenInWebRemoteOperation.kt @@ -46,8 +46,8 @@ class GetUrlToOpenInWebRemoteOperation( private val appName: String, ) : RemoteOperation() { - override fun run(client: OwnCloudClient): RemoteOperationResult { - return try { + override fun run(client: OwnCloudClient): RemoteOperationResult = + try { val openInWebRequestBody = OpenInWebParams(fileId, appName).toRequestBody() @@ -75,7 +75,6 @@ class GetUrlToOpenInWebRemoteOperation( Timber.e(e, "Open in web for file: $fileId failed") result } - } private fun isSuccess(status: Int) = status == HttpConstants.HTTP_OK diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/GetBaseUrlRemoteOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/GetBaseUrlRemoteOperation.kt index 2fd6ab35cb5..88c39655c82 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/GetBaseUrlRemoteOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/GetBaseUrlRemoteOperation.kt @@ -40,8 +40,8 @@ import java.util.concurrent.TimeUnit */ class GetBaseUrlRemoteOperation : RemoteOperation() { - override fun run(client: OwnCloudClient): RemoteOperationResult { - return try { + override fun run(client: OwnCloudClient): RemoteOperationResult = + try { val stringUrl = client.baseFilesWebDavUri.toString() val propFindMethod = PropfindMethod(URL(stringUrl), 0, DavUtils.allPropSet).apply { @@ -64,7 +64,6 @@ class GetBaseUrlRemoteOperation : RemoteOperation() { Timber.e(e, "Could not get actuall (or redirected) base URL from base url (/).") RemoteOperationResult(e) } - } private fun isSuccess(status: Int) = status == HttpConstants.HTTP_OK || status == HttpConstants.HTTP_MULTI_STATUS diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/RemoteFile.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/RemoteFile.kt index 16ec6748d6a..33e99785ae6 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/RemoteFile.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/RemoteFile.kt @@ -182,12 +182,11 @@ data class RemoteFile( return absoluteDavPath.replace(pathToOc + davFilesPath, "") } - private fun getPropertiesEvenIfPostProcessing(response: Response): List { - return if (response.isSuccess()) + private fun getPropertiesEvenIfPostProcessing(response: Response): List = + if (response.isSuccess()) response.propstat.filter { propStat -> propStat.isSuccessOrPostProcessing() }.map { it.properties }.flatten() else emptyList() - } private fun PropStat.isSuccessOrPostProcessing() = (status.code / 100 == 2 || status.code == HttpConstants.HTTP_TOO_EARLY) } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/UploadFileFromContentUriOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/UploadFileFromContentUriOperation.kt index a2f2cb26ebf..ebe95d229c1 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/UploadFileFromContentUriOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/UploadFileFromContentUriOperation.kt @@ -62,7 +62,6 @@ class UploadFileFromContentUriOperation( } } - fun isSuccess(status: Int): Boolean { - return status.isOneOf(HttpConstants.HTTP_OK, HttpConstants.HTTP_CREATED, HttpConstants.HTTP_NO_CONTENT) - } + fun isSuccess(status: Int): Boolean = + status.isOneOf(HttpConstants.HTTP_OK, HttpConstants.HTTP_CREATED, HttpConstants.HTTP_NO_CONTENT) } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/UploadFileFromFileSystemOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/UploadFileFromFileSystemOperation.kt index f8dcc722800..a625a81d90f 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/UploadFileFromFileSystemOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/UploadFileFromFileSystemOperation.kt @@ -152,7 +152,6 @@ open class UploadFileFromFileSystemOperation( } } - fun isSuccess(status: Int): Boolean { - return status.isOneOf(HttpConstants.HTTP_OK, HttpConstants.HTTP_CREATED, HttpConstants.HTTP_NO_CONTENT) - } + fun isSuccess(status: Int): Boolean = + status.isOneOf(HttpConstants.HTTP_OK, HttpConstants.HTTP_CREATED, HttpConstants.HTTP_NO_CONTENT) } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/spaces/services/OCSpacesService.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/spaces/services/OCSpacesService.kt index 2f29601d68b..37c65b72bd7 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/spaces/services/OCSpacesService.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/spaces/services/OCSpacesService.kt @@ -28,7 +28,6 @@ import com.owncloud.android.lib.resources.spaces.GetRemoteSpacesOperation import com.owncloud.android.lib.resources.spaces.responses.SpaceResponse class OCSpacesService(override val client: OwnCloudClient) : SpacesService { - override fun getSpaces(): RemoteOperationResult> { - return GetRemoteSpacesOperation().execute(client) - } + override fun getSpaces(): RemoteOperationResult> = + GetRemoteSpacesOperation().execute(client) } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/OwnCloudVersion.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/OwnCloudVersion.kt index c73805b894c..226bcade362 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/OwnCloudVersion.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/OwnCloudVersion.kt @@ -83,11 +83,10 @@ class OwnCloudVersion(version: String) : Comparable, Parcelable return versionToString } - override fun compareTo(other: OwnCloudVersion): Int { - return if (other.mVersion == mVersion) + override fun compareTo(other: OwnCloudVersion): Int = + if (other.mVersion == mVersion) 0 else if (other.mVersion < mVersion) 1 else -1 - } private fun parseVersion(version: String) { try { @@ -122,9 +121,8 @@ class OwnCloudVersion(version: String) : Comparable, Parcelable return versionValue } - override fun describeContents(): Int { - return super.hashCode() - } + override fun describeContents(): Int = + super.hashCode() override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeInt(mVersion) diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/RemoteCapability.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/RemoteCapability.kt index ed470f8b27f..81718bb25bf 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/RemoteCapability.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/RemoteCapability.kt @@ -92,22 +92,20 @@ data class RemoteCapability( TRUE(1); companion object { - fun fromValue(value: Int): CapabilityBooleanType? { - return when (value) { + fun fromValue(value: Int): CapabilityBooleanType? = + when (value) { -1 -> UNKNOWN 0 -> FALSE 1 -> TRUE else -> null } - } - fun fromBooleanValue(boolValue: Boolean?): CapabilityBooleanType { - return if (boolValue != null && boolValue) { + fun fromBooleanValue(boolValue: Boolean?): CapabilityBooleanType = + if (boolValue != null && boolValue) { TRUE } else { FALSE } - } } } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/StatusRequester.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/StatusRequester.kt index 813eaf9fd3d..09a3f71e040 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/StatusRequester.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/StatusRequester.kt @@ -63,12 +63,11 @@ internal class StatusRequester { return URL(oldLocationURL.protocol, oldLocationURL.host, oldLocationURL.port, redirectedLocation).toString() } - private fun getGetMethod(url: String): GetMethod { - return GetMethod(URL(url)).apply { + private fun getGetMethod(url: String): GetMethod = + GetMethod(URL(url)).apply { setReadTimeout(TRY_CONNECTION_TIMEOUT, TimeUnit.SECONDS) setConnectionTimeout(TRY_CONNECTION_TIMEOUT, TimeUnit.SECONDS) } - } data class RequestResult( val getMethod: GetMethod, From 277c163ea6d158eb650ede8649c682bba2028a6e Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Thu, 9 Jan 2025 19:17:34 +0100 Subject: [PATCH 35/74] style: changed functions with just return to expression body in module `owncloudData` --- .../owncloud/android/data/OwncloudDatabase.kt | 5 +-- .../OCLocalAppRegistryDataSource.kt | 5 +-- .../OCLocalAuthenticationDataSource.kt | 5 +-- .../repository/OCCapabilityRepository.kt | 5 +-- .../owncloud/android/data/files/db/FileDao.kt | 5 +-- .../android/data/files/db/OCFileEntity.kt | 5 +-- .../android/data/migrations/Migration_34.kt | 5 +-- .../oauth/repository/OCOAuthRepository.kt | 5 +-- .../data/providers/LocalStorageProvider.kt | 5 +-- .../data/sharing/shares/db/OCShareEntity.kt | 5 +-- .../shares/repository/OCShareRepository.kt | 15 +++---- .../implementation/OCLocalSpacesDataSource.kt | 40 ++++++++----------- .../OCLocalTransferDataSource.kt | 40 ++++++++----------- .../implementation/OCLocalUserDataSource.kt | 10 ++--- 14 files changed, 62 insertions(+), 93 deletions(-) diff --git a/owncloudData/src/main/java/com/owncloud/android/data/OwncloudDatabase.kt b/owncloudData/src/main/java/com/owncloud/android/data/OwncloudDatabase.kt index aeb5655cdae..c264391e816 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/OwncloudDatabase.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/OwncloudDatabase.kt @@ -117,10 +117,10 @@ abstract class OwncloudDatabase : RoomDatabase() { fun getDatabase( context: Context - ): OwncloudDatabase { + ): OwncloudDatabase = // if the INSTANCE is not null, then return it, // if it is, then create the database - return INSTANCE ?: synchronized(this) { + INSTANCE ?: synchronized(this) { val instance = Room.databaseBuilder( context.applicationContext, OwncloudDatabase::class.java, @@ -131,7 +131,6 @@ abstract class OwncloudDatabase : RoomDatabase() { INSTANCE = instance instance } - } @VisibleForTesting fun switchToInMemory(context: Context, vararg migrations: Migration) { diff --git a/owncloudData/src/main/java/com/owncloud/android/data/appregistry/datasources/implementation/OCLocalAppRegistryDataSource.kt b/owncloudData/src/main/java/com/owncloud/android/data/appregistry/datasources/implementation/OCLocalAppRegistryDataSource.kt index 860c9ee7977..825b8dee4be 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/appregistry/datasources/implementation/OCLocalAppRegistryDataSource.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/appregistry/datasources/implementation/OCLocalAppRegistryDataSource.kt @@ -62,8 +62,8 @@ class OCLocalAppRegistryDataSource( appRegistryDao.deleteAppRegistryForAccount(accountName) } - private fun AppRegistry.toEntities(accountName: String): List { - return mimetypes.map { appRegistryMimeTypes -> + private fun AppRegistry.toEntities(accountName: String): List = + mimetypes.map { appRegistryMimeTypes -> AppRegistryEntity( accountName = accountName, mimeType = appRegistryMimeTypes.mimeType, @@ -76,7 +76,6 @@ class OCLocalAppRegistryDataSource( defaultApplication = appRegistryMimeTypes.defaultApplication, ) } - } private fun AppRegistryEntity.toModel(): AppRegistryMimeType = AppRegistryMimeType( diff --git a/owncloudData/src/main/java/com/owncloud/android/data/authentication/datasources/implementation/OCLocalAuthenticationDataSource.kt b/owncloudData/src/main/java/com/owncloud/android/data/authentication/datasources/implementation/OCLocalAuthenticationDataSource.kt index dbe898ce98b..27a93024c5e 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/authentication/datasources/implementation/OCLocalAuthenticationDataSource.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/authentication/datasources/implementation/OCLocalAuthenticationDataSource.kt @@ -224,9 +224,8 @@ class OCLocalAuthenticationDataSource( return null } - private fun getAccounts(): Array { - return accountManager.getAccountsByType(accountType) - } + private fun getAccounts(): Array = + accountManager.getAccountsByType(accountType) private fun getCurrentAccount(): Account? { val ocAccounts = getAccounts() diff --git a/owncloudData/src/main/java/com/owncloud/android/data/capabilities/repository/OCCapabilityRepository.kt b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/repository/OCCapabilityRepository.kt index 96f5d63d5cf..6b52b5c6865 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/capabilities/repository/OCCapabilityRepository.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/repository/OCCapabilityRepository.kt @@ -35,9 +35,8 @@ class OCCapabilityRepository( private val appRegistryRepository: AppRegistryRepository, ) : CapabilityRepository { - override fun getCapabilitiesAsLiveData(accountName: String): LiveData { - return localCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(accountName) - } + override fun getCapabilitiesAsLiveData(accountName: String): LiveData = + localCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(accountName) override fun getStoredCapabilities( accountName: String diff --git a/owncloudData/src/main/java/com/owncloud/android/data/files/db/FileDao.kt b/owncloudData/src/main/java/com/owncloud/android/data/files/db/FileDao.kt index 3bed19eb04f..a3d6ab3ee9b 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/files/db/FileDao.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/files/db/FileDao.kt @@ -478,15 +478,14 @@ interface FileDao { private fun getNewAvailableOfflineStatus( parentFolderAvailableOfflineStatus: Int?, currentFileAvailableOfflineStatus: Int?, - ): Int { - return if ((parentFolderAvailableOfflineStatus != null) && + ): Int = + if ((parentFolderAvailableOfflineStatus != null) && parentFolderAvailableOfflineStatus.isOneOf(AVAILABLE_OFFLINE.ordinal, AVAILABLE_OFFLINE_PARENT.ordinal) ) { AVAILABLE_OFFLINE_PARENT.ordinal } else if (currentFileAvailableOfflineStatus == AVAILABLE_OFFLINE.ordinal) { AVAILABLE_OFFLINE.ordinal } else NOT_AVAILABLE_OFFLINE.ordinal - } companion object { diff --git a/owncloudData/src/main/java/com/owncloud/android/data/files/db/OCFileEntity.kt b/owncloudData/src/main/java/com/owncloud/android/data/files/db/OCFileEntity.kt index ebb922c5d8b..e41eb62b7ae 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/files/db/OCFileEntity.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/files/db/OCFileEntity.kt @@ -105,8 +105,8 @@ data class OCFileEntity( get() = mimeType.isOneOf(MIME_DIR, MIME_DIR_UNIX) companion object { - fun fromCursor(cursor: Cursor): OCFileEntity { - return OCFileEntity( + fun fromCursor(cursor: Cursor): OCFileEntity = + OCFileEntity( parentId = cursor.getLong(cursor.getColumnIndexOrThrow(FILE_PARENT)), remotePath = cursor.getString(cursor.getColumnIndexOrThrow(FILE_PATH)), owner = cursor.getString(cursor.getColumnIndexOrThrow(FILE_ACCOUNT_OWNER)), @@ -132,7 +132,6 @@ data class OCFileEntity( ).apply { id = cursor.getLong(cursor.getColumnIndexOrThrow(_ID)) } - } private fun Cursor.getStringFromColumnOrEmpty( columnName: String diff --git a/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_34.kt b/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_34.kt index 1c3500eceea..bc31fda7477 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_34.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_34.kt @@ -81,9 +81,8 @@ class CameraUploadsMigrationToRoom(val sharedPreferencesProvider: SharedPreferen return if (uploadPath!!.endsWith(File.separator)) uploadPath else uploadPath + File.separator } - private fun getSourcePathForPreference(keyPreference: String): String { - return sharedPreferencesProvider.getString(keyPreference, null) ?: "" - } + private fun getSourcePathForPreference(keyPreference: String): String = + sharedPreferencesProvider.getString(keyPreference, null) ?: "" private fun getBehaviorForPreference(keyPreference: String): UploadBehavior { val storedBehaviour = sharedPreferencesProvider.getString(keyPreference, null) ?: return UploadBehavior.COPY diff --git a/owncloudData/src/main/java/com/owncloud/android/data/oauth/repository/OCOAuthRepository.kt b/owncloudData/src/main/java/com/owncloud/android/data/oauth/repository/OCOAuthRepository.kt index c29e6dc5621..42527cf5e93 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/oauth/repository/OCOAuthRepository.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/oauth/repository/OCOAuthRepository.kt @@ -30,9 +30,8 @@ class OCOAuthRepository( private val oidcRemoteOAuthDataSource: RemoteOAuthDataSource, ) : OAuthRepository { - override fun performOIDCDiscovery(baseUrl: String): OIDCServerConfiguration { - return oidcRemoteOAuthDataSource.performOIDCDiscovery(baseUrl) - } + override fun performOIDCDiscovery(baseUrl: String): OIDCServerConfiguration = + oidcRemoteOAuthDataSource.performOIDCDiscovery(baseUrl) override fun performTokenRequest(tokenRequest: TokenRequest): TokenResponse = oidcRemoteOAuthDataSource.performTokenRequest(tokenRequest) diff --git a/owncloudData/src/main/java/com/owncloud/android/data/providers/LocalStorageProvider.kt b/owncloudData/src/main/java/com/owncloud/android/data/providers/LocalStorageProvider.kt index be24b33fdf0..a345eebc698 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/providers/LocalStorageProvider.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/providers/LocalStorageProvider.kt @@ -62,13 +62,12 @@ sealed class LocalStorageProvider(private val rootFolderName: String) { accountName: String, remotePath: String, spaceId: String?, - ): String { - return if (spaceId != null) { + ): String = + if (spaceId != null) { getAccountDirectoryPath(accountName) + File.separator + spaceId + File.separator + remotePath } else { getAccountDirectoryPath(accountName) + remotePath } - } /** * Get expected remote path for a file creation, rename, move etc diff --git a/owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/db/OCShareEntity.kt b/owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/db/OCShareEntity.kt index 73538d73007..971fcba4240 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/db/OCShareEntity.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/db/OCShareEntity.kt @@ -62,8 +62,8 @@ data class OCShareEntity( @PrimaryKey(autoGenerate = true) var id: Int = 0 companion object { - fun fromContentValues(values: ContentValues): OCShareEntity { - return OCShareEntity( + fun fromContentValues(values: ContentValues): OCShareEntity = + OCShareEntity( values.getAsInteger(ProviderTableMeta.OCSHARES_SHARE_TYPE), values.getAsString(ProviderTableMeta.OCSHARES_SHARE_WITH), values.getAsString(ProviderTableMeta.OCSHARES_PATH), @@ -79,6 +79,5 @@ data class OCShareEntity( values.getAsString(ProviderTableMeta.OCSHARES_NAME), values.getAsString(ProviderTableMeta.OCSHARES_URL) ) - } } } diff --git a/owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/repository/OCShareRepository.kt b/owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/repository/OCShareRepository.kt index 3b0dbe6526e..1bcf69c74f6 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/repository/OCShareRepository.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/repository/OCShareRepository.kt @@ -54,13 +54,12 @@ class OCShareRepository( ) } - override fun updatePrivateShare(remoteId: String, permissions: Int, accountName: String) { - return updateShare( + override fun updatePrivateShare(remoteId: String, permissions: Int, accountName: String) = + updateShare( remoteId = remoteId, permissions = permissions, accountName = accountName ) - } /****************************************************************************************************** ******************************************* PUBLIC SHARES ******************************************** @@ -92,8 +91,8 @@ class OCShareRepository( expirationDateInMillis: Long, permissions: Int, accountName: String - ) { - return updateShare( + ) = + updateShare( remoteId, permissions, name, @@ -101,14 +100,13 @@ class OCShareRepository( expirationDateInMillis, accountName ) - } /****************************************************************************************************** *********************************************** COMMON *********************************************** ******************************************************************************************************/ - override fun getSharesAsLiveData(filePath: String, accountName: String): LiveData> { - return localShareDataSource.getSharesAsLiveData( + override fun getSharesAsLiveData(filePath: String, accountName: String): LiveData> = + localShareDataSource.getSharesAsLiveData( filePath, accountName, listOf( ShareType.PUBLIC_LINK, ShareType.USER, @@ -116,7 +114,6 @@ class OCShareRepository( ShareType.FEDERATED ) ) - } override fun getShareAsLiveData(remoteId: String): LiveData = localShareDataSource.getShareAsLiveData(remoteId) diff --git a/owncloudData/src/main/java/com/owncloud/android/data/spaces/datasources/implementation/OCLocalSpacesDataSource.kt b/owncloudData/src/main/java/com/owncloud/android/data/spaces/datasources/implementation/OCLocalSpacesDataSource.kt index eaacf966810..53d61b636eb 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/spaces/datasources/implementation/OCLocalSpacesDataSource.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/spaces/datasources/implementation/OCLocalSpacesDataSource.kt @@ -62,30 +62,27 @@ class OCLocalSpacesDataSource( spacesDao.insertOrDeleteSpaces(spaceEntities, spaceSpecialEntities) } - override fun getPersonalSpaceForAccount(accountName: String): OCSpace? { - return spacesDao.getSpacesByDriveTypeForAccount( + override fun getPersonalSpaceForAccount(accountName: String): OCSpace? = + spacesDao.getSpacesByDriveTypeForAccount( accountName = accountName, filterDriveTypes = setOf(DRIVE_TYPE_PERSONAL) ).map { it.toModel() }.firstOrNull() - } - override fun getSharesSpaceForAccount(accountName: String): OCSpace? { - return spacesDao.getSpaceByIdForAccount(spaceId = SPACE_ID_SHARES, accountName = accountName)?.toModel() - } + override fun getSharesSpaceForAccount(accountName: String): OCSpace? = + spacesDao.getSpaceByIdForAccount(spaceId = SPACE_ID_SHARES, accountName = accountName)?.toModel() - override fun getSpacesFromEveryAccountAsStream(): Flow> { - return spacesDao.getSpacesByDriveTypeFromEveryAccountAsStream( + override fun getSpacesFromEveryAccountAsStream(): Flow> = + spacesDao.getSpacesByDriveTypeFromEveryAccountAsStream( filterDriveTypes = setOf(DRIVE_TYPE_PERSONAL, DRIVE_TYPE_PROJECT) ).map { spaceEntities -> spaceEntities.map { spaceEntity -> spaceEntity.toModel() } } - } override fun getSpacesByDriveTypeWithSpecialsForAccountAsFlow( accountName: String, filterDriveTypes: Set, - ): Flow> { - return spacesDao.getSpacesByDriveTypeWithSpecialsForAccountAsFlow( + ): Flow> = + spacesDao.getSpacesByDriveTypeWithSpecialsForAccountAsFlow( accountName = accountName, filterDriveTypes = filterDriveTypes, ).map { spacesWithSpecialsEntitiesList -> @@ -93,26 +90,21 @@ class OCLocalSpacesDataSource( spacesWithSpecialsEntity.toModel() } } - } - override fun getPersonalAndProjectSpacesForAccount(accountName: String): List { - return spacesDao.getSpacesByDriveTypeForAccount( + override fun getPersonalAndProjectSpacesForAccount(accountName: String): List = + spacesDao.getSpacesByDriveTypeForAccount( accountName = accountName, filterDriveTypes = setOf(DRIVE_TYPE_PERSONAL, DRIVE_TYPE_PROJECT), ).map { it.toModel() } - } - override fun getSpaceWithSpecialsByIdForAccount(spaceId: String?, accountName: String): OCSpace { - return spacesDao.getSpaceWithSpecialsByIdForAccount(spaceId, accountName).toModel() - } + override fun getSpaceWithSpecialsByIdForAccount(spaceId: String?, accountName: String): OCSpace = + spacesDao.getSpaceWithSpecialsByIdForAccount(spaceId, accountName).toModel() - override fun getSpaceByIdForAccount(spaceId: String?, accountName: String): OCSpace? { - return spacesDao.getSpaceByIdForAccount(spaceId = spaceId, accountName = accountName)?.toModel() - } + override fun getSpaceByIdForAccount(spaceId: String?, accountName: String): OCSpace? = + spacesDao.getSpaceByIdForAccount(spaceId = spaceId, accountName = accountName)?.toModel() - override fun getWebDavUrlForSpace(spaceId: String?, accountName: String): String? { - return spacesDao.getWebDavUrlForSpace(spaceId, accountName) - } + override fun getWebDavUrlForSpace(spaceId: String?, accountName: String): String? = + spacesDao.getWebDavUrlForSpace(spaceId, accountName) override fun deleteSpacesForAccount(accountName: String) { spacesDao.deleteSpacesForAccount(accountName) diff --git a/owncloudData/src/main/java/com/owncloud/android/data/transfers/datasources/implementation/OCLocalTransferDataSource.kt b/owncloudData/src/main/java/com/owncloud/android/data/transfers/datasources/implementation/OCLocalTransferDataSource.kt index df80edfc2da..a17293528a5 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/transfers/datasources/implementation/OCLocalTransferDataSource.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/transfers/datasources/implementation/OCLocalTransferDataSource.kt @@ -36,9 +36,8 @@ import kotlinx.coroutines.flow.map class OCLocalTransferDataSource( private val transferDao: TransferDao ) : LocalTransferDataSource { - override fun saveTransfer(transfer: OCTransfer): Long { - return transferDao.insertOrReplace(transfer.toEntity()) - } + override fun saveTransfer(transfer: OCTransfer): Long = + transferDao.insertOrReplace(transfer.toEntity()) override fun updateTransfer(transfer: OCTransfer) { transferDao.insertOrReplace(transfer.toEntity()) @@ -85,18 +84,16 @@ class OCLocalTransferDataSource( transferDao.deleteTransfersWithAccountName(accountName) } - override fun getTransferById(id: Long): OCTransfer? { - return transferDao.getTransferWithId(id)?.toModel() - } + override fun getTransferById(id: Long): OCTransfer? = + transferDao.getTransferWithId(id)?.toModel() - override fun getAllTransfers(): List { - return transferDao.getAllTransfers().map { transferEntity -> + override fun getAllTransfers(): List = + transferDao.getAllTransfers().map { transferEntity -> transferEntity.toModel() } - } - override fun getAllTransfersAsStream(): Flow> { - return transferDao.getAllTransfersAsStream().map { transferEntitiesList -> + override fun getAllTransfersAsStream(): Flow> = + transferDao.getAllTransfersAsStream().map { transferEntitiesList -> val transfers = transferEntitiesList.map { transferEntity -> transferEntity.toModel() } @@ -117,29 +114,24 @@ class OCLocalTransferDataSource( } newTransfersList } - } - override fun getLastTransferFor(remotePath: String, accountName: String): OCTransfer? { - return transferDao.getLastTransferWithRemotePathAndAccountName(remotePath, accountName)?.toModel() - } + override fun getLastTransferFor(remotePath: String, accountName: String): OCTransfer? = + transferDao.getLastTransferWithRemotePathAndAccountName(remotePath, accountName)?.toModel() - override fun getCurrentAndPendingTransfers(): List { - return transferDao.getTransfersWithStatus( + override fun getCurrentAndPendingTransfers(): List = + transferDao.getTransfersWithStatus( listOf(TransferStatus.TRANSFER_IN_PROGRESS.value, TransferStatus.TRANSFER_QUEUED.value) ).map { it.toModel() } - } - override fun getFailedTransfers(): List { - return transferDao.getTransfersWithStatus( + override fun getFailedTransfers(): List = + transferDao.getTransfersWithStatus( listOf(TransferStatus.TRANSFER_FAILED.value) ).map { it.toModel() } - } - override fun getFinishedTransfers(): List { - return transferDao.getTransfersWithStatus( + override fun getFinishedTransfers(): List = + transferDao.getTransfersWithStatus( listOf(TransferStatus.TRANSFER_SUCCEEDED.value) ).map { it.toModel() } - } override fun clearFailedTransfers() { transferDao.deleteTransfersWithStatus(TransferStatus.TRANSFER_FAILED.value) diff --git a/owncloudData/src/main/java/com/owncloud/android/data/user/datasources/implementation/OCLocalUserDataSource.kt b/owncloudData/src/main/java/com/owncloud/android/data/user/datasources/implementation/OCLocalUserDataSource.kt index 098e0e9883b..680d41e0533 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/user/datasources/implementation/OCLocalUserDataSource.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/user/datasources/implementation/OCLocalUserDataSource.kt @@ -44,17 +44,15 @@ class OCLocalUserDataSource( override fun getQuotaForAccountAsFlow(accountName: String): Flow = userDao.getQuotaForAccountAsFlow(accountName = accountName).map { it?.toModel() } - override fun getAllUserQuotas(): List { - return userDao.getAllUserQuotas().map { userQuotaEntity -> + override fun getAllUserQuotas(): List = + userDao.getAllUserQuotas().map { userQuotaEntity -> userQuotaEntity.toModel() } - } - override fun getAllUserQuotasAsFlow(): Flow> { - return userDao.getAllUserQuotasAsFlow().map { userQuotasList -> + override fun getAllUserQuotasAsFlow(): Flow> = + userDao.getAllUserQuotasAsFlow().map { userQuotasList -> userQuotasList.map { it.toModel() } } - } override fun deleteQuotaForAccount(accountName: String) { userDao.deleteQuotaForAccount(accountName = accountName) From c0ce8a34005ab0aef9aaf8af31083a40bd3b7cb1 Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Fri, 10 Jan 2025 09:28:52 +0100 Subject: [PATCH 36/74] style: changed functions with just return to expression body in module `owncloudDomain` --- .../oauth/RequestTokenUseCase.kt | 5 ++--- .../model/FolderBackUpConfiguration.kt | 10 ++++------ .../model/AvailableOfflineStatus.kt | 5 ++--- .../domain/capabilities/model/OCCapability.kt | 5 ++--- .../android/domain/extensions/AnyExt.kt | 5 ++--- .../domain/files/usecases/SortFilesUseCase.kt | 20 ++++++++----------- .../usecases/SortFilesWithSyncInfoUseCase.kt | 15 ++++++-------- .../android/domain/server/model/ServerInfo.kt | 10 ++++------ .../usecases/GetServerInfoAsyncUseCase.kt | 7 +++---- .../owncloud/android/domain/utils/Event.kt | 5 ++--- 10 files changed, 35 insertions(+), 52 deletions(-) diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/authentication/oauth/RequestTokenUseCase.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/authentication/oauth/RequestTokenUseCase.kt index 77d46a478eb..1f8379fbc5a 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/authentication/oauth/RequestTokenUseCase.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/authentication/oauth/RequestTokenUseCase.kt @@ -26,9 +26,8 @@ class RequestTokenUseCase( private val oAuthRepository: OAuthRepository ) : BaseUseCaseWithResult() { - override fun run(params: Params): TokenResponse { - return oAuthRepository.performTokenRequest(params.tokenRequest) - } + override fun run(params: Params): TokenResponse = + oAuthRepository.performTokenRequest(params.tokenRequest) data class Params( val tokenRequest: TokenRequest diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/automaticuploads/model/FolderBackUpConfiguration.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/automaticuploads/model/FolderBackUpConfiguration.kt index 6b2821b821a..fd063b69898 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/automaticuploads/model/FolderBackUpConfiguration.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/automaticuploads/model/FolderBackUpConfiguration.kt @@ -50,23 +50,21 @@ enum class UploadBehavior { MOVE, COPY; @Deprecated("Legacy Local Behavior. Remove asap") - fun toLegacyLocalBehavior(): Int { - return when (this) { + fun toLegacyLocalBehavior(): Int = + when (this) { MOVE -> LEGACY_LOCAL_BEHAVIOUR_MOVE COPY -> LEGACY_LOCAL_BEHAVIOUR_COPY } - } companion object { private const val LEGACY_LOCAL_BEHAVIOUR_COPY = 0 private const val LEGACY_LOCAL_BEHAVIOUR_MOVE = 1 - fun fromString(string: String): UploadBehavior { - return if (string.equals("MOVE", ignoreCase = true)) { + fun fromString(string: String): UploadBehavior = + if (string.equals("MOVE", ignoreCase = true)) { MOVE } else { COPY } - } } } diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/availableoffline/model/AvailableOfflineStatus.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/availableoffline/model/AvailableOfflineStatus.kt index 7dd8ae7502a..55f62b4e242 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/availableoffline/model/AvailableOfflineStatus.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/availableoffline/model/AvailableOfflineStatus.kt @@ -36,12 +36,11 @@ enum class AvailableOfflineStatus { AVAILABLE_OFFLINE_PARENT; companion object { - fun fromValue(value: Int?): AvailableOfflineStatus { - return when (value) { + fun fromValue(value: Int?): AvailableOfflineStatus = + when (value) { AVAILABLE_OFFLINE.ordinal -> AVAILABLE_OFFLINE AVAILABLE_OFFLINE_PARENT.ordinal -> AVAILABLE_OFFLINE_PARENT else -> NOT_AVAILABLE_OFFLINE } - } } } diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/capabilities/model/OCCapability.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/capabilities/model/OCCapability.kt index eaaef99e202..cf92de4a637 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/capabilities/model/OCCapability.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/capabilities/model/OCCapability.kt @@ -60,9 +60,8 @@ data class OCCapability( return (filesBigFileChunking.isTrue && doubleChunkingVersion != null && doubleChunkingVersion >= 1.0) } - fun isFetchingAvatarAllowed(): Boolean { - return filesSharingUserProfilePicture.isTrue || filesSharingUserProfilePicture.isUnknown - } + fun isFetchingAvatarAllowed(): Boolean = + filesSharingUserProfilePicture.isTrue || filesSharingUserProfilePicture.isUnknown fun isOpenInWebAllowed(): Boolean = filesAppProviders?.openWebUrl?.isNotBlank() ?: false diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/extensions/AnyExt.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/extensions/AnyExt.kt index 5c64a4ec92a..b08f919bc1f 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/extensions/AnyExt.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/extensions/AnyExt.kt @@ -19,6 +19,5 @@ package com.owncloud.android.domain.extensions -fun Any.isOneOf(vararg values: Any): Boolean { - return this in values -} +fun Any.isOneOf(vararg values: Any): Boolean = + this in values diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/files/usecases/SortFilesUseCase.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/files/usecases/SortFilesUseCase.kt index 71d5b9206f1..d119bff452d 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/files/usecases/SortFilesUseCase.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/files/usecases/SortFilesUseCase.kt @@ -23,13 +23,12 @@ import com.owncloud.android.domain.files.model.OCFile class SortFilesUseCase : BaseUseCase, SortFilesUseCase.Params>() { - override fun run(params: Params): List { - return when (params.sortType) { + override fun run(params: Params): List = + when (params.sortType) { SortType.SORT_BY_NAME -> sortByName(params.listOfFiles, params.ascending) SortType.SORT_BY_SIZE -> sortBySize(params.listOfFiles, params.ascending) SortType.SORT_BY_DATE -> sortByDate(params.listOfFiles, params.ascending) } - } private fun sortByName(listOfFiles: List, ascending: Boolean): List { val newListOfFiles = @@ -40,15 +39,13 @@ class SortFilesUseCase : BaseUseCase, SortFilesUseCase.Params>() { return newListOfFiles.sortedByDescending { it.isFolder } } - private fun sortBySize(listOfFiles: List, ascending: Boolean): List { - return if (ascending) listOfFiles.sortedBy { it.length } + private fun sortBySize(listOfFiles: List, ascending: Boolean): List = + if (ascending) listOfFiles.sortedBy { it.length } else listOfFiles.sortedByDescending { it.length } - } - private fun sortByDate(listOfFiles: List, ascending: Boolean): List { - return if (ascending) listOfFiles.sortedBy { it.modificationTimestamp } + private fun sortByDate(listOfFiles: List, ascending: Boolean): List = + if (ascending) listOfFiles.sortedBy { it.modificationTimestamp } else listOfFiles.sortedByDescending { it.modificationTimestamp } - } data class Params( val listOfFiles: List, @@ -61,13 +58,12 @@ enum class SortType { SORT_BY_NAME, SORT_BY_SIZE, SORT_BY_DATE; companion object { - fun fromPreferences(preferenceValue: Int): SortType { - return when (preferenceValue) { + fun fromPreferences(preferenceValue: Int): SortType = + when (preferenceValue) { 0 -> SORT_BY_NAME 1 -> SORT_BY_DATE 2 -> SORT_BY_SIZE else -> throw IllegalStateException("Sort type not expected") } - } } } diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/files/usecases/SortFilesWithSyncInfoUseCase.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/files/usecases/SortFilesWithSyncInfoUseCase.kt index 3fc8fceff0d..0a5f9080b87 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/files/usecases/SortFilesWithSyncInfoUseCase.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/files/usecases/SortFilesWithSyncInfoUseCase.kt @@ -25,13 +25,12 @@ import com.owncloud.android.domain.files.model.OCFileWithSyncInfo class SortFilesWithSyncInfoUseCase : BaseUseCase, SortFilesWithSyncInfoUseCase.Params>() { - override fun run(params: Params): List { - return when (params.sortType) { + override fun run(params: Params): List = + when (params.sortType) { SortType.SORT_BY_NAME -> sortByName(params.listOfFiles, params.ascending) SortType.SORT_BY_SIZE -> sortBySize(params.listOfFiles, params.ascending) SortType.SORT_BY_DATE -> sortByDate(params.listOfFiles, params.ascending) } - } private fun sortByName(listOfFiles: List, ascending: Boolean): List { val newListOfFiles = @@ -42,15 +41,13 @@ class SortFilesWithSyncInfoUseCase : BaseUseCase, SortF return newListOfFiles.sortedByDescending { it.file.isFolder } } - private fun sortBySize(listOfFiles: List, ascending: Boolean): List { - return if (ascending) listOfFiles.sortedBy { it.file.length } + private fun sortBySize(listOfFiles: List, ascending: Boolean): List = + if (ascending) listOfFiles.sortedBy { it.file.length } else listOfFiles.sortedByDescending { it.file.length } - } - private fun sortByDate(listOfFiles: List, ascending: Boolean): List { - return if (ascending) listOfFiles.sortedBy { it.file.modificationTimestamp } + private fun sortByDate(listOfFiles: List, ascending: Boolean): List = + if (ascending) listOfFiles.sortedBy { it.file.modificationTimestamp } else listOfFiles.sortedByDescending { it.file.modificationTimestamp } - } data class Params( val listOfFiles: List, diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/server/model/ServerInfo.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/server/model/ServerInfo.kt index 5524485cb98..e983a696dff 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/server/model/ServerInfo.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/server/model/ServerInfo.kt @@ -36,9 +36,8 @@ sealed class ServerInfo( return true } - override fun hashCode(): Int { - return javaClass.hashCode() - } + override fun hashCode(): Int = + javaClass.hashCode() class OIDCServer( ownCloudVersion: String, @@ -51,9 +50,8 @@ sealed class ServerInfo( return super.equals(other) } - override fun hashCode(): Int { - return javaClass.hashCode() - } + override fun hashCode(): Int = + javaClass.hashCode() } class OAuth2Server( diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/server/usecases/GetServerInfoAsyncUseCase.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/server/usecases/GetServerInfoAsyncUseCase.kt index 873cd8917c7..58f784175c5 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/server/usecases/GetServerInfoAsyncUseCase.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/server/usecases/GetServerInfoAsyncUseCase.kt @@ -53,13 +53,12 @@ class GetServerInfoAsyncUseCase( /** * In case the user introduces a server url without prefix, we will try to connect to https */ - private fun normalizeProtocolPrefix(url: String): String { - return if (!url.lowercase(Locale.getDefault()).startsWith(HTTP_PREFIX) && + private fun normalizeProtocolPrefix(url: String): String = + if (!url.lowercase(Locale.getDefault()).startsWith(HTTP_PREFIX) && !url.lowercase(Locale.getDefault()).startsWith(HTTPS_PREFIX) ) { - return "$HTTPS_PREFIX$url" + "$HTTPS_PREFIX$url" } else url - } companion object { const val TRAILING_SLASH = '/' diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/utils/Event.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/utils/Event.kt index 5fff9fb3382..cc31adec0f3 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/utils/Event.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/utils/Event.kt @@ -28,14 +28,13 @@ data class Event(private val content: T) { /** * Returns the content and prevents its use again. */ - fun getContentIfNotHandled(): T? { - return if (hasBeenHandled) { + fun getContentIfNotHandled(): T? = + if (hasBeenHandled) { null } else { hasBeenHandled = true content } - } /** * Returns the content, even if it's already been handled. From dbe980c3c78bbf51e0a03702e491abd6840c88db Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Fri, 10 Jan 2025 09:39:31 +0100 Subject: [PATCH 37/74] style: added new line at the end of the file --- .../src/main/java/com/owncloud/android/extensions/DialogExt.kt | 2 +- .../com/owncloud/android/ui/dialog/FileAlreadyExistsDialog.kt | 2 +- .../java/com/owncloud/android/lib/common/http/CookieJarImpl.kt | 2 +- .../com/owncloud/android/lib/common/http/DummyInterceptor.kt | 2 +- .../sharing/sharees/datasources/mapper/RemoteShareeMapper.kt | 2 +- .../com/owncloud/android/domain/exceptions/SSLErrorException.kt | 2 +- .../domain/authentication/oauth/RegisterClientUseCaseTest.kt | 2 +- .../domain/authentication/oauth/RequestTokenUseCaseTest.kt | 2 +- .../java/com/owncloud/android/testutil/security/PatternUtils.kt | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/extensions/DialogExt.kt b/owncloudApp/src/main/java/com/owncloud/android/extensions/DialogExt.kt index feca9059924..da5665ae3c8 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/extensions/DialogExt.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/extensions/DialogExt.kt @@ -28,4 +28,4 @@ fun Dialog.avoidScreenshotsIfNeeded() { if (!BuildConfig.DEBUG && context.resources?.getBoolean(R.bool.allow_screenshots) == false) { window?.addFlags(WindowManager.LayoutParams.FLAG_SECURE) } -} \ No newline at end of file +} diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/dialog/FileAlreadyExistsDialog.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/dialog/FileAlreadyExistsDialog.kt index 123f74876bf..56820ea0bb3 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/dialog/FileAlreadyExistsDialog.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/dialog/FileAlreadyExistsDialog.kt @@ -79,4 +79,4 @@ class FileAlreadyExistsDialog : DialogFragment() { binding.dialogFileAlreadyExistsCheckbox.visibility = if (checkboxVisible == true) { View.VISIBLE } else { View.GONE } } -} \ No newline at end of file +} diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/CookieJarImpl.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/CookieJarImpl.kt index ec355cd7971..737399d81d6 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/CookieJarImpl.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/CookieJarImpl.kt @@ -59,4 +59,4 @@ class CookieJarImpl( override fun loadForRequest(url: HttpUrl) = cookieStore[url.host] ?: ArrayList() -} \ No newline at end of file +} diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/DummyInterceptor.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/DummyInterceptor.kt index 8a81b460fba..d8ad5c11978 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/DummyInterceptor.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/DummyInterceptor.kt @@ -28,4 +28,4 @@ import okhttp3.Interceptor class DummyInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain) = chain.proceed(chain.request()) -} \ No newline at end of file +} diff --git a/owncloudData/src/main/java/com/owncloud/android/data/sharing/sharees/datasources/mapper/RemoteShareeMapper.kt b/owncloudData/src/main/java/com/owncloud/android/data/sharing/sharees/datasources/mapper/RemoteShareeMapper.kt index 28282e37d1f..66f7206b30f 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/sharing/sharees/datasources/mapper/RemoteShareeMapper.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/sharing/sharees/datasources/mapper/RemoteShareeMapper.kt @@ -54,4 +54,4 @@ class RemoteShareeMapper : RemoteMapper, ShareeOcsResponse> { // not needed override fun toRemote(model: List?): ShareeOcsResponse? = null -} \ No newline at end of file +} diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/exceptions/SSLErrorException.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/exceptions/SSLErrorException.kt index 9b9e04229d4..df58151e9f5 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/exceptions/SSLErrorException.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/exceptions/SSLErrorException.kt @@ -25,4 +25,4 @@ class SSLErrorException(override val message: String? = null, val code: SSLError enum class SSLErrorCode { GENERIC, NOT_HTTP_ALLOWED } -const val NOT_HTTP_ALLOWED_MESSAGE = "Connection is not secure, http traffic is not allowed." \ No newline at end of file +const val NOT_HTTP_ALLOWED_MESSAGE = "Connection is not secure, http traffic is not allowed." diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/authentication/oauth/RegisterClientUseCaseTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/authentication/oauth/RegisterClientUseCaseTest.kt index da5949446b8..5223218578e 100644 --- a/owncloudDomain/src/test/java/com/owncloud/android/domain/authentication/oauth/RegisterClientUseCaseTest.kt +++ b/owncloudDomain/src/test/java/com/owncloud/android/domain/authentication/oauth/RegisterClientUseCaseTest.kt @@ -56,4 +56,4 @@ class RegisterClientUseCaseTest { verify(exactly = 1) { repository.registerClient(useCaseParams.clientRegistrationRequest) } } -} \ No newline at end of file +} diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/authentication/oauth/RequestTokenUseCaseTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/authentication/oauth/RequestTokenUseCaseTest.kt index 46bf1d10b0d..0018192932a 100644 --- a/owncloudDomain/src/test/java/com/owncloud/android/domain/authentication/oauth/RequestTokenUseCaseTest.kt +++ b/owncloudDomain/src/test/java/com/owncloud/android/domain/authentication/oauth/RequestTokenUseCaseTest.kt @@ -56,4 +56,4 @@ class RequestTokenUseCaseTest { verify(exactly = 1) { repository.performTokenRequest(useCaseParams.tokenRequest) } } -} \ No newline at end of file +} diff --git a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/security/PatternUtils.kt b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/security/PatternUtils.kt index b0b50de6894..d84b7539ace 100644 --- a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/security/PatternUtils.kt +++ b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/security/PatternUtils.kt @@ -20,4 +20,4 @@ package com.owncloud.android.testutil.security -const val OC_PATTERN = "1234" \ No newline at end of file +const val OC_PATTERN = "1234" From f29cd01be9683ec4e877c18b05c85c770ed9071c Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Fri, 10 Jan 2025 20:50:09 +0100 Subject: [PATCH 38/74] refactor: renamed member so that it doesn't have the name of its class --- .../presentation/security/biometric/BiometricManager.kt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/biometric/BiometricManager.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/biometric/BiometricManager.kt index 35f4c8da842..8fbf40c1d59 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/biometric/BiometricManager.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/biometric/BiometricManager.kt @@ -47,7 +47,7 @@ object BiometricManager { mutableSetOf(BiometricActivity::class.java, PassCodeActivity::class.java, PatternActivity::class.java) private val visibleActivities: MutableSet> = mutableSetOf() private val preferencesProvider = OCSharedPreferencesProvider(appContext) - private val biometricManager: BiometricManager = BiometricManager.from(appContext) + private val androidBiometricManager: BiometricManager = BiometricManager.from(appContext) fun onActivityStarted(activity: Activity) { if (!exemptOfBiometricActivities.contains(activity.javaClass) && biometricShouldBeRequested()) { @@ -96,9 +96,9 @@ object BiometricManager { preferencesProvider.getBoolean(BiometricActivity.PREFERENCE_SET_BIOMETRIC, false) fun isHardwareDetected(): Boolean = - biometricManager.canAuthenticate(BIOMETRIC_WEAK) != BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE && - biometricManager.canAuthenticate(BIOMETRIC_WEAK) != BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE + androidBiometricManager.canAuthenticate(BIOMETRIC_WEAK) != BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE && + androidBiometricManager.canAuthenticate(BIOMETRIC_WEAK) != BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE fun hasEnrolledBiometric(): Boolean = - biometricManager.canAuthenticate(BIOMETRIC_WEAK) != BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED + androidBiometricManager.canAuthenticate(BIOMETRIC_WEAK) != BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED } From 66e5d8e723c24fdb03be36381c59f9c476253866 Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Fri, 10 Jan 2025 21:19:51 +0100 Subject: [PATCH 39/74] refactor: removed unused property --- .../android/presentation/viewmodels/DrawerViewModelTest.kt | 2 -- 1 file changed, 2 deletions(-) diff --git a/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/DrawerViewModelTest.kt b/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/DrawerViewModelTest.kt index a0e8acf2b00..52b5c62eef1 100644 --- a/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/DrawerViewModelTest.kt +++ b/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/DrawerViewModelTest.kt @@ -47,8 +47,6 @@ class DrawerViewModelTest : ViewModelTest() { private lateinit var contextProvider: ContextProvider - private val commonException = Exception() - @Before fun setUp() { contextProvider = mockk() From 34a2770dfac8ed3a7df17d2603d44acf5e788590 Mon Sep 17 00:00:00 2001 From: joragua Date: Mon, 20 Jan 2025 13:39:59 +0100 Subject: [PATCH 40/74] refactor: replaced forbidden comments by normal comments --- .../android/datamodel/FileDataStorageManager.kt | 10 +++++----- .../android/presentation/avatar/AvatarUtils.kt | 2 +- .../documentsprovider/DocumentsStorageProvider.kt | 2 +- .../android/presentation/files/SortOptionsView.kt | 2 +- .../presentation/files/details/FileDetailsFragment.kt | 2 +- .../transfers/uploads/CancelUploadForFileUseCase.kt | 2 +- .../viewmodels/capabilities/CapabilityViewModelTest.kt | 2 +- .../viewmodels/sharing/ShareViewModelTest.kt | 2 +- .../owncloud/android/lib/common/ConnectionValidator.kt | 2 +- .../owncloud/android/lib/resources/files/RemoteFile.kt | 2 +- .../resources/oauth/responses/OIDCDiscoveryResponse.kt | 2 +- .../implementation/OCLocalFileDataSource.kt | 2 +- .../android/data/files/repository/OCFileRepository.kt | 4 ++-- .../implementation/OCSharedPreferencesProvider.kt | 2 +- .../oauth/model/OIDCServerConfiguration.kt | 2 +- 15 files changed, 20 insertions(+), 20 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt b/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt index 29a7c0cd960..673dd687bfa 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt @@ -80,7 +80,7 @@ class FileDataStorageManager( result } - // TODO: New_arch: Remove this and call usecase inside FilesViewModel + // To do: New_arch: Remove this and call usecase inside FilesViewModel fun getFileById(id: Long): OCFile? = runBlocking(CoroutinesDispatcherProvider().io) { val getFileByIdUseCase: GetFileByIdUseCase by inject() @@ -94,24 +94,24 @@ class FileDataStorageManager( fun getFolderContent(f: OCFile?): List = if (f != null && f.isFolder && f.id != -1L) { - // TODO: Remove !! + // To do: Remove !! getFolderContent(f.id!!) } else { listOf() } - // TODO: New_arch: Remove this and call usecase inside FilesViewModel + // New_arch: Remove this and call usecase inside FilesViewModel fun getFolderImages(folder: OCFile?): List = runBlocking(CoroutinesDispatcherProvider().io) { val getFolderImagesUseCase: GetFolderImagesUseCase by inject() val result = withContext(CoroutineScope(CoroutinesDispatcherProvider().io).coroutineContext) { - // TODO: Remove !! + // To do: Remove !! getFolderImagesUseCase(GetFolderImagesUseCase.Params(folderId = folder!!.id!!)) }.getDataOrNull() result ?: listOf() } - // TODO: New_arch: Remove this and call usecase inside FilesViewModel + // New_arch: Remove this and call usecase inside FilesViewModel private fun getFolderContent(parentId: Long): List = runBlocking(CoroutinesDispatcherProvider().io) { val getFolderContentUseCase: GetFolderContentUseCase by inject() diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/avatar/AvatarUtils.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/avatar/AvatarUtils.kt index 97599741c83..9c1653f6290 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/avatar/AvatarUtils.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/avatar/AvatarUtils.kt @@ -56,7 +56,7 @@ class AvatarUtils : KoinComponent { fetchIfNotCached: Boolean = false, displayRadius: Float ) { - //TODO: Tech debt: Move this to a viewModel and use its viewModelScope instead + // Tech debt: Move this to a viewModel and use its viewModelScope instead CoroutineScope(Dispatchers.IO).launch { val drawable = avatarManager.getAvatarForAccount( account = account, diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/documentsprovider/DocumentsStorageProvider.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/documentsprovider/DocumentsStorageProvider.kt index 9c46544f655..6188b120430 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/documentsprovider/DocumentsStorageProvider.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/documentsprovider/DocumentsStorageProvider.kt @@ -310,7 +310,7 @@ class DocumentsStorageProvider : DocumentsProvider() { sizeHint: Point?, signal: CancellationSignal? ): AssetFileDescriptor { - // TODO: Show thumbnail for spaces + // To do: Show thumbnail for spaces val file = getFileByIdOrException(documentId.toInt()) val realFile = File(file.storagePath) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/SortOptionsView.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/SortOptionsView.kt index 0dd35772caf..00f3bd9d8af 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/SortOptionsView.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/SortOptionsView.kt @@ -62,7 +62,7 @@ class SortOptionsView @JvmOverloads constructor( var sortTypeSelected: SortType = SortType.SORT_TYPE_BY_NAME set(sortType) { if (field == sortType) { - // TODO: Should be changed directly, not here. + // To do: Should be changed directly, not here. sortOrderSelected = sortOrderSelected.getOppositeSortOrder() } binding.sortTypeTitle.text = context.getText(sortType.toStringRes()) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/details/FileDetailsFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/details/FileDetailsFragment.kt index 3af7d5892c2..b5ca2e500b5 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/details/FileDetailsFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/details/FileDetailsFragment.kt @@ -559,7 +559,7 @@ class FileDetailsFragment : FileFragment() { requireActivity().invalidateOptionsMenu() } - // TODO: Move navigation to a common place. + // To do: Move navigation to a common place. private fun navigateToPreviewOrOpenFile(fileWaitingToPreview: OCFile) { val fileDisplayActivity = requireActivity() as FileDisplayActivity when { diff --git a/owncloudApp/src/main/java/com/owncloud/android/usecases/transfers/uploads/CancelUploadForFileUseCase.kt b/owncloudApp/src/main/java/com/owncloud/android/usecases/transfers/uploads/CancelUploadForFileUseCase.kt index 55edb3ec9be..de1b5b8fcd0 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/usecases/transfers/uploads/CancelUploadForFileUseCase.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/usecases/transfers/uploads/CancelUploadForFileUseCase.kt @@ -55,7 +55,7 @@ class CancelUploadForFileUseCase( workManager.getWorkInfoByTags(listOf(uploadForFile.id.toString(), file.owner)) workersToCancel.forEach { - // TODO: We need to check if the work is cancelled before finishing. + // To do: We need to check if the work is cancelled before finishing. // Otherwise, the database would be updated by the worker. // It should be a way to check within the worker that a cancellation has been triggered. // In that case, we would update the database there. diff --git a/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/capabilities/CapabilityViewModelTest.kt b/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/capabilities/CapabilityViewModelTest.kt index c796016f112..b3b23e5efed 100644 --- a/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/capabilities/CapabilityViewModelTest.kt +++ b/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/capabilities/CapabilityViewModelTest.kt @@ -86,7 +86,7 @@ class CapabilityViewModelTest { Dispatchers.setMain(testCoroutineDispatcher) ocContextProvider = mockk(relaxed = true) - //TODO: Add tests when is not connected + // To do: Add tests when is not connected every { ocContextProvider.isConnected() } returns true Dispatchers.setMain(testCoroutineDispatcher) diff --git a/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/sharing/ShareViewModelTest.kt b/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/sharing/ShareViewModelTest.kt index d0b508b98ae..f761e995c57 100644 --- a/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/sharing/ShareViewModelTest.kt +++ b/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/sharing/ShareViewModelTest.kt @@ -99,7 +99,7 @@ class ShareViewModelTest { fun setUp() { ocContextProvider = mockk(relaxed = true) - //TODO: Add tests when is not connected + // To do: Add tests when is not connected every { ocContextProvider.isConnected() } returns true Dispatchers.setMain(testCoroutineDispatcher) diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/ConnectionValidator.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/ConnectionValidator.kt index 258c514ce39..5ffc8e978f9 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/ConnectionValidator.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/ConnectionValidator.kt @@ -105,7 +105,7 @@ class ConnectionValidator( private fun isOwnCloudStatusOk(client: OwnCloudClient): Boolean { val reply = getOwnCloudStatus(client) // dont check status code. It currently relais on the broken redirect code of the owncloud client - // TODO: Use okhttp redirect and add this check again + // To do: Use okhttp redirect and add this check again // return reply.httpCode == HttpConstants.HTTP_OK && return !reply.isException && reply.data != null diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/RemoteFile.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/RemoteFile.kt index 33e99785ae6..c6f047cfb37 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/RemoteFile.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/RemoteFile.kt @@ -76,7 +76,7 @@ data class RemoteFile( var sharedWithSharee: Boolean = false, ) : Parcelable { - // TODO: Quotas not used. Use or remove them. + // To do: Quotas not used. Use or remove them. init { require( !(remotePath.isEmpty() || !remotePath.startsWith(File.separator)) diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/oauth/responses/OIDCDiscoveryResponse.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/oauth/responses/OIDCDiscoveryResponse.kt index eaba7b980d7..52720bdd5e7 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/oauth/responses/OIDCDiscoveryResponse.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/oauth/responses/OIDCDiscoveryResponse.kt @@ -35,7 +35,7 @@ data class OIDCDiscoveryResponse( val end_session_endpoint: String?, val issuer: String, val registration_endpoint: String?, - val response_types_supported: List?, // TODO: provisional, remove nullability ASAP + val response_types_supported: List?, // To do: provisional, remove nullability ASAP val scopes_supported: List?, val token_endpoint: String, val token_endpoint_auth_methods_supported: List?, diff --git a/owncloudData/src/main/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSource.kt b/owncloudData/src/main/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSource.kt index 1ec4bfd2b22..5d16bff6335 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSource.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSource.kt @@ -154,7 +154,7 @@ class OCLocalFileDataSource( } override fun saveFilesInFolderAndReturnTheFilesThatChanged(listOfFiles: List, folder: OCFile): List { - // TODO: If it is root, add 0 as parent Id + // To do: If it is root, add 0 as parent Id val folderContent = fileDao.insertFilesInFolderAndReturnTheFilesThatChanged( folder = folder.toEntity(), folderContent = listOfFiles.map { it.toEntity() } diff --git a/owncloudData/src/main/java/com/owncloud/android/data/files/repository/OCFileRepository.kt b/owncloudData/src/main/java/com/owncloud/android/data/files/repository/OCFileRepository.kt index 29421665a4f..072538e4f5b 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/files/repository/OCFileRepository.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/files/repository/OCFileRepository.kt @@ -203,7 +203,7 @@ class OCFileRepository( Timber.i("There was an error: $e") } } - // TODO: Retrieving the root folders should return a non nullable. If they don't exist yet, they are created and returned. Remove nullability + // To do: Retrieving the root folders should return a non nullable. If they don't exist yet, they are created and returned. Remove nullability val personalRootFolder = localFileDataSource.getFileByRemotePath(remotePath = ROOT_PATH, owner = owner, spaceId = personalSpace?.root?.id) return personalRootFolder!! } @@ -402,7 +402,7 @@ class OCFileRepository( if (remoteFolder.isAvailableOffline) { availableOfflineStatus = AVAILABLE_OFFLINE_PARENT } - // FIXME: What about renames? Need to fix storage path + // Fix: What about renames? Need to fix storage path }) } } diff --git a/owncloudData/src/main/java/com/owncloud/android/data/providers/implementation/OCSharedPreferencesProvider.kt b/owncloudData/src/main/java/com/owncloud/android/data/providers/implementation/OCSharedPreferencesProvider.kt index cf2097133c9..86e7d895fd6 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/providers/implementation/OCSharedPreferencesProvider.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/providers/implementation/OCSharedPreferencesProvider.kt @@ -28,7 +28,7 @@ class OCSharedPreferencesProvider( context: Context ) : SharedPreferencesProvider { - // TODO: Move to Androidx Preferences or DataStore + // To do: Move to Androidx Preferences or DataStore private val sharedPreferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) private val editor = sharedPreferences.edit() diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/authentication/oauth/model/OIDCServerConfiguration.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/authentication/oauth/model/OIDCServerConfiguration.kt index 1c0d22405ff..269b096f520 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/authentication/oauth/model/OIDCServerConfiguration.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/authentication/oauth/model/OIDCServerConfiguration.kt @@ -27,7 +27,7 @@ data class OIDCServerConfiguration( val endSessionEndpoint: String?, val issuer: String, val registrationEndpoint: String?, - val responseTypesSupported: List?, // TODO: provisional, remove nullability ASAP + val responseTypesSupported: List?, // To do: provisional, remove nullability ASAP val scopesSupported: List?, val tokenEndpoint: String, val tokenEndpointAuthMethodsSupported: List?, From 4f5e55868a5098fe670af3adfc55083e14bec6d9 Mon Sep 17 00:00:00 2001 From: joragua Date: Mon, 20 Jan 2025 13:45:19 +0100 Subject: [PATCH 41/74] refactor: removed wildcard imports and added necessary ones --- .../lib/resources/status/responses/CapabilityResponse.kt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/responses/CapabilityResponse.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/responses/CapabilityResponse.kt index 2f3a4ef6cb8..722054839d6 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/responses/CapabilityResponse.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/responses/CapabilityResponse.kt @@ -29,7 +29,10 @@ package com.owncloud.android.lib.resources.status.responses import com.owncloud.android.lib.resources.status.RemoteCapability -import com.owncloud.android.lib.resources.status.RemoteCapability.* +import com.owncloud.android.lib.resources.status.RemoteCapability.CapabilityBooleanType +import com.owncloud.android.lib.resources.status.RemoteCapability.RemoteAppProviders +import com.owncloud.android.lib.resources.status.RemoteCapability.RemotePasswordPolicy +import com.owncloud.android.lib.resources.status.RemoteCapability.RemoteSpaces import com.squareup.moshi.Json import com.squareup.moshi.JsonClass From 7618d49f5a67a0170794000f77299a81c028ba79 Mon Sep 17 00:00:00 2001 From: joragua Date: Mon, 20 Jan 2025 14:09:30 +0100 Subject: [PATCH 42/74] style: renamed some variables that were not following naming convention --- .../files/createfolder/CreateFolderDialogFragment.kt | 6 +++--- .../files/renamefile/RenameFileDialogFragment.kt | 6 +++--- .../presentation/security/passcode/PassCodeActivity.kt | 6 +++--- .../owncloud/android/ui/preview/PreviewTextFragment.kt | 8 ++++---- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/createfolder/CreateFolderDialogFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/createfolder/CreateFolderDialogFragment.kt index 8d840fc671d..34eab6b9a18 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/createfolder/CreateFolderDialogFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/createfolder/CreateFolderDialogFragment.kt @@ -44,7 +44,7 @@ class CreateFolderDialogFragment : DialogFragment() { private lateinit var parentFolder: OCFile private lateinit var createFolderListener: CreateFolderListener private var isButtonEnabled: Boolean = false - private val MAX_FILENAME_LENGTH = 223 + private val maxFilenameLength = 223 override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { @@ -101,10 +101,10 @@ class CreateFolderDialogFragment : DialogFragment() { if (text.isNullOrBlank()) { okButton.isEnabled = false error = getString(R.string.uploader_upload_text_dialog_filename_error_empty) - } else if (text.length > MAX_FILENAME_LENGTH) { + } else if (text.length > maxFilenameLength) { error = String.format( getString(R.string.uploader_upload_text_dialog_filename_error_length_max), - MAX_FILENAME_LENGTH + maxFilenameLength ) } else if (forbiddenChars.any { text.contains(it) }) { error = getString(R.string.filename_forbidden_characters) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/renamefile/RenameFileDialogFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/renamefile/RenameFileDialogFragment.kt index b8ff0d8a7f9..a3c37fb0300 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/renamefile/RenameFileDialogFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/renamefile/RenameFileDialogFragment.kt @@ -50,7 +50,7 @@ class RenameFileDialogFragment : DialogFragment(), DialogInterface.OnClickListen private var targetFile: OCFile? = null private val filesViewModel: FileOperationsViewModel by sharedViewModel() private var isButtonEnabled = true - private val MAX_FILENAME_LENGTH = 223 + private val maxFilenameLength = 223 override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { if (savedInstanceState != null) { isButtonEnabled = savedInstanceState.getBoolean(IS_BUTTON_ENABLED_FLAG_KEY) @@ -105,10 +105,10 @@ class RenameFileDialogFragment : DialogFragment(), DialogInterface.OnClickListen if (text.isNullOrBlank()) { okButton.isEnabled = false error = getString(R.string.uploader_upload_text_dialog_filename_error_empty) - } else if (text.length > MAX_FILENAME_LENGTH) { + } else if (text.length > maxFilenameLength) { error = String.format( getString(R.string.uploader_upload_text_dialog_filename_error_length_max), - MAX_FILENAME_LENGTH + maxFilenameLength ) } else if (forbiddenChars.any { text.contains(it) }) { error = getString(R.string.filename_forbidden_characters) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt index a8dbac100ed..74ea292d9cf 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt @@ -174,11 +174,11 @@ class PassCodeActivity : AppCompatActivity(), NumberKeyboardListener, EnableBiom } private fun inflatePasscodeTxtLine() { - val layout_code = findViewById(R.id.layout_code) + val layoutCode = findViewById(R.id.layout_code) val numberOfPasscodeDigits = (passCodeViewModel.getPassCode()?.length ?: passCodeViewModel.getNumberOfPassCodeDigits()) for (i in 0 until numberOfPasscodeDigits) { - val txt = layoutInflater.inflate(R.layout.passcode_edit_text, layout_code, false) as EditText - layout_code.addView(txt) + val txt = layoutInflater.inflate(R.layout.passcode_edit_text, layoutCode, false) as EditText + layoutCode.addView(txt) passCodeEditTexts[i] = txt } passCodeEditTexts.first()?.requestFocus() diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewTextFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewTextFragment.kt index 48124216a09..697ea3b7c4d 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewTextFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewTextFragment.kt @@ -283,7 +283,7 @@ class PreviewTextFragment : FileFragment() { var viewPager: ViewPager2 ) : AsyncTask() { - private val DIALOG_WAIT_TAG = "DIALOG_WAIT" + private val dialogWaitTag = "DIALOG_WAIT" private lateinit var mimeType: String override fun onPreExecute() { @@ -345,14 +345,14 @@ class PreviewTextFragment : FileFragment() { } fun showLoadingDialog() { - val waitDialogFragment = requireActivity().supportFragmentManager.findFragmentByTag(DIALOG_WAIT_TAG) + val waitDialogFragment = requireActivity().supportFragmentManager.findFragmentByTag(dialogWaitTag) val loading: LoadingDialog if (waitDialogFragment == null) { loading = LoadingDialog.newInstance(R.string.wait_a_moment, false) val fragmentManager = requireActivity().supportFragmentManager val fragmentTransaction = fragmentManager.beginTransaction() - loading.show(fragmentTransaction, DIALOG_WAIT_TAG) + loading.show(fragmentTransaction, dialogWaitTag) } else { loading = waitDialogFragment as LoadingDialog loading.showsDialog = true @@ -360,7 +360,7 @@ class PreviewTextFragment : FileFragment() { } fun dismissLoadingDialog() { - val waitDialogFragment = requireActivity().supportFragmentManager.findFragmentByTag(DIALOG_WAIT_TAG) + val waitDialogFragment = requireActivity().supportFragmentManager.findFragmentByTag(dialogWaitTag) waitDialogFragment?.let { val loading = waitDialogFragment as LoadingDialog loading.dismiss() From 9ea9fe2bd27bbe3633e81d4877c8beda93d66c82 Mon Sep 17 00:00:00 2001 From: joragua Date: Tue, 21 Jan 2025 08:41:53 +0100 Subject: [PATCH 43/74] refactor: removed empty secondary constructors --- .../java/com/owncloud/android/ui/preview/ViewPagerWorkAround.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/ViewPagerWorkAround.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/ViewPagerWorkAround.kt index ee99952de7f..c91c545807f 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/ViewPagerWorkAround.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/ViewPagerWorkAround.kt @@ -31,7 +31,7 @@ import timber.log.Timber */ class ViewPagerWorkAround : ViewPager { constructor(context: Context) : super(context) - constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {} + constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(ev: MotionEvent?): Boolean { From a73d06bec6a52439edbc3cc949de380b0f57fe3a Mon Sep 17 00:00:00 2001 From: joragua Date: Wed, 22 Jan 2025 17:19:03 +0100 Subject: [PATCH 44/74] refactor: modified some methods with more than 2 `return` --- .../DocumentsStorageProvider.kt | 104 +++++++++--------- .../files/filelist/FileListAdapter.kt | 8 +- .../files/filelist/FileListDiffCallback.kt | 25 ++--- .../files/filelist/MainFileListFragment.kt | 49 +++++---- .../security/passcode/PassCodeActivity.kt | 8 +- .../transfers/TransfersDiffUtil.kt | 14 +-- .../android/providers/FileContentProvider.kt | 28 ++--- .../ui/activity/FileDisplayActivity.kt | 46 ++++---- .../synchronization/SynchronizeFileUseCase.kt | 74 ++++++------- .../downloads/DownloadFileUseCase.kt | 12 +- .../files/MoveRemoteFileOperation.kt | 84 +++++++------- .../files/ReadRemoteFolderOperation.kt | 6 +- .../files/RenameRemoteFileOperation.kt | 46 ++++---- .../oauth/GetOIDCDiscoveryRemoteOperation.kt | 8 +- .../oauth/RegisterClientRemoteOperation.kt | 6 +- .../oauth/TokenRequestRemoteOperation.kt | 6 +- .../lib/resources/status/StatusRequester.kt | 66 +++++------ .../implementation/OCLocalFileDataSource.kt | 9 +- .../repository/OCServerInfoRepository.kt | 6 +- 19 files changed, 303 insertions(+), 302 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/documentsprovider/DocumentsStorageProvider.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/documentsprovider/DocumentsStorageProvider.kt index 6188b120430..3d2c1be78f6 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/documentsprovider/DocumentsStorageProvider.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/documentsprovider/DocumentsStorageProvider.kt @@ -127,49 +127,51 @@ class DocumentsStorageProvider : DocumentsProvider() { val fileToOpen = File(ocFile.storagePath) - if (!isWrite) return ParcelFileDescriptor.open(fileToOpen, accessMode) - - val handler = Handler(MainApp.appContext.mainLooper) - // Attach a close listener if the document is opened in write mode. - try { - return ParcelFileDescriptor.open(fileToOpen, accessMode, handler) { - // Update the file with the cloud server. The client is done writing. - Timber.d("A file with id $documentId has been closed! Time to synchronize it with server.") - // If only needs to upload that file - if (uploadOnly) { - ocFile.length = fileToOpen.length() - val uploadFilesUseCase: UploadFilesFromSystemUseCase by inject() - val uploadFilesUseCaseParams = UploadFilesFromSystemUseCase.Params( - accountName = ocFile.owner, - listOfLocalPaths = listOf(fileToOpen.path), - uploadFolderPath = ocFile.remotePath.substringBeforeLast(PATH_SEPARATOR).plus(PATH_SEPARATOR), - spaceId = ocFile.spaceId, - ) - CoroutineScope(Dispatchers.IO).launch { - uploadFilesUseCase(uploadFilesUseCaseParams) - } - } else { - Thread { - val synchronizeFileUseCase: SynchronizeFileUseCase by inject() - val result = synchronizeFileUseCase( - SynchronizeFileUseCase.Params( - fileToSynchronize = ocFile, - ) + return if (!isWrite) { + ParcelFileDescriptor.open(fileToOpen, accessMode) + } else { + val handler = Handler(MainApp.appContext.mainLooper) + // Attach a close listener if the document is opened in write mode. + try { + ParcelFileDescriptor.open(fileToOpen, accessMode, handler) { + // Update the file with the cloud server. The client is done writing. + Timber.d("A file with id $documentId has been closed! Time to synchronize it with server.") + // If only needs to upload that file + if (uploadOnly) { + ocFile.length = fileToOpen.length() + val uploadFilesUseCase: UploadFilesFromSystemUseCase by inject() + val uploadFilesUseCaseParams = UploadFilesFromSystemUseCase.Params( + accountName = ocFile.owner, + listOfLocalPaths = listOf(fileToOpen.path), + uploadFolderPath = ocFile.remotePath.substringBeforeLast(PATH_SEPARATOR).plus(PATH_SEPARATOR), + spaceId = ocFile.spaceId, ) - Timber.d("Synced ${ocFile.remotePath} from ${ocFile.owner} with result: $result") - if (result.getDataOrNull() is SynchronizeFileUseCase.SyncType.ConflictDetected) { - context?.let { - NotificationUtils.notifyConflict( - fileInConflict = ocFile, - context = it + CoroutineScope(Dispatchers.IO).launch { + uploadFilesUseCase(uploadFilesUseCaseParams) + } + } else { + Thread { + val synchronizeFileUseCase: SynchronizeFileUseCase by inject() + val result = synchronizeFileUseCase( + SynchronizeFileUseCase.Params( + fileToSynchronize = ocFile, ) + ) + Timber.d("Synced ${ocFile.remotePath} from ${ocFile.owner} with result: $result") + if (result.getDataOrNull() is SynchronizeFileUseCase.SyncType.ConflictDetected) { + context?.let { + NotificationUtils.notifyConflict( + fileInConflict = ocFile, + context = it + ) + } } - } - }.start() + }.start() + } } + } catch (e: IOException) { + throw FileNotFoundException("Failed to open document with id $documentId and mode $mode") } - } catch (e: IOException) { - throw FileNotFoundException("Failed to open document with id $documentId and mode $mode") } } @@ -287,22 +289,22 @@ class DocumentsStorageProvider : DocumentsProvider() { // If access from document provider is not allowed, return empty cursor val preferences: SharedPreferencesProvider by inject() val lockAccessFromDocumentProvider = preferences.getBoolean(PREFERENCE_LOCK_ACCESS_FROM_DOCUMENT_PROVIDER, false) - if (lockAccessFromDocumentProvider && accounts.isNotEmpty()) { - return result.apply { addProtectedRoot(contextApp) } - } - - for (account in accounts) { - val getStoredCapabilitiesUseCase: GetStoredCapabilitiesUseCase by inject() - val capabilities = getStoredCapabilitiesUseCase( - GetStoredCapabilitiesUseCase.Params( - accountName = account.name + return if (lockAccessFromDocumentProvider && accounts.isNotEmpty()) { + result.apply { addProtectedRoot(contextApp) } + } else { + for (account in accounts) { + val getStoredCapabilitiesUseCase: GetStoredCapabilitiesUseCase by inject() + val capabilities = getStoredCapabilitiesUseCase( + GetStoredCapabilitiesUseCase.Params( + accountName = account.name + ) ) - ) - val spacesFeatureAllowedForAccount = AccountUtils.isSpacesFeatureAllowedForAccount(contextApp, account, capabilities) + val spacesFeatureAllowedForAccount = AccountUtils.isSpacesFeatureAllowedForAccount(contextApp, account, capabilities) - result.addRoot(account, contextApp, spacesFeatureAllowedForAccount) + result.addRoot(account, contextApp, spacesFeatureAllowedForAccount) + } + result } - return result } override fun openDocumentThumbnail( diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt index 2748c1b49d6..7aba743ea48 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt @@ -387,9 +387,9 @@ class FileListAdapter( } private fun generateFooterText(filesCount: Int, foldersCount: Int): String { - when { + return when { filesCount <= 0 -> { - return when { + when { foldersCount <= 0 -> { "" } @@ -405,7 +405,7 @@ class FileListAdapter( } filesCount == 1 -> { - return when { + when { foldersCount <= 0 -> { context.getString(R.string.file_list__footer__file) } @@ -421,7 +421,7 @@ class FileListAdapter( } else -> { // filesCount > 1 - return when { + when { foldersCount <= 0 -> { context.getString(R.string.file_list__footer__files, filesCount) } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListDiffCallback.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListDiffCallback.kt index b72f1987c0d..78c708c6770 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListDiffCallback.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListDiffCallback.kt @@ -41,23 +41,18 @@ class FileListDiffCallback( val oldItem = oldList[oldItemPosition] val newItem = newList[newItemPosition] - if (oldItem is Unit && newItem is Unit) { - return true + return if (oldItem is Unit && newItem is Unit) { + true + } else if (oldItem is Boolean && newItem is Boolean) { + true + } else if (oldItem is OCFileWithSyncInfo && newItem is OCFileWithSyncInfo) { + oldItem.file.id == newItem.file.id + } else if (oldItem is OCFooterFile && newItem is OCFooterFile) { + oldItem.text == newItem.text + } else { + false } - if (oldItem is Boolean && newItem is Boolean) { - return true - } - - if (oldItem is OCFileWithSyncInfo && newItem is OCFileWithSyncInfo) { - return oldItem.file.id == newItem.file.id - } - - if (oldItem is OCFooterFile && newItem is OCFooterFile) { - return oldItem.text == newItem.text - } - - return false } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean = diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt index c9f9bd35bb4..1d00df1340e 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt @@ -1230,19 +1230,19 @@ class MainFileListFragment : Fragment(), } } - when (menuId) { + return when (menuId) { R.id.action_share_file -> { fileActions?.onShareFileClicked(singleFile) fileListAdapter.clearSelection() updateActionModeAfterTogglingSelected() - return true + true } R.id.action_open_file_with -> { fileActions?.openFile(singleFile) fileListAdapter.clearSelection() updateActionModeAfterTogglingSelected() - return true + true } R.id.action_rename_file -> { @@ -1250,19 +1250,19 @@ class MainFileListFragment : Fragment(), dialog.show(requireActivity().supportFragmentManager, FRAGMENT_TAG_RENAME_FILE) fileListAdapter.clearSelection() updateActionModeAfterTogglingSelected() - return true + true } R.id.action_see_details -> { fileListAdapter.clearSelection() updateActionModeAfterTogglingSelected() fileActions?.showDetails(singleFile) - return true + true } R.id.action_sync_file -> { syncFiles(listOf(singleFile)) - return true + true } R.id.action_send_file -> { @@ -1273,7 +1273,7 @@ class MainFileListFragment : Fragment(), } else { fileActions?.sendDownloadedFile(singleFile) } - return true + true } R.id.action_set_available_offline -> { @@ -1289,46 +1289,49 @@ class MainFileListFragment : Fragment(), } else { fileOperationsViewModel.performOperation(FileOperation.SynchronizeFileOperation(singleFile, singleFile.owner)) } - return true + true } R.id.action_unset_available_offline -> { fileOperationsViewModel.performOperation(FileOperation.UnsetFilesAsAvailableOffline(listOf(singleFile))) - return true + true + } + + else -> { + false } } - return false } private fun onCheckedFilesActionChosen(menuId: Int?, checkedFiles: ArrayList): Boolean { - when (menuId) { + return when (menuId) { R.id.file_action_select_all -> { fileListAdapter.selectAll() updateActionModeAfterTogglingSelected() - return true + true } R.id.action_select_inverse -> { fileListAdapter.selectInverse() updateActionModeAfterTogglingSelected() - return true + true } R.id.action_remove_file -> { filesToRemove = checkedFiles fileOperationsViewModel.showRemoveDialog(filesToRemove) - return true + true } R.id.action_download_file, R.id.action_sync_file -> { syncFiles(checkedFiles) - return true + true } R.id.action_cancel_sync -> { fileActions?.cancelFileTransference(checkedFiles) - return true + true } R.id.action_set_available_offline -> { @@ -1340,16 +1343,17 @@ class MainFileListFragment : Fragment(), fileOperationsViewModel.performOperation(FileOperation.SynchronizeFileOperation(ocFile, ocFile.owner)) } } - return true + true } R.id.action_unset_available_offline -> { fileOperationsViewModel.performOperation(FileOperation.UnsetFilesAsAvailableOffline(checkedFiles)) - return true + true } R.id.action_send_file -> { requireActivity().sendDownloadedFilesByShareSheet(checkedFiles) + true } R.id.action_move -> { @@ -1359,7 +1363,7 @@ class MainFileListFragment : Fragment(), requireActivity().startActivityForResult(action, FileDisplayActivity.REQUEST_CODE__MOVE_FILES) fileListAdapter.clearSelection() updateActionModeAfterTogglingSelected() - return true + true } R.id.action_copy -> { @@ -1369,10 +1373,13 @@ class MainFileListFragment : Fragment(), requireActivity().startActivityForResult(action, FileDisplayActivity.REQUEST_CODE__COPY_FILES) fileListAdapter.clearSelection() updateActionModeAfterTogglingSelected() - return true + true + } + + else -> { + false } } - return false } /** diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt index 74ea292d9cf..6ee5b88e998 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt @@ -416,17 +416,17 @@ class PassCodeActivity : AppCompatActivity(), NumberKeyboardListener, EnableBiom } private fun getPasscodeAction(action: String?): PasscodeAction { - when (action) { + return when (action) { ACTION_REMOVE -> { - return PasscodeAction.REMOVE + PasscodeAction.REMOVE } ACTION_CREATE -> { - return PasscodeAction.CREATE + PasscodeAction.CREATE } else -> { - return PasscodeAction.CHECK + PasscodeAction.CHECK } } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/transfers/TransfersDiffUtil.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/transfers/TransfersDiffUtil.kt index 7ac66db5e02..1a03ccdbd79 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/transfers/TransfersDiffUtil.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/transfers/TransfersDiffUtil.kt @@ -34,15 +34,13 @@ class TransfersDiffUtil( val oldItem = oldList[oldItemPosition] val newItem = newList[newItemPosition] - if (oldItem is TransfersAdapter.TransferRecyclerItem.TransferItem && newItem is TransfersAdapter.TransferRecyclerItem.TransferItem) { - return oldItem.transfer.id == newItem.transfer.id + return if (oldItem is TransfersAdapter.TransferRecyclerItem.TransferItem && newItem is TransfersAdapter.TransferRecyclerItem.TransferItem) { + oldItem.transfer.id == newItem.transfer.id + } else if (oldItem is TransfersAdapter.TransferRecyclerItem.HeaderItem && newItem is TransfersAdapter.TransferRecyclerItem.HeaderItem) { + oldItem.status == newItem.status + } else { + false } - - if (oldItem is TransfersAdapter.TransferRecyclerItem.HeaderItem && newItem is TransfersAdapter.TransferRecyclerItem.HeaderItem) { - return oldItem.status == newItem.status - } - - return false } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean = diff --git a/owncloudApp/src/main/java/com/owncloud/android/providers/FileContentProvider.kt b/owncloudApp/src/main/java/com/owncloud/android/providers/FileContentProvider.kt index 363ac937750..e06575660da 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/providers/FileContentProvider.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/providers/FileContentProvider.kt @@ -194,7 +194,7 @@ class FileContentProvider(val executors: Executors = Executors()) : ContentProvi } private fun insert(db: SQLiteDatabase, uri: Uri, values: ContentValues?): Uri { - when (uriMatcher.match(uri)) { + return when (uriMatcher.match(uri)) { ROOT_DIRECTORY, SINGLE_FILE -> { val remotePath = values?.getAsString(ProviderTableMeta.FILE_PATH) val accountName = values?.getAsString(ProviderTableMeta.FILE_ACCOUNT_OWNER) @@ -230,7 +230,7 @@ class FileContentProvider(val executors: Executors = Executors()) : ContentProvi val shareId = db.insert(ProviderTableMeta.OCSHARES_TABLE_NAME, null, values) if (shareId <= 0) throw SQLException("ERROR $uri") - return ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_SHARE, shareId) + ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_SHARE, shareId) } @@ -238,7 +238,7 @@ class FileContentProvider(val executors: Executors = Executors()) : ContentProvi val capabilityId = db.insert(ProviderTableMeta.CAPABILITIES_TABLE_NAME, null, values) if (capabilityId <= 0) throw SQLException("ERROR $uri") - return ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_CAPABILITIES, capabilityId) + ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_CAPABILITIES, capabilityId) } UPLOADS -> { @@ -246,7 +246,7 @@ class FileContentProvider(val executors: Executors = Executors()) : ContentProvi if (uploadId <= 0) throw SQLException("ERROR $uri") trimSuccessfulUploads(db) - return ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_UPLOADS, uploadId) + ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_UPLOADS, uploadId) } CAMERA_UPLOADS_SYNC -> { @@ -256,7 +256,7 @@ class FileContentProvider(val executors: Executors = Executors()) : ContentProvi ) if (cameraUploadId <= 0) throw SQLException("ERROR $uri") - return ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_CAMERA_UPLOADS_SYNC, cameraUploadId) + ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_CAMERA_UPLOADS_SYNC, cameraUploadId) } QUOTAS -> { val quotaId = db.insert( @@ -265,7 +265,7 @@ class FileContentProvider(val executors: Executors = Executors()) : ContentProvi ) if (quotaId <= 0) throw SQLException("ERROR $uri") - return ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_QUOTAS, quotaId) + ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_QUOTAS, quotaId) } else -> throw IllegalArgumentException("Unknown uri id: $uri") } @@ -414,18 +414,18 @@ class FileContentProvider(val executors: Executors = Executors()) : ContentProvi if (selection != null && selectionArgs == null) { throw IllegalArgumentException("Selection not allowed, use parameterized queries") } - when (uriMatcher.match(uri)) { - DIRECTORY -> return 0 //updateFolderSize(db, selectionArgs[0]); - SHARES -> return db.update(ProviderTableMeta.OCSHARES_TABLE_NAME, values, selection, selectionArgs) - CAPABILITIES -> return db.update(ProviderTableMeta.CAPABILITIES_TABLE_NAME, values, selection, selectionArgs) + return when (uriMatcher.match(uri)) { + DIRECTORY -> 0 //updateFolderSize(db, selectionArgs[0]); + SHARES -> db.update(ProviderTableMeta.OCSHARES_TABLE_NAME, values, selection, selectionArgs) + CAPABILITIES -> db.update(ProviderTableMeta.CAPABILITIES_TABLE_NAME, values, selection, selectionArgs) UPLOADS -> { val ret = db.update(ProviderTableMeta.UPLOADS_TABLE_NAME, values, selection, selectionArgs) trimSuccessfulUploads(db) - return ret + ret } - CAMERA_UPLOADS_SYNC -> return db.update(ProviderTableMeta.CAMERA_UPLOADS_SYNC_TABLE_NAME, values, selection, selectionArgs) - QUOTAS -> return db.update(ProviderTableMeta.USER_QUOTAS_TABLE_NAME, values, selection, selectionArgs) - else -> return db.update( + CAMERA_UPLOADS_SYNC -> db.update(ProviderTableMeta.CAMERA_UPLOADS_SYNC_TABLE_NAME, values, selection, selectionArgs) + QUOTAS -> db.update(ProviderTableMeta.USER_QUOTAS_TABLE_NAME, values, selection, selectionArgs) + else -> db.update( ProviderTableMeta.FILE_TABLE_NAME, values, selection, selectionArgs ) } diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt index d1bdbfca5fd..ff97ffe1cf9 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt @@ -464,33 +464,37 @@ class FileDisplayActivity : FileActivity(), val secondFragment = supportFragmentManager.findFragmentByTag(TAG_SECOND_FRAGMENT) as FileFragment? // Return second fragment if it has been already chosen - if (secondFragment != null) return secondFragment + return if (secondFragment != null) { + secondFragment // Return null if we receive a folder. This way, second fragment will be cleared. We should move this logic out of here. - if (file.isFolder) return null + } else if (file.isFolder) { + null // Otherwise, decide which fragment should be shown. - return when { - PreviewAudioFragment.canBePreviewed(file) -> { - val startPlaybackPosition = intent.getIntExtra(PreviewVideoActivity.EXTRA_PLAY_POSITION, 0) - val autoplay = intent.getBooleanExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, true) - PreviewAudioFragment.newInstance( - file, - account, - startPlaybackPosition, - autoplay - ) - } + } else { + when { + PreviewAudioFragment.canBePreviewed(file) -> { + val startPlaybackPosition = intent.getIntExtra(PreviewVideoActivity.EXTRA_PLAY_POSITION, 0) + val autoplay = intent.getBooleanExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, true) + PreviewAudioFragment.newInstance( + file, + account, + startPlaybackPosition, + autoplay + ) + } - PreviewTextFragment.canBePreviewed(file) -> { - PreviewTextFragment.newInstance( - file, - account - ) - } + PreviewTextFragment.canBePreviewed(file) -> { + PreviewTextFragment.newInstance( + file, + account + ) + } - else -> { - FileDetailsFragment.newInstance(file, account, false) + else -> { + FileDetailsFragment.newInstance(file, account, false) + } } } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/usecases/synchronization/SynchronizeFileUseCase.kt b/owncloudApp/src/main/java/com/owncloud/android/usecases/synchronization/SynchronizeFileUseCase.kt index ff96526f3bd..e292f902792 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/usecases/synchronization/SynchronizeFileUseCase.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/usecases/synchronization/SynchronizeFileUseCase.kt @@ -65,49 +65,49 @@ class SynchronizeFileUseCase( } // 2. File not downloaded -> Download it - if (!fileToSynchronize.isAvailableLocally) { + return if (!fileToSynchronize.isAvailableLocally) { Timber.i("File ${fileToSynchronize.fileName} is not downloaded. Let's download it") val uuid = requestForDownload(accountName = accountName, ocFile = fileToSynchronize) - return SyncType.DownloadEnqueued(uuid) - } - - // 3. Check if file has changed locally - val changedLocally = fileToSynchronize.localModificationTimestamp > fileToSynchronize.lastSyncDateForData!! - Timber.i("Local file modification timestamp :${fileToSynchronize.localModificationTimestamp}" + - " and last sync date for data :${fileToSynchronize.lastSyncDateForData}") - Timber.i("So it has changed locally: $changedLocally") + SyncType.DownloadEnqueued(uuid) + } else { + // 3. Check if file has changed locally + val changedLocally = fileToSynchronize.localModificationTimestamp > fileToSynchronize.lastSyncDateForData!! + Timber.i("Local file modification timestamp :${fileToSynchronize.localModificationTimestamp}" + + " and last sync date for data :${fileToSynchronize.lastSyncDateForData}") + Timber.i("So it has changed locally: $changedLocally") - // 4. Check if file has changed remotely - val changedRemotely = serverFile.etag != fileToSynchronize.etag - Timber.i("Local etag :${fileToSynchronize.etag} and remote etag :${serverFile.etag}") - Timber.i("So it has changed remotely: $changedRemotely") + // 4. Check if file has changed remotely + val changedRemotely = serverFile.etag != fileToSynchronize.etag + Timber.i("Local etag :${fileToSynchronize.etag} and remote etag :${serverFile.etag}") + Timber.i("So it has changed remotely: $changedRemotely") - if (changedLocally && changedRemotely) { - // 5.1 File has changed locally and remotely. We got a conflict, save the conflict. - Timber.i("File ${fileToSynchronize.fileName} has changed locally and remotely. We got a conflict with etag: ${serverFile.etag}") - if (fileToSynchronize.etagInConflict == null) { - saveConflictUseCase( - SaveConflictUseCase.Params( - fileId = fileToSynchronize.id!!, - eTagInConflict = serverFile.etag!! + if (changedLocally && changedRemotely) { + // 5.1 File has changed locally and remotely. We got a conflict, save the conflict. + Timber.i("File ${fileToSynchronize.fileName} has changed locally and remotely. We got a conflict with etag: ${serverFile.etag}") + if (fileToSynchronize.etagInConflict == null) { + saveConflictUseCase( + SaveConflictUseCase.Params( + fileId = fileToSynchronize.id!!, + eTagInConflict = serverFile.etag!! + ) ) - ) + } + SyncType.ConflictDetected(serverFile.etag!!) + } else if (changedRemotely) { + // 5.2 File has changed ONLY remotely -> download new version + Timber.i("File ${fileToSynchronize.fileName} has changed remotely. Let's download the new version") + val uuid = requestForDownload(accountName, fileToSynchronize) + SyncType.DownloadEnqueued(uuid) + } else if (changedLocally) { + // 5.3 File has change ONLY locally -> upload new version + Timber.i("File ${fileToSynchronize.fileName} has changed locally. Let's upload the new version") + val uuid = requestForUpload(accountName, fileToSynchronize) + SyncType.UploadEnqueued(uuid) + } else { + // 5.4 File has not change locally not remotely -> do nothing + Timber.i("File ${fileToSynchronize.fileName} is already synchronized. Nothing to do here") + SyncType.AlreadySynchronized } - return SyncType.ConflictDetected(serverFile.etag!!) - } else if (changedRemotely) { - // 5.2 File has changed ONLY remotely -> download new version - Timber.i("File ${fileToSynchronize.fileName} has changed remotely. Let's download the new version") - val uuid = requestForDownload(accountName, fileToSynchronize) - return SyncType.DownloadEnqueued(uuid) - } else if (changedLocally) { - // 5.3 File has change ONLY locally -> upload new version - Timber.i("File ${fileToSynchronize.fileName} has changed locally. Let's upload the new version") - val uuid = requestForUpload(accountName, fileToSynchronize) - return SyncType.UploadEnqueued(uuid) - } else { - // 5.4 File has not change locally not remotely -> do nothing - Timber.i("File ${fileToSynchronize.fileName} is already synchronized. Nothing to do here") - return SyncType.AlreadySynchronized } } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/usecases/transfers/downloads/DownloadFileUseCase.kt b/owncloudApp/src/main/java/com/owncloud/android/usecases/transfers/downloads/DownloadFileUseCase.kt index a60909cb5f1..56c40788046 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/usecases/transfers/downloads/DownloadFileUseCase.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/usecases/transfers/downloads/DownloadFileUseCase.kt @@ -50,13 +50,13 @@ class DownloadFileUseCase( val ocFile = params.file val accountName = params.accountName - if (ocFile.id == null) return null - - if (isDownloadAlreadyEnqueued(accountName, ocFile)) { - return null + return if (ocFile.id == null) { + null + } else if (isDownloadAlreadyEnqueued(accountName, ocFile)) { + null + } else { + enqueueNewDownload(ocFile, accountName) } - - return enqueueNewDownload(ocFile, accountName) } private fun isDownloadAlreadyEnqueued(accountName: String, file: OCFile): Boolean { diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/MoveRemoteFileOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/MoveRemoteFileOperation.kt index 7da6684c967..5e86e5e0412 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/MoveRemoteFileOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/MoveRemoteFileOperation.kt @@ -64,59 +64,57 @@ open class MoveRemoteFileOperation( * @param client Client object to communicate with the remote ownCloud server. */ override fun run(client: OwnCloudClient): RemoteOperationResult { - if (targetRemotePath == sourceRemotePath) { + return if (targetRemotePath == sourceRemotePath) { // nothing to do! - return RemoteOperationResult(ResultCode.OK) - } - - if (targetRemotePath.startsWith(sourceRemotePath)) { - return RemoteOperationResult(ResultCode.INVALID_MOVE_INTO_DESCENDANT) - } - - /// perform remote operation - var result: RemoteOperationResult - try { - // After finishing a chunked upload, we have to move the resulting file from uploads folder to files one, - // so this uri has to be customizable - val srcWebDavUri = getSrcWebDavUriForClient(client) - val moveMethod = MoveMethod( - url = URL((spaceWebDavUrl ?: srcWebDavUri.toString()) + WebdavUtils.encodePath(sourceRemotePath)), - destinationUrl = (spaceWebDavUrl ?: client.userFilesWebDavUri.toString()) + WebdavUtils.encodePath(targetRemotePath), - forceOverride = forceOverride, - ).apply { - addRequestHeaders(this) - setReadTimeout(MOVE_READ_TIMEOUT, TimeUnit.SECONDS) - setConnectionTimeout(MOVE_CONNECTION_TIMEOUT, TimeUnit.SECONDS) - } + RemoteOperationResult(ResultCode.OK) + } else if (targetRemotePath.startsWith(sourceRemotePath)) { + RemoteOperationResult(ResultCode.INVALID_MOVE_INTO_DESCENDANT) + } else { + /// perform remote operation + var result: RemoteOperationResult + try { + // After finishing a chunked upload, we have to move the resulting file from uploads folder to files one, + // so this uri has to be customizable + val srcWebDavUri = getSrcWebDavUriForClient(client) + val moveMethod = MoveMethod( + url = URL((spaceWebDavUrl ?: srcWebDavUri.toString()) + WebdavUtils.encodePath(sourceRemotePath)), + destinationUrl = (spaceWebDavUrl ?: client.userFilesWebDavUri.toString()) + WebdavUtils.encodePath(targetRemotePath), + forceOverride = forceOverride, + ).apply { + addRequestHeaders(this) + setReadTimeout(MOVE_READ_TIMEOUT, TimeUnit.SECONDS) + setConnectionTimeout(MOVE_CONNECTION_TIMEOUT, TimeUnit.SECONDS) + } - val status = client.executeHttpMethod(moveMethod) + val status = client.executeHttpMethod(moveMethod) - when { - isSuccess(status) -> { - result = RemoteOperationResult(ResultCode.OK) - } + when { + isSuccess(status) -> { + result = RemoteOperationResult(ResultCode.OK) + } - isPreconditionFailed(status) -> { - result = RemoteOperationResult(ResultCode.INVALID_OVERWRITE) - client.exhaustResponse(moveMethod.getResponseBodyAsStream()) + isPreconditionFailed(status) -> { + result = RemoteOperationResult(ResultCode.INVALID_OVERWRITE) + client.exhaustResponse(moveMethod.getResponseBodyAsStream()) - /// for other errors that could be explicitly handled, check first: - /// http://www.webdav.org/specs/rfc4918.html#rfc.section.9.9.4 - } + /// for other errors that could be explicitly handled, check first: + /// http://www.webdav.org/specs/rfc4918.html#rfc.section.9.9.4 + } - else -> { - result = RemoteOperationResult(moveMethod) - client.exhaustResponse(moveMethod.getResponseBodyAsStream()) + else -> { + result = RemoteOperationResult(moveMethod) + client.exhaustResponse(moveMethod.getResponseBodyAsStream()) + } } - } - Timber.i("Move $sourceRemotePath to $targetRemotePath - HTTP status code: $status") - } catch (e: Exception) { - result = RemoteOperationResult(e) - Timber.e(e, "Move $sourceRemotePath to $targetRemotePath: ${result.logMessage}") + Timber.i("Move $sourceRemotePath to $targetRemotePath - HTTP status code: $status") + } catch (e: Exception) { + result = RemoteOperationResult(e) + Timber.e(e, "Move $sourceRemotePath to $targetRemotePath: ${result.logMessage}") + } + result } - return result } /** diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/ReadRemoteFolderOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/ReadRemoteFolderOperation.kt index b816bf12014..f85e27ee0c5 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/ReadRemoteFolderOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/ReadRemoteFolderOperation.kt @@ -69,7 +69,7 @@ class ReadRemoteFolderOperation( val status = client.executeHttpMethod(propfindMethod) - if (isSuccess(status)) { + return if (isSuccess(status)) { val mFolderAndFiles = ArrayList() val remoteFolder = RemoteFile.getRemoteFileFromDav( @@ -92,12 +92,12 @@ class ReadRemoteFolderOperation( } // Result of the operation - return RemoteOperationResult>(ResultCode.OK).apply { + RemoteOperationResult>(ResultCode.OK).apply { data = mFolderAndFiles Timber.i("Synchronized $remotePath with ${mFolderAndFiles.size} files. - HTTP status code: $status") } } else { // synchronization failed - return RemoteOperationResult>(propfindMethod).also { + RemoteOperationResult>(propfindMethod).also { Timber.w("Synchronized $remotePath ${it.logMessage}") } } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/RenameRemoteFileOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/RenameRemoteFileOperation.kt index 70ed48f6b42..2d712cdea37 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/RenameRemoteFileOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/RenameRemoteFileOperation.kt @@ -66,37 +66,35 @@ class RenameRemoteFileOperation( override fun run(client: OwnCloudClient): RemoteOperationResult { var result: RemoteOperationResult - try { + return try { if (newName == oldName) { - return RemoteOperationResult(ResultCode.OK) - } - - if (targetPathIsUsed(client)) { - return RemoteOperationResult(ResultCode.INVALID_OVERWRITE) - } - - val moveMethod: MoveMethod = MoveMethod( - url = URL((spaceWebDavUrl ?: client.userFilesWebDavUri.toString()) + WebdavUtils.encodePath(oldRemotePath)), - destinationUrl = (spaceWebDavUrl ?: client.userFilesWebDavUri.toString()) + WebdavUtils.encodePath(newRemotePath), - ).apply { - setReadTimeout(RENAME_READ_TIMEOUT, TimeUnit.MILLISECONDS) - setConnectionTimeout(RENAME_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS) - } - val status = client.executeHttpMethod(moveMethod) - - result = if (isSuccess(status)) { RemoteOperationResult(ResultCode.OK) + } else if (targetPathIsUsed(client)) { + RemoteOperationResult(ResultCode.INVALID_OVERWRITE) } else { - RemoteOperationResult(moveMethod) - } + val moveMethod: MoveMethod = MoveMethod( + url = URL((spaceWebDavUrl ?: client.userFilesWebDavUri.toString()) + WebdavUtils.encodePath(oldRemotePath)), + destinationUrl = (spaceWebDavUrl ?: client.userFilesWebDavUri.toString()) + WebdavUtils.encodePath(newRemotePath), + ).apply { + setReadTimeout(RENAME_READ_TIMEOUT, TimeUnit.MILLISECONDS) + setConnectionTimeout(RENAME_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS) + } + val status = client.executeHttpMethod(moveMethod) - Timber.i("Rename $oldRemotePath to $newRemotePath - HTTP status code: $status") - client.exhaustResponse(moveMethod.getResponseBodyAsStream()) - return result + result = if (isSuccess(status)) { + RemoteOperationResult(ResultCode.OK) + } else { + RemoteOperationResult(moveMethod) + } + + Timber.i("Rename $oldRemotePath to $newRemotePath - HTTP status code: $status") + client.exhaustResponse(moveMethod.getResponseBodyAsStream()) + result + } } catch (exception: Exception) { result = RemoteOperationResult(exception) Timber.e(exception, "Rename $oldRemotePath to $newName: ${result.logMessage}") - return result + result } } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/oauth/GetOIDCDiscoveryRemoteOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/oauth/GetOIDCDiscoveryRemoteOperation.kt index c3f55dc9ea6..5f3b11db1de 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/oauth/GetOIDCDiscoveryRemoteOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/oauth/GetOIDCDiscoveryRemoteOperation.kt @@ -60,7 +60,7 @@ class GetOIDCDiscoveryRemoteOperation : RemoteOperation() val responseBody = getMethod.getResponseBodyAsString() - if (status == HttpConstants.HTTP_OK && responseBody != null) { + return if (status == HttpConstants.HTTP_OK && responseBody != null) { Timber.d("Successful response $responseBody") // Parse the response @@ -69,19 +69,17 @@ class GetOIDCDiscoveryRemoteOperation : RemoteOperation() val oidcDiscoveryResponse: OIDCDiscoveryResponse? = jsonAdapter.fromJson(responseBody) Timber.d("Get OIDC Discovery completed and parsed to [$oidcDiscoveryResponse]") - return RemoteOperationResult(RemoteOperationResult.ResultCode.OK).apply { + RemoteOperationResult(RemoteOperationResult.ResultCode.OK).apply { data = oidcDiscoveryResponse } } else { Timber.e("Failed response while getting OIDC server discovery from the server status code: $status; response message: $responseBody") - - return RemoteOperationResult(getMethod) + RemoteOperationResult(getMethod) } } catch (e: Exception) { Timber.e(e, "Exception while getting OIDC server discovery") - return RemoteOperationResult(e) } } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/oauth/RegisterClientRemoteOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/oauth/RegisterClientRemoteOperation.kt index 5d6482da8bc..ab553b5117c 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/oauth/RegisterClientRemoteOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/oauth/RegisterClientRemoteOperation.kt @@ -56,7 +56,7 @@ class RegisterClientRemoteOperation( val responseBody = postMethod.getResponseBodyAsString() - if (status == HttpConstants.HTTP_CREATED && responseBody != null) { + return if (status == HttpConstants.HTTP_CREATED && responseBody != null) { Timber.d("Successful response $responseBody") // Parse the response @@ -66,13 +66,13 @@ class RegisterClientRemoteOperation( val clientRegistrationResponse: ClientRegistrationResponse? = jsonAdapter.fromJson(responseBody) Timber.d("Client registered and parsed to $clientRegistrationResponse") - return RemoteOperationResult(RemoteOperationResult.ResultCode.OK).apply { + RemoteOperationResult(RemoteOperationResult.ResultCode.OK).apply { data = clientRegistrationResponse } } else { Timber.e("Failed response while registering a new client. Status code: $status; response message: $responseBody") - return RemoteOperationResult(postMethod) + RemoteOperationResult(postMethod) } } catch (e: Exception) { diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/oauth/TokenRequestRemoteOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/oauth/TokenRequestRemoteOperation.kt index 67253c4c846..cd1f2bc170c 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/oauth/TokenRequestRemoteOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/oauth/TokenRequestRemoteOperation.kt @@ -60,7 +60,7 @@ class TokenRequestRemoteOperation( val responseBody = postMethod.getResponseBodyAsString() - if (status == HTTP_OK && responseBody != null) { + return if (status == HTTP_OK && responseBody != null) { Timber.d("Successful response $responseBody") // Parse the response @@ -69,13 +69,13 @@ class TokenRequestRemoteOperation( val tokenResponse: TokenResponse? = jsonAdapter.fromJson(responseBody) Timber.d("Get tokens completed and parsed to $tokenResponse") - return RemoteOperationResult(RemoteOperationResult.ResultCode.OK).apply { + RemoteOperationResult(RemoteOperationResult.ResultCode.OK).apply { data = tokenResponse } } else { Timber.e("Failed response while getting tokens from the server status code: $status; response message: $responseBody") - return RemoteOperationResult(postMethod) + RemoteOperationResult(postMethod) } } catch (e: Exception) { diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/StatusRequester.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/StatusRequester.kt index 09a3f71e040..a54306ab124 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/StatusRequester.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/StatusRequester.kt @@ -53,14 +53,14 @@ internal class StatusRequester { /** Redirection with different endpoint. * When asking for server.com/status.php and redirected to different.one/, we need to ask different.one/status.php */ - if (redirectedLocation.endsWith('/')) { - return redirectedLocation.trimEnd('/') + OwnCloudClient.STATUS_PATH + return if (redirectedLocation.endsWith('/')) { + redirectedLocation.trimEnd('/') + OwnCloudClient.STATUS_PATH + } else if (!redirectedLocation.startsWith("/")) { + redirectedLocation + } else { + val oldLocationURL = URL(oldLocation) + URL(oldLocationURL.protocol, oldLocationURL.host, oldLocationURL.port, redirectedLocation).toString() } - - if (!redirectedLocation.startsWith("/")) - return redirectedLocation - val oldLocationURL = URL(oldLocation) - return URL(oldLocationURL.protocol, oldLocationURL.host, oldLocationURL.port, redirectedLocation).toString() } private fun getGetMethod(url: String): GetMethod = @@ -92,33 +92,33 @@ internal class StatusRequester { requestResult: RequestResult, baseUrl: String ): RemoteOperationResult { - if (!requestResult.status.isSuccess()) - return RemoteOperationResult(requestResult.getMethod) - val respJSON = JSONObject(requestResult.getMethod.getResponseBodyAsString()) - if (!respJSON.getBoolean(NODE_INSTALLED)) - return RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED) - - val ocVersion = OwnCloudVersion(respJSON.getString(NODE_VERSION)) - // the version object will be returned even if the version is invalid, no error code; - // every app will decide how to act if (ocVersion.isVersionValid() == false) - val result: RemoteOperationResult = - if (baseUrl.startsWith(HTTPS_SCHEME)) RemoteOperationResult(RemoteOperationResult.ResultCode.OK_SSL) - else RemoteOperationResult(RemoteOperationResult.ResultCode.OK_NO_SSL) - val finalUrl = URL(requestResult.lastLocation) - val finalBaseUrl = URL( - finalUrl.protocol, - finalUrl.host, - finalUrl.port, - finalUrl.file.dropLastWhile { it != '/' }.trimEnd('/') - ) - - result.data = RemoteServerInfo( - ownCloudVersion = ocVersion, - baseUrl = finalBaseUrl.toString(), - isSecureConnection = finalBaseUrl.protocol.startsWith(HTTPS_SCHEME) - ) - return result + return if (!requestResult.status.isSuccess()) { + RemoteOperationResult(requestResult.getMethod) + } else if (!respJSON.getBoolean(NODE_INSTALLED)) { + RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED) + } else { + val ocVersion = OwnCloudVersion(respJSON.getString(NODE_VERSION)) + // the version object will be returned even if the version is invalid, no error code; + // every app will decide how to act if (ocVersion.isVersionValid() == false) + val result: RemoteOperationResult = + if (baseUrl.startsWith(HTTPS_SCHEME)) RemoteOperationResult(RemoteOperationResult.ResultCode.OK_SSL) + else RemoteOperationResult(RemoteOperationResult.ResultCode.OK_NO_SSL) + val finalUrl = URL(requestResult.lastLocation) + val finalBaseUrl = URL( + finalUrl.protocol, + finalUrl.host, + finalUrl.port, + finalUrl.file.dropLastWhile { it != '/' }.trimEnd('/') + ) + + result.data = RemoteServerInfo( + ownCloudVersion = ocVersion, + baseUrl = finalBaseUrl.toString(), + isSecureConnection = finalBaseUrl.protocol.startsWith(HTTPS_SCHEME) + ) + result + } } companion object { diff --git a/owncloudData/src/main/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSource.kt b/owncloudData/src/main/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSource.kt index 5d16bff6335..0bfd831c9ae 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSource.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSource.kt @@ -55,7 +55,7 @@ class OCLocalFileDataSource( fileDao.getFileByOwnerAndRemotePath(owner, remotePath, spaceId)?.let { return it.toModel() } // If root folder do not exists, create and return it. - if (remotePath == ROOT_PATH) { + return if (remotePath == ROOT_PATH) { val rootFolder = OCFile( parentId = ROOT_PARENT_ID, owner = owner, @@ -66,10 +66,11 @@ class OCLocalFileDataSource( spaceId = spaceId, permissions = "CK", ) - fileDao.mergeRemoteAndLocalFile(rootFolder.toEntity()).also { return getFileById(it) } + val idFile = fileDao.mergeRemoteAndLocalFile(rootFolder.toEntity()) + getFileById(idFile) + } else { + null } - - return null } override fun getFileByRemoteId(remoteId: String): OCFile? = diff --git a/owncloudData/src/main/java/com/owncloud/android/data/server/repository/OCServerInfoRepository.kt b/owncloudData/src/main/java/com/owncloud/android/data/server/repository/OCServerInfoRepository.kt index dcffee6f3bd..6547add0bd3 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/server/repository/OCServerInfoRepository.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/server/repository/OCServerInfoRepository.kt @@ -49,8 +49,8 @@ class OCServerInfoRepository( val serverInfo = remoteServerInfoDataSource.getServerInfo(path, enforceOIDC) - if (serverInfo is ServerInfo.BasicServer) { - return serverInfo + return if (serverInfo is ServerInfo.BasicServer) { + serverInfo } else { // Could be OAuth or OpenID Connect val openIDConnectServerConfiguration = try { @@ -60,7 +60,7 @@ class OCServerInfoRepository( null } - return if (openIDConnectServerConfiguration != null) { + if (openIDConnectServerConfiguration != null) { ServerInfo.OIDCServer( ownCloudVersion = serverInfo.ownCloudVersion, baseUrl = serverInfo.baseUrl, From 3c35a89504a2778d3decba201a32b196fea89fff Mon Sep 17 00:00:00 2001 From: joragua Date: Wed, 22 Jan 2025 17:21:57 +0100 Subject: [PATCH 45/74] feat: disabled ReturnCount codesmell from detekt.yml --- config/detekt/detekt.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.yml index cb449f47faf..3bf851de6f7 100644 --- a/config/detekt/detekt.yml +++ b/config/detekt/detekt.yml @@ -817,7 +817,7 @@ style: RedundantVisibilityModifierRule: active: true ReturnCount: - active: true + active: false max: 2 excludedFunctions: ['equals'] excludeLabeled: false From 24ef5004d09b630ce9b4e705dfb0e8adb5dd1ba7 Mon Sep 17 00:00:00 2001 From: joragua Date: Thu, 23 Jan 2025 08:46:46 +0100 Subject: [PATCH 46/74] style: changed functions with just return to expression body --- .../presentation/files/filelist/FileListAdapter.kt | 5 ++--- .../files/filelist/MainFileListFragment.kt | 5 ++--- .../security/passcode/PassCodeActivity.kt | 5 ++--- .../android/providers/FileContentProvider.kt | 8 +++----- .../transfers/downloads/DownloadFileUseCase.kt | 12 ++++++------ .../lib/resources/files/MoveRemoteFileOperation.kt | 5 ++--- .../android/lib/resources/status/StatusRequester.kt | 5 ++--- 7 files changed, 19 insertions(+), 26 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt index 7aba743ea48..d82cf82bd5d 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/FileListAdapter.kt @@ -386,8 +386,8 @@ class FileListAdapter( } } - private fun generateFooterText(filesCount: Int, foldersCount: Int): String { - return when { + private fun generateFooterText(filesCount: Int, foldersCount: Int): String = + when { filesCount <= 0 -> { when { foldersCount <= 0 -> { @@ -438,7 +438,6 @@ class FileListAdapter( } } } - } interface FileListAdapterListener { fun onItemClick(ocFileWithSyncInfo: OCFileWithSyncInfo, position: Int) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt index 1d00df1340e..b09c371b4a1 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt @@ -1303,8 +1303,8 @@ class MainFileListFragment : Fragment(), } } - private fun onCheckedFilesActionChosen(menuId: Int?, checkedFiles: ArrayList): Boolean { - return when (menuId) { + private fun onCheckedFilesActionChosen(menuId: Int?, checkedFiles: ArrayList): Boolean = + when (menuId) { R.id.file_action_select_all -> { fileListAdapter.selectAll() updateActionModeAfterTogglingSelected() @@ -1380,7 +1380,6 @@ class MainFileListFragment : Fragment(), false } } - } /** * Update or remove the actionMode after applying any change to the selected items. diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt index 6ee5b88e998..e34cf0c42a2 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt @@ -415,8 +415,8 @@ class PassCodeActivity : AppCompatActivity(), NumberKeyboardListener, EnableBiom finish() } - private fun getPasscodeAction(action: String?): PasscodeAction { - return when (action) { + private fun getPasscodeAction(action: String?): PasscodeAction = + when (action) { ACTION_REMOVE -> { PasscodeAction.REMOVE } @@ -429,7 +429,6 @@ class PassCodeActivity : AppCompatActivity(), NumberKeyboardListener, EnableBiom PasscodeAction.CHECK } } - } override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean = when (keyCode) { diff --git a/owncloudApp/src/main/java/com/owncloud/android/providers/FileContentProvider.kt b/owncloudApp/src/main/java/com/owncloud/android/providers/FileContentProvider.kt index e06575660da..3a9c2a88f12 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/providers/FileContentProvider.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/providers/FileContentProvider.kt @@ -193,8 +193,8 @@ class FileContentProvider(val executors: Executors = Executors()) : ContentProvi return newUri } - private fun insert(db: SQLiteDatabase, uri: Uri, values: ContentValues?): Uri { - return when (uriMatcher.match(uri)) { + private fun insert(db: SQLiteDatabase, uri: Uri, values: ContentValues?): Uri = + when (uriMatcher.match(uri)) { ROOT_DIRECTORY, SINGLE_FILE -> { val remotePath = values?.getAsString(ProviderTableMeta.FILE_PATH) val accountName = values?.getAsString(ProviderTableMeta.FILE_ACCOUNT_OWNER) @@ -211,7 +211,7 @@ class FileContentProvider(val executors: Executors = Executors()) : ContentProvi val doubleCheck = query(uri, projection, where, whereArgs, null) // ugly patch; serious refactorization is needed to reduce work in // FileDataStorageManager and bring it to FileContentProvider - return if (!doubleCheck.moveToFirst()) { + if (!doubleCheck.moveToFirst()) { doubleCheck.close() val fileId = db.insert(ProviderTableMeta.FILE_TABLE_NAME, null, values) if (fileId <= 0) throw SQLException("ERROR $uri") @@ -270,8 +270,6 @@ class FileContentProvider(val executors: Executors = Executors()) : ContentProvi else -> throw IllegalArgumentException("Unknown uri id: $uri") } - } - override fun onCreate(): Boolean { dbHelper = DataBaseHelper(context) // This sentence is for opening the database, which is necessary to perform the migration correctly to DB version 38 diff --git a/owncloudApp/src/main/java/com/owncloud/android/usecases/transfers/downloads/DownloadFileUseCase.kt b/owncloudApp/src/main/java/com/owncloud/android/usecases/transfers/downloads/DownloadFileUseCase.kt index 56c40788046..9d9633cbda5 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/usecases/transfers/downloads/DownloadFileUseCase.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/usecases/transfers/downloads/DownloadFileUseCase.kt @@ -50,12 +50,12 @@ class DownloadFileUseCase( val ocFile = params.file val accountName = params.accountName - return if (ocFile.id == null) { - null - } else if (isDownloadAlreadyEnqueued(accountName, ocFile)) { - null - } else { - enqueueNewDownload(ocFile, accountName) + return ocFile.id?.let { + if (isDownloadAlreadyEnqueued(accountName, ocFile)) { + null + } else { + enqueueNewDownload(ocFile, accountName) + } } } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/MoveRemoteFileOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/MoveRemoteFileOperation.kt index 5e86e5e0412..50647414b6b 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/MoveRemoteFileOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/MoveRemoteFileOperation.kt @@ -63,8 +63,8 @@ open class MoveRemoteFileOperation( * * @param client Client object to communicate with the remote ownCloud server. */ - override fun run(client: OwnCloudClient): RemoteOperationResult { - return if (targetRemotePath == sourceRemotePath) { + override fun run(client: OwnCloudClient): RemoteOperationResult = + if (targetRemotePath == sourceRemotePath) { // nothing to do! RemoteOperationResult(ResultCode.OK) } else if (targetRemotePath.startsWith(sourceRemotePath)) { @@ -115,7 +115,6 @@ open class MoveRemoteFileOperation( } result } - } /** * For standard moves, we will use [OwnCloudClient.getUserFilesWebDavUri]. diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/StatusRequester.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/StatusRequester.kt index a54306ab124..730c85b4c8f 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/StatusRequester.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/StatusRequester.kt @@ -49,11 +49,11 @@ internal class StatusRequester { (baseUrl.startsWith(HTTPS_SCHEME) && !redirectedUrl.startsWith(HTTPS_SCHEME)) - fun updateLocationWithRedirectPath(oldLocation: String, redirectedLocation: String): String { + fun updateLocationWithRedirectPath(oldLocation: String, redirectedLocation: String): String = /** Redirection with different endpoint. * When asking for server.com/status.php and redirected to different.one/, we need to ask different.one/status.php */ - return if (redirectedLocation.endsWith('/')) { + if (redirectedLocation.endsWith('/')) { redirectedLocation.trimEnd('/') + OwnCloudClient.STATUS_PATH } else if (!redirectedLocation.startsWith("/")) { redirectedLocation @@ -61,7 +61,6 @@ internal class StatusRequester { val oldLocationURL = URL(oldLocation) URL(oldLocationURL.protocol, oldLocationURL.host, oldLocationURL.port, redirectedLocation).toString() } - } private fun getGetMethod(url: String): GetMethod = GetMethod(URL(url)).apply { From 472ac64da3e387d29ea74f8333fb097647729613 Mon Sep 17 00:00:00 2001 From: joragua Date: Thu, 23 Jan 2025 09:30:44 +0100 Subject: [PATCH 47/74] refactor: removed not implemented declarations (TODO functions) --- .../presentation/files/details/FileDetailsFragment.kt | 8 ++++---- .../presentation/files/filelist/MainFileListViewModel.kt | 3 ++- .../owncloud/android/ui/activity/FileDisplayActivity.kt | 4 ++-- .../datasources/implementation/OCLocalFileDataSource.kt | 2 +- 4 files changed, 9 insertions(+), 8 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/details/FileDetailsFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/details/FileDetailsFragment.kt index b5ca2e500b5..17131a69291 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/details/FileDetailsFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/details/FileDetailsFragment.kt @@ -585,11 +585,11 @@ class FileDetailsFragment : FileFragment() { } override fun updateViewForSyncInProgress() { - TODO("Not yet implemented") + // Not yet implemented } override fun updateViewForSyncOff() { - TODO("Not yet implemented") + // Not yet implemented } override fun onFileMetadataChanged(updatedFile: OCFile?) { @@ -597,11 +597,11 @@ class FileDetailsFragment : FileFragment() { } override fun onFileMetadataChanged() { - TODO("Not yet implemented") + // Not yet implemented } override fun onFileContentChanged() { - TODO("Not yet implemented") + // Not yet implemented } companion object { diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListViewModel.kt index c2dcb0924b3..88d24cdb360 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListViewModel.kt @@ -67,6 +67,7 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update @@ -368,7 +369,7 @@ class MainFileListViewModel( FileListOption.ALL_FILES -> retrieveFlowForAllFiles(currentFolderDisplayed, currentFolderDisplayed.owner) FileListOption.SHARED_BY_LINK -> retrieveFlowForShareByLink(currentFolderDisplayed, currentFolderDisplayed.owner) FileListOption.AV_OFFLINE -> retrieveFlowForAvailableOffline(currentFolderDisplayed, currentFolderDisplayed.owner) - FileListOption.SPACES_LIST -> TODO() + FileListOption.SPACES_LIST -> flow {} }.toFileListUiState( currentFolderDisplayed, fileListOption, diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt index ff97ffe1cf9..58a76883bf5 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt @@ -1351,8 +1351,8 @@ class FileDisplayActivity : FileActivity(), } is SynchronizeFileUseCase.SyncType.UploadEnqueued -> showSnackMessage(getString(R.string.upload_enqueued_msg)) - - null -> TODO() + null -> { // Nothing to do + } } } diff --git a/owncloudData/src/main/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSource.kt b/owncloudData/src/main/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSource.kt index 0bfd831c9ae..cd67af46e56 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSource.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSource.kt @@ -209,7 +209,7 @@ class OCLocalFileDataSource( } override fun saveUploadWorkerUuid(fileId: Long, workerUuid: UUID) { - TODO("Not yet implemented") + // Not yet implemented } override fun saveDownloadWorkerUuid(fileId: Long, workerUuid: UUID) { From 4e475fe606870e3bc64506c64672abc1e08fa26f Mon Sep 17 00:00:00 2001 From: joragua Date: Thu, 23 Jan 2025 14:33:21 +0100 Subject: [PATCH 48/74] style: modified some comments and replaced `flow{}` by `flowOf()` --- .../owncloud/android/datamodel/FileDataStorageManager.kt | 6 +++--- .../presentation/files/filelist/MainFileListViewModel.kt | 4 ++-- .../com/owncloud/android/ui/activity/FileDisplayActivity.kt | 3 +-- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt b/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt index 673dd687bfa..a81faa9757c 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt @@ -80,7 +80,7 @@ class FileDataStorageManager( result } - // To do: New_arch: Remove this and call usecase inside FilesViewModel + // To do: New_arch. Remove this and call usecase inside FilesViewModel fun getFileById(id: Long): OCFile? = runBlocking(CoroutinesDispatcherProvider().io) { val getFileByIdUseCase: GetFileByIdUseCase by inject() @@ -100,7 +100,7 @@ class FileDataStorageManager( listOf() } - // New_arch: Remove this and call usecase inside FilesViewModel + // To do: New_arch. Remove this and call usecase inside FilesViewModel fun getFolderImages(folder: OCFile?): List = runBlocking(CoroutinesDispatcherProvider().io) { val getFolderImagesUseCase: GetFolderImagesUseCase by inject() @@ -111,7 +111,7 @@ class FileDataStorageManager( result ?: listOf() } - // New_arch: Remove this and call usecase inside FilesViewModel + // To do: New_arch. Remove this and call usecase inside FilesViewModel private fun getFolderContent(parentId: Long): List = runBlocking(CoroutinesDispatcherProvider().io) { val getFolderContentUseCase: GetFolderContentUseCase by inject() diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListViewModel.kt index 88d24cdb360..c484a7ac4b4 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListViewModel.kt @@ -67,7 +67,7 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.flatMapLatest -import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update @@ -369,7 +369,7 @@ class MainFileListViewModel( FileListOption.ALL_FILES -> retrieveFlowForAllFiles(currentFolderDisplayed, currentFolderDisplayed.owner) FileListOption.SHARED_BY_LINK -> retrieveFlowForShareByLink(currentFolderDisplayed, currentFolderDisplayed.owner) FileListOption.AV_OFFLINE -> retrieveFlowForAvailableOffline(currentFolderDisplayed, currentFolderDisplayed.owner) - FileListOption.SPACES_LIST -> flow {} + FileListOption.SPACES_LIST -> flowOf() }.toFileListUiState( currentFolderDisplayed, fileListOption, diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt index 58a76883bf5..3ae2e34bb9f 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt @@ -1351,8 +1351,7 @@ class FileDisplayActivity : FileActivity(), } is SynchronizeFileUseCase.SyncType.UploadEnqueued -> showSnackMessage(getString(R.string.upload_enqueued_msg)) - null -> { // Nothing to do - } + null -> { /* Nothing to do */ } } } From 95a4c95969a199dc388ad899e289805d8aa0357b Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Fri, 24 Jan 2025 09:28:41 +0100 Subject: [PATCH 49/74] style: added braces in multi-line loops --- .../presentation/viewmodels/security/PassCodeViewModelTest.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/security/PassCodeViewModelTest.kt b/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/security/PassCodeViewModelTest.kt index d418831799a..be1210bba39 100644 --- a/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/security/PassCodeViewModelTest.kt +++ b/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/security/PassCodeViewModelTest.kt @@ -69,8 +69,9 @@ class PassCodeViewModelTest : ViewModelTest() { ) { every { contextProvider.getInt(R.integer.passcode_digits) } returns passcodeDigits //getNumberOfPassCodeDigits() every { preferencesProvider.getString(PREFERENCE_PASSCODE, any()) } returns passcode //getPassCode() - for (i in 0..4) + for (i in 0..4) { every { preferencesProvider.getString(PREFERENCE_PASSCODE_D + i, null) } returns passcodeD //loadPinFromOldFormatIfPossible() + } every { preferencesProvider.getInt(PREFERENCE_LOCK_ATTEMPTS, any()) } returns lockAttempts //getNumberOfAttempts() every { preferencesProvider.getLong(PREFERENCE_LAST_UNLOCK_ATTEMPT_TIMESTAMP, any()) } returns lastUnlockAttempt //getTimeToUnlockLeft() } From 7d1b1fbbe51bb9c70076bd5c6644a503282295bf Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Fri, 24 Jan 2025 10:40:08 +0100 Subject: [PATCH 50/74] style: ordered properly some classes (properties, constructors, methods and companion objects) --- .../authentication/AuthenticationViewModel.kt | 42 +-- .../authentication/oauth/OAuthViewModel.kt | 12 +- .../files/filelist/MainFileListFragment.kt | 246 +++++++++--------- .../files/filelist/SelectableAdapter.kt | 14 +- .../presentation/settings/SettingsFragment.kt | 3 +- .../presentation/sharing/ShareViewModel.kt | 38 +-- .../ui/dialog/FileAlreadyExistsDialog.kt | 55 ++-- .../ui/preview/PreviewImageActivity.kt | 14 +- .../lib/common/http/methods/HttpBaseMethod.kt | 16 +- .../common/http/methods/webdav/DavMethod.kt | 16 +- .../http/methods/webdav/PropfindMethod.kt | 10 +- .../files/DownloadRemoteFileOperation.kt | 4 +- .../implementation/OCLocalFileDataSource.kt | 20 +- .../OCLocalFolderBackupDataSource.kt | 27 +- .../OCLocalShareDataSourceTest.kt | 60 ++--- .../android/domain/files/model/OCFile.kt | 40 +-- 16 files changed, 307 insertions(+), 310 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/AuthenticationViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/AuthenticationViewModel.kt index 623cfb723e1..69840f95125 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/AuthenticationViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/AuthenticationViewModel.kt @@ -79,6 +79,27 @@ class AuthenticationViewModel( private val _legacyWebfingerHost = MediatorLiveData>>() val legacyWebfingerHost: LiveData>> = _legacyWebfingerHost + private val _serverInfo = MediatorLiveData>>() + val serverInfo: LiveData>> = _serverInfo + + private val _loginResult = MediatorLiveData>>() + val loginResult: LiveData>> = _loginResult + + private val _supportsOAuth2 = MediatorLiveData>>() + val supportsOAuth2: LiveData>> = _supportsOAuth2 + + private val _baseUrl = MediatorLiveData>>() + val baseUrl: LiveData>> = _baseUrl + + private val _registerClient = MediatorLiveData>>() + val registerClient: LiveData>> = _registerClient + + private val _requestToken = MediatorLiveData>>() + val requestToken: LiveData>> = _requestToken + + private val _accountDiscovery = MediatorLiveData>>() + val accountDiscovery: LiveData>> = _accountDiscovery + var launchedFromDeepLink = false fun getLegacyWebfingerHost( @@ -94,9 +115,6 @@ class AuthenticationViewModel( ) } - private val _serverInfo = MediatorLiveData>>() - val serverInfo: LiveData>> = _serverInfo - fun getServerInfo( serverUrl: String, creatingAccount: Boolean = false, @@ -115,9 +133,6 @@ class AuthenticationViewModel( ) } - private val _loginResult = MediatorLiveData>>() - val loginResult: LiveData>> = _loginResult - fun loginBasic( username: String, password: String, @@ -190,9 +205,6 @@ class AuthenticationViewModel( } } - private val _supportsOAuth2 = MediatorLiveData>>() - val supportsOAuth2: LiveData>> = _supportsOAuth2 - fun supportsOAuth2( accountName: String ) = runUseCaseWithResult( @@ -205,9 +217,6 @@ class AuthenticationViewModel( ) ) - private val _baseUrl = MediatorLiveData>>() - val baseUrl: LiveData>> = _baseUrl - fun getBaseUrl( accountName: String ) = runUseCaseWithResult( @@ -220,9 +229,6 @@ class AuthenticationViewModel( ) ) - private val _registerClient = MediatorLiveData>>() - val registerClient: LiveData>> = _registerClient - fun registerClient( registrationEndpoint: String ) { @@ -240,9 +246,6 @@ class AuthenticationViewModel( ) } - private val _requestToken = MediatorLiveData>>() - val requestToken: LiveData>> = _requestToken - fun requestToken( tokenRequest: TokenRequest ) = runUseCaseWithResult( @@ -253,9 +256,6 @@ class AuthenticationViewModel( useCaseParams = RequestTokenUseCase.Params(tokenRequest = tokenRequest) ) - private val _accountDiscovery = MediatorLiveData>>() - val accountDiscovery: LiveData>> = _accountDiscovery - fun discoverAccount(accountName: String, discoveryNeeded: Boolean = false) { Timber.d("Account Discovery for account: $accountName needed: $discoveryNeeded") if (!discoveryNeeded) { diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/oauth/OAuthViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/oauth/OAuthViewModel.kt index 1a42b47f18c..4da984931df 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/oauth/OAuthViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/oauth/OAuthViewModel.kt @@ -49,6 +49,12 @@ class OAuthViewModel( private val _oidcDiscovery = MediatorLiveData>>() val oidcDiscovery: LiveData>> = _oidcDiscovery + private val _registerClient = MediatorLiveData>>() + val registerClient: LiveData>> = _registerClient + + private val _requestToken = MediatorLiveData>>() + val requestToken: LiveData>> = _requestToken + fun getOIDCServerConfiguration( serverUrl: String ) = runUseCaseWithResult( @@ -59,9 +65,6 @@ class OAuthViewModel( useCaseParams = OIDCDiscoveryUseCase.Params(baseUrl = serverUrl) ) - private val _registerClient = MediatorLiveData>>() - val registerClient: LiveData>> = _registerClient - fun registerClient( registrationEndpoint: String ) { @@ -79,9 +82,6 @@ class OAuthViewModel( ) } - private val _requestToken = MediatorLiveData>>() - val requestToken: LiveData>> = _requestToken - fun requestToken( tokenRequest: TokenRequest ) = runUseCaseWithResult( diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt index b09c371b4a1..26dd4d451ec 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt @@ -189,6 +189,129 @@ class MainFileListFragment : Fragment(), private var succeededTransfers: List? = null private var numberOfUploadsRefreshed: Int = 0 + private val actionModeCallback: ActionMode.Callback = object : ActionMode.Callback { + + override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean { + setDrawerStatus(enabled = false) + actionMode = mode + + requireActivity().findViewById(R.id.owncloud_app_bar).isFocusableInTouchMode = false + + val inflater = requireActivity().menuInflater + inflater.inflate(R.menu.file_actions_menu, menu) + this@MainFileListFragment.menu = menu + + mode?.invalidate() + + // Set gray color + val window = activity?.window + statusBarColor = window?.statusBarColor ?: -1 + + // Hide FAB in multi selection mode + toggleFabVisibility(false) + fileActions?.setBottomBarVisibility(false) + + // Hide sort options view in multi-selection mode + binding.optionsLayout.visibility = View.GONE + + return true + } + + /** + * Updates available action in menu depending on current selection. + */ + override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean { + val checkedFilesWithSyncInfo = fileListAdapter.getCheckedItems() + val checkedCount = checkedFilesWithSyncInfo.size + val title = resources.getQuantityString( + R.plurals.items_selected_count, + checkedCount, + checkedCount + ) + mode?.title = title + + checkedFiles = checkedFilesWithSyncInfo.map { it.file } + + val checkedFilesSync = checkedFilesWithSyncInfo.map { + OCFileSyncInfo( + fileId = it.file.id!!, + uploadWorkerUuid = it.uploadWorkerUuid, + downloadWorkerUuid = it.downloadWorkerUuid, + isSynchronizing = it.isSynchronizing + ) + } + + val displaySelectAll = checkedCount != fileListAdapter.itemCount - 1 // -1 because one of them is the footer :S + mainFileListViewModel.filterMenuOptions( + checkedFiles, checkedFilesSync, + displaySelectAll, isMultiselection = true + ) + + if (checkedFiles.size == 1) { + mainFileListViewModel.getAppRegistryForMimeType(checkedFiles.first().mimeType, isMultiselection = true) + } else { + menu?.let { + openInWebProviders.forEach { (_, menuItemId) -> + it.removeItem(menuItemId) + } + openInWebProviders = emptyMap() + } + } + setRolesAccessibilityToMenuItems() + + return true + } + + private fun setRolesAccessibilityToMenuItems() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + val roleAccessibilityDescription = getString(R.string.button_role_accessibility) + menu?.apply { + findItem(R.id.file_action_select_all)?.contentDescription = + "${getString(R.string.actionbar_select_all)} $roleAccessibilityDescription" + findItem(R.id.action_select_inverse)?.contentDescription = + "${getString(R.string.actionbar_select_inverse)} $roleAccessibilityDescription" + findItem(R.id.action_open_file_with)?.contentDescription = + "${getString(R.string.actionbar_open_with)} $roleAccessibilityDescription" + findItem(R.id.action_rename_file)?.contentDescription = "${getString(R.string.common_rename)} $roleAccessibilityDescription" + findItem(R.id.action_move)?.contentDescription = "${getString(R.string.actionbar_move)} $roleAccessibilityDescription" + findItem(R.id.action_copy)?.contentDescription = "${getString(R.string.copy)} $roleAccessibilityDescription" + findItem(R.id.action_send_file)?.contentDescription = + "${getString(R.string.actionbar_send_file)} $roleAccessibilityDescription" + findItem(R.id.action_set_available_offline)?.contentDescription = + "${getString(R.string.set_available_offline)} $roleAccessibilityDescription" + findItem(R.id.action_unset_available_offline)?.contentDescription = + "${getString(R.string.unset_available_offline)} $roleAccessibilityDescription" + findItem(R.id.action_see_details)?.contentDescription = + "${getString(R.string.actionbar_see_details)} $roleAccessibilityDescription" + findItem(R.id.action_remove_file)?.contentDescription = "${getString(R.string.common_remove)} $roleAccessibilityDescription" + } + } + } + + override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean = + onFileActionChosen(item?.itemId) + + override fun onDestroyActionMode(mode: ActionMode?) { + setDrawerStatus(enabled = true) + actionMode = null + + requireActivity().findViewById(R.id.owncloud_app_bar).isFocusableInTouchMode = true + + // reset to previous color + requireActivity().window.statusBarColor = statusBarColor!! + + // show or hide FAB on multi selection mode exit + showOrHideFab(mainFileListViewModel.fileListOption.value, mainFileListViewModel.currentFolderDisplayed.value) + + fileActions?.setBottomBarVisibility(true) + + // Show sort options view when multi-selection mode finish + binding.optionsLayout.visibility = View.VISIBLE + + fileListAdapter.clearSelection() + } + } + override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? @@ -1441,129 +1564,6 @@ class MainFileListFragment : Fragment(), ) } - private val actionModeCallback: ActionMode.Callback = object : ActionMode.Callback { - - override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean { - setDrawerStatus(enabled = false) - actionMode = mode - - requireActivity().findViewById(R.id.owncloud_app_bar).isFocusableInTouchMode = false - - val inflater = requireActivity().menuInflater - inflater.inflate(R.menu.file_actions_menu, menu) - this@MainFileListFragment.menu = menu - - mode?.invalidate() - - // Set gray color - val window = activity?.window - statusBarColor = window?.statusBarColor ?: -1 - - // Hide FAB in multi selection mode - toggleFabVisibility(false) - fileActions?.setBottomBarVisibility(false) - - // Hide sort options view in multi-selection mode - binding.optionsLayout.visibility = View.GONE - - return true - } - - /** - * Updates available action in menu depending on current selection. - */ - override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean { - val checkedFilesWithSyncInfo = fileListAdapter.getCheckedItems() - val checkedCount = checkedFilesWithSyncInfo.size - val title = resources.getQuantityString( - R.plurals.items_selected_count, - checkedCount, - checkedCount - ) - mode?.title = title - - checkedFiles = checkedFilesWithSyncInfo.map { it.file } - - val checkedFilesSync = checkedFilesWithSyncInfo.map { - OCFileSyncInfo( - fileId = it.file.id!!, - uploadWorkerUuid = it.uploadWorkerUuid, - downloadWorkerUuid = it.downloadWorkerUuid, - isSynchronizing = it.isSynchronizing - ) - } - - val displaySelectAll = checkedCount != fileListAdapter.itemCount - 1 // -1 because one of them is the footer :S - mainFileListViewModel.filterMenuOptions( - checkedFiles, checkedFilesSync, - displaySelectAll, isMultiselection = true - ) - - if (checkedFiles.size == 1) { - mainFileListViewModel.getAppRegistryForMimeType(checkedFiles.first().mimeType, isMultiselection = true) - } else { - menu?.let { - openInWebProviders.forEach { (_, menuItemId) -> - it.removeItem(menuItemId) - } - openInWebProviders = emptyMap() - } - } - setRolesAccessibilityToMenuItems() - - return true - } - - private fun setRolesAccessibilityToMenuItems() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - val roleAccessibilityDescription = getString(R.string.button_role_accessibility) - menu?.apply { - findItem(R.id.file_action_select_all)?.contentDescription = - "${getString(R.string.actionbar_select_all)} $roleAccessibilityDescription" - findItem(R.id.action_select_inverse)?.contentDescription = - "${getString(R.string.actionbar_select_inverse)} $roleAccessibilityDescription" - findItem(R.id.action_open_file_with)?.contentDescription = - "${getString(R.string.actionbar_open_with)} $roleAccessibilityDescription" - findItem(R.id.action_rename_file)?.contentDescription = "${getString(R.string.common_rename)} $roleAccessibilityDescription" - findItem(R.id.action_move)?.contentDescription = "${getString(R.string.actionbar_move)} $roleAccessibilityDescription" - findItem(R.id.action_copy)?.contentDescription = "${getString(R.string.copy)} $roleAccessibilityDescription" - findItem(R.id.action_send_file)?.contentDescription = - "${getString(R.string.actionbar_send_file)} $roleAccessibilityDescription" - findItem(R.id.action_set_available_offline)?.contentDescription = - "${getString(R.string.set_available_offline)} $roleAccessibilityDescription" - findItem(R.id.action_unset_available_offline)?.contentDescription = - "${getString(R.string.unset_available_offline)} $roleAccessibilityDescription" - findItem(R.id.action_see_details)?.contentDescription = - "${getString(R.string.actionbar_see_details)} $roleAccessibilityDescription" - findItem(R.id.action_remove_file)?.contentDescription = "${getString(R.string.common_remove)} $roleAccessibilityDescription" - } - } - } - - override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean = - onFileActionChosen(item?.itemId) - - override fun onDestroyActionMode(mode: ActionMode?) { - setDrawerStatus(enabled = true) - actionMode = null - - requireActivity().findViewById(R.id.owncloud_app_bar).isFocusableInTouchMode = true - - // reset to previous color - requireActivity().window.statusBarColor = statusBarColor!! - - // show or hide FAB on multi selection mode exit - showOrHideFab(mainFileListViewModel.fileListOption.value, mainFileListViewModel.currentFolderDisplayed.value) - - fileActions?.setBottomBarVisibility(true) - - // Show sort options view when multi-selection mode finish - binding.optionsLayout.visibility = View.VISIBLE - - fileListAdapter.clearSelection() - } - } - private fun syncFiles(files: List) { for (file in files) { if (file.isFolder) { diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/SelectableAdapter.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/SelectableAdapter.kt index 9c669546cb2..985805599fa 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/SelectableAdapter.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/SelectableAdapter.kt @@ -27,6 +27,13 @@ abstract class SelectableAdapter : RecyclerView.Adapter() { private val selectedItems: SparseBooleanArray = SparseBooleanArray() + /** + * Count the selected items + * @return Selected items count + */ + val selectedItemCount: Int + get() = selectedItems.size() + /** * Indicates if the item at position position is selected * @param position Position of the item to check @@ -56,13 +63,6 @@ abstract class SelectableAdapter : notifyDataSetChanged() } - /** - * Count the selected items - * @return Selected items count - */ - val selectedItemCount: Int - get() = selectedItems.size() - /** * Indicates the list of selected items * @return List of selected items ids diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/SettingsFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/SettingsFragment.kt index 1ab50e482a3..b5471eec0d0 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/SettingsFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/SettingsFragment.kt @@ -131,12 +131,11 @@ class SettingsFragment : PreferenceFragmentCompat() { private const val SUBSECTION_VIDEO_UPLOADS = "video_uploads_subsection" private const val SUBSECTION_MORE = "more_subsection" private const val SUBSECTION_NOTIFICATIONS = "notifications_subsection" + private const val SUBSECTION_WHATSNEW = "whatsNew" // Remove preference with nullability check fun PreferenceScreen?.removePreferenceFromScreen(preference: Preference?) { preference?.let { this?.removePreference(it) } } - - private const val SUBSECTION_WHATSNEW = "whatsNew" } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareViewModel.kt index fdf76d0c22d..74f0e851d6b 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareViewModel.kt @@ -71,6 +71,26 @@ class ShareViewModel( private var capabilities: OCCapability? = null + private val _shareDeletionStatus = MediatorLiveData>>() + val shareDeletionStatus: LiveData>> = _shareDeletionStatus + + private val _privateShareCreationStatus = MediatorLiveData>>() + val privateShareCreationStatus: LiveData>> = _privateShareCreationStatus + + private val _privateShare = MediatorLiveData>>() + val privateShare: LiveData>> = _privateShare + + private val _privateShareEditionStatus = MediatorLiveData>>() + val privateShareEditionStatus: LiveData>> = _privateShareEditionStatus + + private val _publicShareCreationStatus = MediatorLiveData>>() + val publicShareCreationStatus: LiveData>> = _publicShareCreationStatus + + private val _publicShareEditionStatus = MediatorLiveData>>() + val publicShareEditionStatus: LiveData>> = _publicShareEditionStatus + + + init { _shares.addSource(sharesLiveData) { shares -> _shares.postValue(Event(UIResult.Success(shares))) @@ -98,9 +118,6 @@ class ShareViewModel( ) ) - private val _shareDeletionStatus = MediatorLiveData>>() - val shareDeletionStatus: LiveData>> = _shareDeletionStatus - fun deleteShare( remoteId: String ) = runUseCaseWithResult( @@ -121,9 +138,6 @@ class ShareViewModel( ******************************************* PRIVATE SHARES ******************************************* ******************************************************************************************************/ - private val _privateShareCreationStatus = MediatorLiveData>>() - val privateShareCreationStatus: LiveData>> = _privateShareCreationStatus - fun insertPrivateShare( filePath: String, shareType: ShareType?, @@ -145,9 +159,6 @@ class ShareViewModel( postSuccessWithData = false ) - private val _privateShare = MediatorLiveData>>() - val privateShare: LiveData>> = _privateShare - // Used to get a specific private share after updating it fun refreshPrivateShare( remoteId: String @@ -161,9 +172,6 @@ class ShareViewModel( } } - private val _privateShareEditionStatus = MediatorLiveData>>() - val privateShareEditionStatus: LiveData>> = _privateShareEditionStatus - fun updatePrivateShare( remoteId: String, permissions: Int, @@ -185,9 +193,6 @@ class ShareViewModel( ******************************************* PUBLIC SHARES ******************************************** ******************************************************************************************************/ - private val _publicShareCreationStatus = MediatorLiveData>>() - val publicShareCreationStatus: LiveData>> = _publicShareCreationStatus - fun insertPublicShare( filePath: String, permissions: Int, @@ -211,9 +216,6 @@ class ShareViewModel( postSuccessWithData = false ) - private val _publicShareEditionStatus = MediatorLiveData>>() - val publicShareEditionStatus: LiveData>> = _publicShareEditionStatus - fun updatePublicShare( remoteId: String, name: String, diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/dialog/FileAlreadyExistsDialog.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/dialog/FileAlreadyExistsDialog.kt index 56820ea0bb3..b47fba813d1 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/dialog/FileAlreadyExistsDialog.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/dialog/FileAlreadyExistsDialog.kt @@ -18,34 +18,6 @@ class FileAlreadyExistsDialog : DialogFragment() { fun onReplaceButtonClick() } - companion object { - var mListener: DialogButtonClickListener? = null - - const val TITLE_TEXT = "titleText" - const val DESCRIPTION_TEXT = "descriptionText" - const val CHECKBOX_TEXT = "checkboxText" - private const val CHECKBOX_VISIBLE = "checkboxVisible" - - fun newInstance( - titleText: String?, - descriptionText: String?, - checkboxText: String?, - checkboxVisible: Boolean, - dialogClickListener: DialogButtonClickListener? = null, - ): FileAlreadyExistsDialog { - val fragment = FileAlreadyExistsDialog() - val args = Bundle() - args.putString(TITLE_TEXT, titleText) - args.putString(DESCRIPTION_TEXT, descriptionText) - args.putString(CHECKBOX_TEXT, checkboxText) - args.putBoolean(CHECKBOX_VISIBLE, checkboxVisible) - - mListener = dialogClickListener - fragment.arguments = args - return fragment - } - } - fun setDialogButtonClickListener(listener: DialogButtonClickListener) = apply { mListener = listener } override fun onCreateView( @@ -79,4 +51,31 @@ class FileAlreadyExistsDialog : DialogFragment() { binding.dialogFileAlreadyExistsCheckbox.visibility = if (checkboxVisible == true) { View.VISIBLE } else { View.GONE } } + companion object { + var mListener: DialogButtonClickListener? = null + + const val TITLE_TEXT = "titleText" + const val DESCRIPTION_TEXT = "descriptionText" + const val CHECKBOX_TEXT = "checkboxText" + private const val CHECKBOX_VISIBLE = "checkboxVisible" + + fun newInstance( + titleText: String?, + descriptionText: String?, + checkboxText: String?, + checkboxVisible: Boolean, + dialogClickListener: DialogButtonClickListener? = null, + ): FileAlreadyExistsDialog { + val fragment = FileAlreadyExistsDialog() + val args = Bundle() + args.putString(TITLE_TEXT, titleText) + args.putString(DESCRIPTION_TEXT, descriptionText) + args.putString(CHECKBOX_TEXT, checkboxText) + args.putBoolean(CHECKBOX_VISIBLE, checkboxVisible) + + mListener = dialogClickListener + fragment.arguments = args + return fragment + } + } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.kt index bef837cf6f5..eed049e8e62 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.kt @@ -89,6 +89,13 @@ class PreviewImageActivity : FileActivity(), private var localBroadcastManager: LocalBroadcastManager? = null private var fullScreenAnchorView: View? = null + var mHideSystemUiHandler: Handler = object : Handler() { + override fun handleMessage(msg: Message) { + hideSystemUI(fullScreenAnchorView) + showActionBar(false) + } + } + override fun onCreate(savedInstanceState: Bundle?) { requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY) super.onCreate(savedInstanceState) @@ -229,13 +236,6 @@ class PreviewImageActivity : FileActivity(), delayedHide() } - var mHideSystemUiHandler: Handler = object : Handler() { - override fun handleMessage(msg: Message) { - hideSystemUI(fullScreenAnchorView) - showActionBar(false) - } - } - private fun delayedHide(delayMillis: Int = INITIAL_HIDE_DELAY) { mHideSystemUiHandler.removeMessages(0) mHideSystemUiHandler.sendEmptyMessageDelayed(0, delayMillis.toLong()) diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/HttpBaseMethod.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/HttpBaseMethod.kt index 9974412ea11..bb1fb2aa996 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/HttpBaseMethod.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/HttpBaseMethod.kt @@ -53,6 +53,14 @@ abstract class HttpBaseMethod constructor(url: URL) { var readTimeoutUnit: TimeUnit? = null private set + val statusCode: Int + get() = response.code + val statusMessage: String + get() = response.message + + open val isAborted: Boolean + get() = call?.isCanceled() ?: false + init { request = Request.Builder() .url(httpUrl) @@ -118,11 +126,6 @@ abstract class HttpBaseMethod constructor(url: URL) { /**************** *** Response *** ****************/ - val statusCode: Int - get() = response.code - - val statusMessage: String - get() = response.message // Headers open fun getResponseHeaders(): Headers? = @@ -172,9 +175,6 @@ abstract class HttpBaseMethod constructor(url: URL) { call?.cancel() } - open val isAborted: Boolean - get() = call?.isCanceled() ?: false - ////////////////////////////// // For override ////////////////////////////// diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/DavMethod.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/DavMethod.kt index 1f551d76a54..d3dec99e0d5 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/DavMethod.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/DavMethod.kt @@ -44,6 +44,13 @@ abstract class DavMethod protected constructor(url: URL) : HttpBaseMethod(url) { override lateinit var response: Response private var davResource: DavOCResource? = null + ////////////////////////////// + // Getter + ////////////////////////////// + + override val isAborted: Boolean + get() = davResource?.isCallAborted() ?: false + override fun abort() { davResource?.cancelCall() } @@ -84,13 +91,4 @@ abstract class DavMethod protected constructor(url: URL) : HttpBaseMethod(url) { } httpException.code } - - ////////////////////////////// - // Getter - ////////////////////////////// - - - override val isAborted: Boolean - get() = davResource?.isCallAborted() ?: false - } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/PropfindMethod.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/PropfindMethod.kt index 6f987f1dde7..67c4aeb334a 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/PropfindMethod.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/PropfindMethod.kt @@ -47,6 +47,11 @@ class PropfindMethod( var root: Response? private set + init { + members = arrayListOf() + this.root = null + } + @Throws(IOException::class, DavException::class) public override fun onDavExecute(davResource: DavOCResource): Int { davResource.propfind( @@ -65,9 +70,4 @@ class PropfindMethod( }) return statusCode } - - init { - members = arrayListOf() - this.root = null - } } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/DownloadRemoteFileOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/DownloadRemoteFileOperation.kt index 1c3890dd72a..68a19d7d18c 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/DownloadRemoteFileOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/DownloadRemoteFileOperation.kt @@ -62,6 +62,8 @@ class DownloadRemoteFileOperation( var etag: String = "" private set + private val tmpPath: String = localFolderPath + remotePath + override fun run(client: OwnCloudClient): RemoteOperationResult { // download will be performed to a temporal file, then moved to the final location val tmpFile = File(tmpPath) @@ -179,8 +181,6 @@ class DownloadRemoteFileOperation( private fun isSuccess(status: Int) = status == HttpConstants.HTTP_OK - private val tmpPath: String = localFolderPath + remotePath - fun addDatatransferProgressListener(listener: OnDatatransferProgressListener) { synchronized(dataTransferListeners) { dataTransferListeners.add(listener) } } diff --git a/owncloudData/src/main/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSource.kt b/owncloudData/src/main/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSource.kt index cd67af46e56..a43e55f1a6b 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSource.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/files/datasources/implementation/OCLocalFileDataSource.kt @@ -220,6 +220,16 @@ class OCLocalFileDataSource( fileDao.updateSyncStatusForFile(fileId, null) } + @VisibleForTesting + fun OCFileAndFileSync.toModel(): OCFileWithSyncInfo = + OCFileWithSyncInfo( + file = file.toModel(), + uploadWorkerUuid = fileSync?.uploadWorkerUuid, + downloadWorkerUuid = fileSync?.downloadWorkerUuid, + isSynchronizing = fileSync?.isSynchronizing == true, + space = space?.toModel(), + ) + companion object { @VisibleForTesting fun OCFileEntity.toModel(): OCFile = @@ -279,14 +289,4 @@ class OCLocalFileDataSource( spaceId = spaceId, ).apply { this@toEntity.id?.let { modelId -> this.id = modelId } } } - - @VisibleForTesting - fun OCFileAndFileSync.toModel(): OCFileWithSyncInfo = - OCFileWithSyncInfo( - file = file.toModel(), - uploadWorkerUuid = fileSync?.uploadWorkerUuid, - downloadWorkerUuid = fileSync?.downloadWorkerUuid, - isSynchronizing = fileSync?.isSynchronizing == true, - space = space?.toModel(), - ) } diff --git a/owncloudData/src/main/java/com/owncloud/android/data/folderbackup/datasources/implementation/OCLocalFolderBackupDataSource.kt b/owncloudData/src/main/java/com/owncloud/android/data/folderbackup/datasources/implementation/OCLocalFolderBackupDataSource.kt index 591a558c1d5..37780d2c92c 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/folderbackup/datasources/implementation/OCLocalFolderBackupDataSource.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/folderbackup/datasources/implementation/OCLocalFolderBackupDataSource.kt @@ -61,6 +61,19 @@ class OCLocalFolderBackupDataSource( ************************************************* Mappers **************************************************** **************************************************************************************************************/ + private fun FolderBackUpConfiguration.toEntity(): FolderBackUpEntity = + FolderBackUpEntity( + accountName = accountName, + behavior = behavior.toString(), + sourcePath = sourcePath, + uploadPath = uploadPath, + wifiOnly = wifiOnly, + chargingOnly = chargingOnly, + name = name, + lastSyncTimestamp = lastSyncTimestamp, + spaceId = spaceId, + ) + companion object { @VisibleForTesting fun FolderBackUpEntity.toModel() = @@ -76,18 +89,4 @@ class OCLocalFolderBackupDataSource( spaceId = spaceId, ) } - - - private fun FolderBackUpConfiguration.toEntity(): FolderBackUpEntity = - FolderBackUpEntity( - accountName = accountName, - behavior = behavior.toString(), - sourcePath = sourcePath, - uploadPath = uploadPath, - wifiOnly = wifiOnly, - chargingOnly = chargingOnly, - name = name, - lastSyncTimestamp = lastSyncTimestamp, - spaceId = spaceId, - ) } diff --git a/owncloudData/src/test/java/com/owncloud/android/data/sharing/shares/datasources/implementation/OCLocalShareDataSourceTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/sharing/shares/datasources/implementation/OCLocalShareDataSourceTest.kt index f3a80cb933c..7774138e47b 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/sharing/shares/datasources/implementation/OCLocalShareDataSourceTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/sharing/shares/datasources/implementation/OCLocalShareDataSourceTest.kt @@ -45,6 +45,36 @@ class OCLocalShareDataSourceTest { private lateinit var ocLocalSharesDataSource: OCLocalShareDataSource private val ocSharesDao = mockk(relaxUnitFun = true) + private val privateShares = listOf( + OC_PRIVATE_SHARE.copy( + path = "/Docs/doc1.doc", + shareWith = "username", + sharedWithDisplayName = "Sophie" + ).toEntity(), + OC_PRIVATE_SHARE.copy( + path = "/Docs/doc1.doc", + shareWith = "user.name", + sharedWithDisplayName = "Nicole" + ).toEntity() + ) + + private val privateShareTypes = listOf(ShareType.USER, ShareType.GROUP, ShareType.FEDERATED) + + private val publicShares = listOf( + OC_PUBLIC_SHARE.copy( + path = "/Photos/", + isFolder = true, + name = "Photos link", + shareLink = "http://server:port/s/1" + ).toEntity(), + OC_PUBLIC_SHARE.copy( + path = "/Photos/", + isFolder = true, + name = "Photos link 2", + shareLink = "http://server:port/s/2" + ).toEntity() + ) + @Rule @JvmField val instantExecutorRule = InstantTaskExecutorRule() @@ -62,21 +92,6 @@ class OCLocalShareDataSourceTest { ******************************************* PRIVATE SHARES ******************************************* ******************************************************************************************************/ - private val privateShares = listOf( - OC_PRIVATE_SHARE.copy( - path = "/Docs/doc1.doc", - shareWith = "username", - sharedWithDisplayName = "Sophie" - ).toEntity(), - OC_PRIVATE_SHARE.copy( - path = "/Docs/doc1.doc", - shareWith = "user.name", - sharedWithDisplayName = "Nicole" - ).toEntity() - ) - - private val privateShareTypes = listOf(ShareType.USER, ShareType.GROUP, ShareType.FEDERATED) - @Test fun `getSharesAsLiveData returns a LiveData of a list of OCShare when read local private shares`() { val privateSharesAsLiveData: MutableLiveData> = MutableLiveData() @@ -182,21 +197,6 @@ class OCLocalShareDataSourceTest { ******************************************* PUBLIC SHARES ******************************************** ******************************************************************************************************/ - private val publicShares = listOf( - OC_PUBLIC_SHARE.copy( - path = "/Photos/", - isFolder = true, - name = "Photos link", - shareLink = "http://server:port/s/1" - ).toEntity(), - OC_PUBLIC_SHARE.copy( - path = "/Photos/", - isFolder = true, - name = "Photos link 2", - shareLink = "http://server:port/s/2" - ).toEntity() - ) - @Test fun `getSharesAsLiveData returns a LiveData of a list of OCShare when read local public shares`() { val publicSharesAsLiveData: MutableLiveData> = MutableLiveData() diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/files/model/OCFile.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/files/model/OCFile.kt index 32c92a4d32e..22a20c9da13 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/files/model/OCFile.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/files/model/OCFile.kt @@ -63,17 +63,6 @@ data class OCFile( val fileName: String get() = File(remotePath).name.let { it.ifBlank { ROOT_PATH } } - @Deprecated("Do not use this constructor. Remove it as soon as possible") - constructor(remotePath: String, mimeType: String, parentId: Long?, owner: String, spaceId: String? = null) : this( - remotePath = remotePath, - mimeType = mimeType, - parentId = parentId, - owner = owner, - spaceId = spaceId, - modificationTimestamp = 0, - length = 0 - ) - /** * Use this to find out if this file is a folder. * @@ -148,15 +137,6 @@ data class OCFile( val hasResharePermission: Boolean get() = permissions?.contains(char = 'R', ignoreCase = true) ?: false - /** - * get remote path of parent file - * @return remote path - */ - fun getParentRemotePath(): String { - val parentPath: String = File(remotePath).parent ?: throw IllegalArgumentException("Parent path is null") - return if (parentPath.endsWith("$PATH_SEPARATOR")) parentPath else "$parentPath$PATH_SEPARATOR" - } - /** * Use this to check if this file is available locally * @@ -199,6 +179,26 @@ data class OCFile( File(storagePath).lastModified() } ?: 0 + @Deprecated("Do not use this constructor. Remove it as soon as possible") + constructor(remotePath: String, mimeType: String, parentId: Long?, owner: String, spaceId: String? = null) : this( + remotePath = remotePath, + mimeType = mimeType, + parentId = parentId, + owner = owner, + spaceId = spaceId, + modificationTimestamp = 0, + length = 0 + ) + + /** + * get remote path of parent file + * @return remote path + */ + fun getParentRemotePath(): String { + val parentPath: String = File(remotePath).parent ?: throw IllegalArgumentException("Parent path is null") + return if (parentPath.endsWith("$PATH_SEPARATOR")) parentPath else "$parentPath$PATH_SEPARATOR" + } + fun copyLocalPropertiesFrom(sourceFile: OCFile) { parentId = sourceFile.parentId id = sourceFile.id From 10d1ff79ee09db17f1013a196d65429caa1c34bf Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Mon, 27 Jan 2025 11:18:16 +0100 Subject: [PATCH 51/74] refactor: renamed files so that they match the single top-level declarations they contain --- .../presentation/security/{SecurityUtils.kt => LockTimeout.kt} | 0 .../advanced/{AdvancedSettingsUtils.kt => RemoveLocalFiles.kt} | 0 .../java/com/owncloud/android/data/migrations/Migration_34.kt | 3 +++ 3 files changed, 3 insertions(+) rename owncloudApp/src/main/java/com/owncloud/android/presentation/security/{SecurityUtils.kt => LockTimeout.kt} (100%) rename owncloudApp/src/main/java/com/owncloud/android/presentation/settings/advanced/{AdvancedSettingsUtils.kt => RemoveLocalFiles.kt} (100%) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/SecurityUtils.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/LockTimeout.kt similarity index 100% rename from owncloudApp/src/main/java/com/owncloud/android/presentation/security/SecurityUtils.kt rename to owncloudApp/src/main/java/com/owncloud/android/presentation/security/LockTimeout.kt diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/advanced/AdvancedSettingsUtils.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/advanced/RemoveLocalFiles.kt similarity index 100% rename from owncloudApp/src/main/java/com/owncloud/android/presentation/settings/advanced/AdvancedSettingsUtils.kt rename to owncloudApp/src/main/java/com/owncloud/android/presentation/settings/advanced/RemoveLocalFiles.kt diff --git a/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_34.kt b/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_34.kt index bc31fda7477..d239fabd179 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_34.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/migrations/Migration_34.kt @@ -17,6 +17,9 @@ * along with this program. If not, see . * */ + +@file:Suppress("MatchingDeclarationName") + package com.owncloud.android.data.migrations import androidx.room.migration.Migration From fac94c6dd047ebd782e38df90286381e5bdab2d7 Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Mon, 27 Jan 2025 11:20:13 +0100 Subject: [PATCH 52/74] refactor: added explicit Locale not to rely on default Locale, which can lead to potential bugs --- .../presentation/security/passcode/PassCodeViewModel.kt | 4 +++- .../owncloud/android/lib/common/utils/OCFileLoggingTree.kt | 3 +++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeViewModel.kt index 221dd658285..8ded0c2a387 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeViewModel.kt @@ -33,6 +33,7 @@ import com.owncloud.android.presentation.security.PREFERENCE_LAST_UNLOCK_TIMESTA import com.owncloud.android.presentation.security.biometric.BiometricActivity import com.owncloud.android.presentation.settings.security.SettingsSecurityFragment.Companion.PREFERENCE_LOCK_ATTEMPTS import com.owncloud.android.providers.ContextProvider +import java.util.Locale import java.util.concurrent.TimeUnit import kotlin.math.max import kotlin.math.pow @@ -209,7 +210,8 @@ class PassCodeViewModel( else TimeUnit.MINUTES.convert(millisUntilFinished.plus(1000), TimeUnit.MILLISECONDS) val seconds = TimeUnit.SECONDS.convert(millisUntilFinished.plus(1000), TimeUnit.MILLISECONDS).rem(60) val timeString = - if (hours > 0) String.format("%02d:%02d:%02d", hours, minutes, seconds) else String.format("%02d:%02d", minutes, seconds) + if (hours > 0) String.format(Locale.US, "%02d:%02d:%02d", hours, minutes, seconds) + else String.format(Locale.US, "%02d:%02d", minutes, seconds) _getTimeToUnlockLiveData.postValue(Event(timeString)) } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/utils/OCFileLoggingTree.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/utils/OCFileLoggingTree.kt index 03b95ef0b60..a4c0a0cb91c 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/utils/OCFileLoggingTree.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/utils/OCFileLoggingTree.kt @@ -90,6 +90,7 @@ class OCFileLoggingTree( override fun createStackElementTag(element: StackTraceElement): String { if (newLogcat) { method = String.format( + Locale.US, "%s.%s()", // method is fully qualified only when class differs on filename otherwise it can be cropped on long lambda expressions super.createStackElementTag(element)?.replaceFirst(element.fileName.takeWhile { it != '.' }, ""), @@ -97,6 +98,7 @@ class OCFileLoggingTree( ) codeIdentifier = String.format( + Locale.US, "(%s:%d)", element.fileName, element.lineNumber // format ensures line numbers have at least 3 places to align consecutive output from the same file @@ -104,6 +106,7 @@ class OCFileLoggingTree( return "(${element.fileName}:${element.lineNumber})" } else return String.format( + Locale.US, "(%s:%d) %s.%s()", element.fileName, element.lineNumber, // format ensures line numbers have at least 3 places to align consecutive output from the same file From 91288d16d582b645bab09b08de2b339844058958 Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Mon, 27 Jan 2025 15:08:50 +0100 Subject: [PATCH 53/74] refactor: avoid spread operators --- .../roommigrations/MigrationToDB29Test.kt | 43 +++++++++++++- .../roommigrations/MigrationToDB30Test.kt | 58 +++++++++++++++++-- .../roommigrations/MigrationToDB33Test.kt | 28 ++++++++- .../roommigrations/MigrationToDB35Test.kt | 28 ++++++++- .../roommigrations/MigrationToDB36Test.kt | 28 ++++++++- .../owncloud/android/data/OwncloudDatabase.kt | 29 +++++----- 6 files changed, 185 insertions(+), 29 deletions(-) diff --git a/owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB29Test.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB29Test.kt index 5605ee2bee6..66ee3be1289 100644 --- a/owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB29Test.kt +++ b/owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB29Test.kt @@ -23,9 +23,20 @@ package com.owncloud.android.data.roommigrations import android.database.sqlite.SQLiteDatabase import androidx.sqlite.db.SupportSQLiteDatabase import androidx.test.filters.SmallTest -import com.owncloud.android.data.OwncloudDatabase import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.OCSHARES_TABLE_NAME +import com.owncloud.android.data.migrations.MIGRATION_27_28 +import com.owncloud.android.data.migrations.MIGRATION_28_29 +import com.owncloud.android.data.migrations.MIGRATION_29_30 +import com.owncloud.android.data.migrations.MIGRATION_30_31 +import com.owncloud.android.data.migrations.MIGRATION_31_32 +import com.owncloud.android.data.migrations.MIGRATION_32_33 +import com.owncloud.android.data.migrations.MIGRATION_33_34 +import com.owncloud.android.data.migrations.MIGRATION_34_35 +import com.owncloud.android.data.migrations.MIGRATION_35_36 +import com.owncloud.android.data.migrations.MIGRATION_37_38 +import com.owncloud.android.data.migrations.MIGRATION_41_42 +import com.owncloud.android.data.migrations.MIGRATION_42_43 import com.owncloud.android.testutil.OC_SHARE import org.junit.Assert.assertEquals import org.junit.Test @@ -43,7 +54,20 @@ class MigrationToDB29Test : MigrationTest() { currentVersion = DB_VERSION_29, insertData = { database -> insertDataToTest(database) }, validateMigration = { database -> validateMigrationTo29(database) }, - listOfMigrations = OwncloudDatabase.ALL_MIGRATIONS + listOfMigrations = arrayOf( + MIGRATION_27_28, + MIGRATION_28_29, + MIGRATION_29_30, + MIGRATION_30_31, + MIGRATION_31_32, + MIGRATION_32_33, + MIGRATION_33_34, + MIGRATION_34_35, + MIGRATION_35_36, + MIGRATION_37_38, + MIGRATION_41_42, + MIGRATION_42_43, + ) ) } @@ -54,7 +78,20 @@ class MigrationToDB29Test : MigrationTest() { currentVersion = DB_VERSION_29, insertData = { database -> insertDataToTest(database) }, validateMigration = { database -> validateMigrationTo29(database) }, - listOfMigrations = OwncloudDatabase.ALL_MIGRATIONS + listOfMigrations = arrayOf( + MIGRATION_27_28, + MIGRATION_28_29, + MIGRATION_29_30, + MIGRATION_30_31, + MIGRATION_31_32, + MIGRATION_32_33, + MIGRATION_33_34, + MIGRATION_34_35, + MIGRATION_35_36, + MIGRATION_37_38, + MIGRATION_41_42, + MIGRATION_42_43, + ) ) } diff --git a/owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB30Test.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB30Test.kt index b72ec3be08d..b266457acd0 100644 --- a/owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB30Test.kt +++ b/owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB30Test.kt @@ -24,7 +24,6 @@ import android.content.ContentValues import android.database.sqlite.SQLiteDatabase import androidx.sqlite.db.SupportSQLiteDatabase import androidx.test.filters.SmallTest -import com.owncloud.android.data.OwncloudDatabase import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_CORE_POLLINTERVAL import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_DAV_CHUNKING_VERSION @@ -33,6 +32,18 @@ import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_TAB import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.LEGACY_CAPABILITIES_VERSION_MAYOR import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_VERSION_MICRO import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_VERSION_MINOR +import com.owncloud.android.data.migrations.MIGRATION_27_28 +import com.owncloud.android.data.migrations.MIGRATION_28_29 +import com.owncloud.android.data.migrations.MIGRATION_29_30 +import com.owncloud.android.data.migrations.MIGRATION_30_31 +import com.owncloud.android.data.migrations.MIGRATION_31_32 +import com.owncloud.android.data.migrations.MIGRATION_32_33 +import com.owncloud.android.data.migrations.MIGRATION_33_34 +import com.owncloud.android.data.migrations.MIGRATION_34_35 +import com.owncloud.android.data.migrations.MIGRATION_35_36 +import com.owncloud.android.data.migrations.MIGRATION_37_38 +import com.owncloud.android.data.migrations.MIGRATION_41_42 +import com.owncloud.android.data.migrations.MIGRATION_42_43 import com.owncloud.android.testutil.OC_CAPABILITY import org.junit.Assert.assertEquals import org.junit.Test @@ -50,7 +61,20 @@ class MigrationToDB30Test : MigrationTest() { currentVersion = DB_VERSION_30, insertData = { database -> insertDataToTest(database) }, validateMigration = { database -> validateMigrationTo30(database) }, - listOfMigrations = OwncloudDatabase.ALL_MIGRATIONS + listOfMigrations = arrayOf( + MIGRATION_27_28, + MIGRATION_28_29, + MIGRATION_29_30, + MIGRATION_30_31, + MIGRATION_31_32, + MIGRATION_32_33, + MIGRATION_33_34, + MIGRATION_34_35, + MIGRATION_35_36, + MIGRATION_37_38, + MIGRATION_41_42, + MIGRATION_42_43, + ) ) } @@ -61,7 +85,20 @@ class MigrationToDB30Test : MigrationTest() { currentVersion = DB_VERSION_30, insertData = { database -> insertDataToTest(database) }, validateMigration = { database -> validateMigrationTo30(database) }, - listOfMigrations = OwncloudDatabase.ALL_MIGRATIONS + listOfMigrations = arrayOf( + MIGRATION_27_28, + MIGRATION_28_29, + MIGRATION_29_30, + MIGRATION_30_31, + MIGRATION_31_32, + MIGRATION_32_33, + MIGRATION_33_34, + MIGRATION_34_35, + MIGRATION_35_36, + MIGRATION_37_38, + MIGRATION_41_42, + MIGRATION_42_43, + ) ) } @@ -72,7 +109,20 @@ class MigrationToDB30Test : MigrationTest() { currentVersion = DB_VERSION_30, insertData = { database -> insertDataToTest(database) }, validateMigration = { database -> validateMigrationTo30(database) }, - listOfMigrations = OwncloudDatabase.ALL_MIGRATIONS + listOfMigrations = arrayOf( + MIGRATION_27_28, + MIGRATION_28_29, + MIGRATION_29_30, + MIGRATION_30_31, + MIGRATION_31_32, + MIGRATION_32_33, + MIGRATION_33_34, + MIGRATION_34_35, + MIGRATION_35_36, + MIGRATION_37_38, + MIGRATION_41_42, + MIGRATION_42_43, + ) ) } diff --git a/owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB33Test.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB33Test.kt index 19a6c8d8fbc..b8b475c2769 100644 --- a/owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB33Test.kt +++ b/owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB33Test.kt @@ -22,8 +22,19 @@ package com.owncloud.android.data.roommigrations import androidx.sqlite.db.SupportSQLiteDatabase import androidx.test.filters.SmallTest -import com.owncloud.android.data.OwncloudDatabase import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.OCSHARES_TABLE_NAME +import com.owncloud.android.data.migrations.MIGRATION_27_28 +import com.owncloud.android.data.migrations.MIGRATION_28_29 +import com.owncloud.android.data.migrations.MIGRATION_29_30 +import com.owncloud.android.data.migrations.MIGRATION_30_31 +import com.owncloud.android.data.migrations.MIGRATION_31_32 +import com.owncloud.android.data.migrations.MIGRATION_32_33 +import com.owncloud.android.data.migrations.MIGRATION_33_34 +import com.owncloud.android.data.migrations.MIGRATION_34_35 +import com.owncloud.android.data.migrations.MIGRATION_35_36 +import com.owncloud.android.data.migrations.MIGRATION_37_38 +import com.owncloud.android.data.migrations.MIGRATION_41_42 +import com.owncloud.android.data.migrations.MIGRATION_42_43 import com.owncloud.android.testutil.OC_SHARE import org.junit.Assert.assertEquals import org.junit.Test @@ -41,7 +52,20 @@ class MigrationToDB33Test : MigrationTest() { currentVersion = DB_VERSION_33, insertData = { database -> insertDataToTest(database) }, validateMigration = { database -> validateMigrationTo33(database) }, - listOfMigrations = OwncloudDatabase.ALL_MIGRATIONS + listOfMigrations = arrayOf( + MIGRATION_27_28, + MIGRATION_28_29, + MIGRATION_29_30, + MIGRATION_30_31, + MIGRATION_31_32, + MIGRATION_32_33, + MIGRATION_33_34, + MIGRATION_34_35, + MIGRATION_35_36, + MIGRATION_37_38, + MIGRATION_41_42, + MIGRATION_42_43, + ) ) } diff --git a/owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB35Test.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB35Test.kt index 79ed539ae60..7ac33097818 100644 --- a/owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB35Test.kt +++ b/owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB35Test.kt @@ -22,8 +22,19 @@ package com.owncloud.android.data.roommigrations import androidx.sqlite.db.SupportSQLiteDatabase import androidx.test.filters.SmallTest -import com.owncloud.android.data.OwncloudDatabase import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.FOLDER_BACKUP_TABLE_NAME +import com.owncloud.android.data.migrations.MIGRATION_27_28 +import com.owncloud.android.data.migrations.MIGRATION_28_29 +import com.owncloud.android.data.migrations.MIGRATION_29_30 +import com.owncloud.android.data.migrations.MIGRATION_30_31 +import com.owncloud.android.data.migrations.MIGRATION_31_32 +import com.owncloud.android.data.migrations.MIGRATION_32_33 +import com.owncloud.android.data.migrations.MIGRATION_33_34 +import com.owncloud.android.data.migrations.MIGRATION_34_35 +import com.owncloud.android.data.migrations.MIGRATION_35_36 +import com.owncloud.android.data.migrations.MIGRATION_37_38 +import com.owncloud.android.data.migrations.MIGRATION_41_42 +import com.owncloud.android.data.migrations.MIGRATION_42_43 import com.owncloud.android.testutil.OC_BACKUP import org.junit.Assert import org.junit.Test @@ -38,7 +49,20 @@ class MigrationToDB35Test : MigrationTest() { currentVersion = DB_VERSION_35, insertData = { database -> insertDataToTest(database) }, validateMigration = { database -> validateMigrationTo35(database) }, - listOfMigrations = OwncloudDatabase.ALL_MIGRATIONS + listOfMigrations = arrayOf( + MIGRATION_27_28, + MIGRATION_28_29, + MIGRATION_29_30, + MIGRATION_30_31, + MIGRATION_31_32, + MIGRATION_32_33, + MIGRATION_33_34, + MIGRATION_34_35, + MIGRATION_35_36, + MIGRATION_37_38, + MIGRATION_41_42, + MIGRATION_42_43, + ) ) } diff --git a/owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB36Test.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB36Test.kt index 7e4fc0fb7e3..1e26d4afc00 100644 --- a/owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB36Test.kt +++ b/owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB36Test.kt @@ -22,8 +22,19 @@ package com.owncloud.android.data.roommigrations import androidx.sqlite.db.SupportSQLiteDatabase import androidx.test.filters.SmallTest -import com.owncloud.android.data.OwncloudDatabase import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME +import com.owncloud.android.data.migrations.MIGRATION_27_28 +import com.owncloud.android.data.migrations.MIGRATION_28_29 +import com.owncloud.android.data.migrations.MIGRATION_29_30 +import com.owncloud.android.data.migrations.MIGRATION_30_31 +import com.owncloud.android.data.migrations.MIGRATION_31_32 +import com.owncloud.android.data.migrations.MIGRATION_32_33 +import com.owncloud.android.data.migrations.MIGRATION_33_34 +import com.owncloud.android.data.migrations.MIGRATION_34_35 +import com.owncloud.android.data.migrations.MIGRATION_35_36 +import com.owncloud.android.data.migrations.MIGRATION_37_38 +import com.owncloud.android.data.migrations.MIGRATION_41_42 +import com.owncloud.android.data.migrations.MIGRATION_42_43 import com.owncloud.android.testutil.OC_CAPABILITY import org.junit.Assert import org.junit.Test @@ -38,7 +49,20 @@ class MigrationToDB36Test : MigrationTest() { currentVersion = DB_VERSION_36, insertData = { database -> insertDataToTest(database) }, validateMigration = { database -> validateMigrationTo36(database) }, - listOfMigrations = OwncloudDatabase.ALL_MIGRATIONS + listOfMigrations = arrayOf( + MIGRATION_27_28, + MIGRATION_28_29, + MIGRATION_29_30, + MIGRATION_30_31, + MIGRATION_31_32, + MIGRATION_32_33, + MIGRATION_33_34, + MIGRATION_34_35, + MIGRATION_35_36, + MIGRATION_37_38, + MIGRATION_41_42, + MIGRATION_42_43, + ) ) } diff --git a/owncloudData/src/main/java/com/owncloud/android/data/OwncloudDatabase.kt b/owncloudData/src/main/java/com/owncloud/android/data/OwncloudDatabase.kt index c264391e816..b67a8d8a0eb 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/OwncloudDatabase.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/OwncloudDatabase.kt @@ -100,21 +100,6 @@ abstract class OwncloudDatabase : RoomDatabase() { @Volatile private var INSTANCE: OwncloudDatabase? = null - val ALL_MIGRATIONS = arrayOf( - MIGRATION_27_28, - MIGRATION_28_29, - MIGRATION_29_30, - MIGRATION_30_31, - MIGRATION_31_32, - MIGRATION_32_33, - MIGRATION_33_34, - MIGRATION_34_35, - MIGRATION_35_36, - MIGRATION_37_38, - MIGRATION_41_42, - MIGRATION_42_43, - ) - fun getDatabase( context: Context ): OwncloudDatabase = @@ -126,7 +111,19 @@ abstract class OwncloudDatabase : RoomDatabase() { OwncloudDatabase::class.java, ProviderMeta.NEW_DB_NAME ) - .addMigrations(*ALL_MIGRATIONS) + .addMigrations( + MIGRATION_27_28, + MIGRATION_28_29, + MIGRATION_29_30, + MIGRATION_30_31, + MIGRATION_31_32, + MIGRATION_32_33, + MIGRATION_33_34, + MIGRATION_34_35, + MIGRATION_35_36, + MIGRATION_37_38, + MIGRATION_41_42, + MIGRATION_42_43) .build() INSTANCE = instance instance From 4a3d54fb22c07c992f92165694a74979da7e70e0 Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Tue, 28 Jan 2025 11:21:39 +0100 Subject: [PATCH 54/74] refactor: transform utility classes to objects --- .../authentication/LoginActivity.kt | 2 +- .../DocumentsProviderUtils.kt | 18 +-- .../security/passcode/PassCodeActivity.kt | 2 +- .../security/pattern/PatternActivity.kt | 2 +- .../security/SettingsSecurityFragment.kt | 2 +- .../owncloud/android/utils/RemoteFileUtils.kt | 138 +++++++++--------- .../workers/UploadFileFromContentUriWorker.kt | 2 +- .../workers/UploadFileFromFileSystemWorker.kt | 2 +- 8 files changed, 82 insertions(+), 86 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/LoginActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/LoginActivity.kt index 0c6cd7850cd..1c5e7da85f8 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/LoginActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/LoginActivity.kt @@ -73,7 +73,7 @@ import com.owncloud.android.presentation.authentication.AccountUtils.getAccounts import com.owncloud.android.presentation.authentication.AccountUtils.getUsernameOfAccount import com.owncloud.android.presentation.authentication.oauth.OAuthUtils import com.owncloud.android.presentation.common.UIResult -import com.owncloud.android.presentation.documentsprovider.DocumentsProviderUtils.Companion.notifyDocumentsProviderRoots +import com.owncloud.android.presentation.documentsprovider.DocumentsProviderUtils.notifyDocumentsProviderRoots import com.owncloud.android.presentation.security.LockType import com.owncloud.android.presentation.security.SecurityEnforced import com.owncloud.android.presentation.settings.SettingsActivity diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/documentsprovider/DocumentsProviderUtils.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/documentsprovider/DocumentsProviderUtils.kt index 073dcf68079..ff26f553e3e 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/documentsprovider/DocumentsProviderUtils.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/documentsprovider/DocumentsProviderUtils.kt @@ -23,15 +23,13 @@ import android.content.Context import android.provider.DocumentsContract import com.owncloud.android.R -class DocumentsProviderUtils { - companion object { - /** - * Notify Document Provider to refresh roots - */ - fun notifyDocumentsProviderRoots(context: Context) { - val authority = context.resources.getString(R.string.document_provider_authority) - val rootsUri = DocumentsContract.buildRootsUri(authority) - context.contentResolver.notifyChange(rootsUri, null) - } +object DocumentsProviderUtils { + /** + * Notify Document Provider to refresh roots + */ + fun notifyDocumentsProviderRoots(context: Context) { + val authority = context.resources.getString(R.string.document_provider_authority) + val rootsUri = DocumentsContract.buildRootsUri(authority) + context.contentResolver.notifyChange(rootsUri, null) } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt index e34cf0c42a2..b690437b01c 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt @@ -44,7 +44,7 @@ import com.owncloud.android.R import com.owncloud.android.databinding.PasscodelockBinding import com.owncloud.android.domain.utils.Event import com.owncloud.android.extensions.showBiometricDialog -import com.owncloud.android.presentation.documentsprovider.DocumentsProviderUtils.Companion.notifyDocumentsProviderRoots +import com.owncloud.android.presentation.documentsprovider.DocumentsProviderUtils.notifyDocumentsProviderRoots import com.owncloud.android.presentation.security.biometric.BiometricStatus import com.owncloud.android.presentation.security.biometric.BiometricViewModel import com.owncloud.android.presentation.security.biometric.EnableBiometrics diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/pattern/PatternActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/pattern/PatternActivity.kt index 3f8bfd0db1f..8b6b8b9dde6 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/pattern/PatternActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/pattern/PatternActivity.kt @@ -40,7 +40,7 @@ import com.owncloud.android.R import com.owncloud.android.data.providers.implementation.OCSharedPreferencesProvider import com.owncloud.android.databinding.ActivityPatternLockBinding import com.owncloud.android.extensions.showBiometricDialog -import com.owncloud.android.presentation.documentsprovider.DocumentsProviderUtils.Companion.notifyDocumentsProviderRoots +import com.owncloud.android.presentation.documentsprovider.DocumentsProviderUtils.notifyDocumentsProviderRoots import com.owncloud.android.presentation.security.PREFERENCE_LAST_UNLOCK_TIMESTAMP import com.owncloud.android.presentation.security.biometric.BiometricStatus import com.owncloud.android.presentation.security.biometric.BiometricViewModel diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/security/SettingsSecurityFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/security/SettingsSecurityFragment.kt index 6a84ed1e116..240edcc2018 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/security/SettingsSecurityFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/security/SettingsSecurityFragment.kt @@ -34,7 +34,7 @@ import androidx.preference.PreferenceScreen import com.owncloud.android.R import com.owncloud.android.extensions.avoidScreenshotsIfNeeded import com.owncloud.android.extensions.showMessageInSnackbar -import com.owncloud.android.presentation.documentsprovider.DocumentsProviderUtils.Companion.notifyDocumentsProviderRoots +import com.owncloud.android.presentation.documentsprovider.DocumentsProviderUtils.notifyDocumentsProviderRoots import com.owncloud.android.presentation.security.LockTimeout import com.owncloud.android.presentation.security.PREFERENCE_LOCK_TIMEOUT import com.owncloud.android.presentation.security.biometric.BiometricActivity diff --git a/owncloudApp/src/main/java/com/owncloud/android/utils/RemoteFileUtils.kt b/owncloudApp/src/main/java/com/owncloud/android/utils/RemoteFileUtils.kt index 68dc34e351e..df472f764f4 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/utils/RemoteFileUtils.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/utils/RemoteFileUtils.kt @@ -24,80 +24,78 @@ package com.owncloud.android.utils import com.owncloud.android.lib.common.OwnCloudClient import com.owncloud.android.lib.resources.files.CheckPathExistenceRemoteOperation -class RemoteFileUtils { - companion object { - /** - * Checks if remotePath does not exist in the server and returns it, or adds - * a suffix to it in order to avoid the server file is overwritten. - * - * @param ownCloudClient - * @param remotePath - * @return - */ - fun getAvailableRemotePath( - ownCloudClient: OwnCloudClient, - remotePath: String, - spaceWebDavUrl: String? = null, - isUserLogged: Boolean, - ): String { - var checkExistsFile = existsFile( - ownCloudClient = ownCloudClient, - remotePath = remotePath, - spaceWebDavUrl = spaceWebDavUrl, - isUserLogged = isUserLogged, - ) - if (!checkExistsFile) { - return remotePath - } - val pos = remotePath.lastIndexOf(".") - var suffix: String - var extension = "" - if (pos >= 0) { - extension = remotePath.substring(pos + 1) - remotePath.apply { - substring(0, pos) - } - } - var count = 1 - do { - suffix = " ($count)" - checkExistsFile = if (pos >= 0) { - existsFile( - ownCloudClient = ownCloudClient, - remotePath = "${remotePath.substringBeforeLast('.', "")}$suffix.$extension", - spaceWebDavUrl = spaceWebDavUrl, - isUserLogged = isUserLogged, - ) - } else { - existsFile( - ownCloudClient = ownCloudClient, - remotePath = remotePath + suffix, - spaceWebDavUrl = spaceWebDavUrl, - isUserLogged = isUserLogged, - ) - } - count++ - } while (checkExistsFile) - return if (pos >= 0) { - "${remotePath.substringBeforeLast('.', "")}$suffix.$extension" - } else { - remotePath + suffix +object RemoteFileUtils { + /** + * Checks if remotePath does not exist in the server and returns it, or adds + * a suffix to it in order to avoid the server file is overwritten. + * + * @param ownCloudClient + * @param remotePath + * @return + */ + fun getAvailableRemotePath( + ownCloudClient: OwnCloudClient, + remotePath: String, + spaceWebDavUrl: String? = null, + isUserLogged: Boolean, + ): String { + var checkExistsFile = existsFile( + ownCloudClient = ownCloudClient, + remotePath = remotePath, + spaceWebDavUrl = spaceWebDavUrl, + isUserLogged = isUserLogged, + ) + if (!checkExistsFile) { + return remotePath + } + val pos = remotePath.lastIndexOf(".") + var suffix: String + var extension = "" + if (pos >= 0) { + extension = remotePath.substring(pos + 1) + remotePath.apply { + substring(0, pos) } } - - private fun existsFile( - ownCloudClient: OwnCloudClient, - remotePath: String, - spaceWebDavUrl: String?, - isUserLogged: Boolean, - ): Boolean { - val existsOperation = - CheckPathExistenceRemoteOperation( - remotePath = remotePath, - isUserLoggedIn = isUserLogged, + var count = 1 + do { + suffix = " ($count)" + checkExistsFile = if (pos >= 0) { + existsFile( + ownCloudClient = ownCloudClient, + remotePath = "${remotePath.substringBeforeLast('.', "")}$suffix.$extension", spaceWebDavUrl = spaceWebDavUrl, + isUserLogged = isUserLogged, ) - return existsOperation.execute(ownCloudClient).isSuccess + } else { + existsFile( + ownCloudClient = ownCloudClient, + remotePath = remotePath + suffix, + spaceWebDavUrl = spaceWebDavUrl, + isUserLogged = isUserLogged, + ) + } + count++ + } while (checkExistsFile) + return if (pos >= 0) { + "${remotePath.substringBeforeLast('.', "")}$suffix.$extension" + } else { + remotePath + suffix } } + + private fun existsFile( + ownCloudClient: OwnCloudClient, + remotePath: String, + spaceWebDavUrl: String?, + isUserLogged: Boolean, + ): Boolean { + val existsOperation = + CheckPathExistenceRemoteOperation( + remotePath = remotePath, + isUserLoggedIn = isUserLogged, + spaceWebDavUrl = spaceWebDavUrl, + ) + return existsOperation.execute(ownCloudClient).isSuccess + } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromContentUriWorker.kt b/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromContentUriWorker.kt index 33cbeb94064..6a3581e43b6 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromContentUriWorker.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromContentUriWorker.kt @@ -59,7 +59,7 @@ import com.owncloud.android.lib.resources.files.chunks.ChunkedUploadFromFileSyst import com.owncloud.android.lib.resources.files.services.implementation.OCChunkService import com.owncloud.android.presentation.authentication.AccountUtils import com.owncloud.android.utils.NotificationUtils -import com.owncloud.android.utils.RemoteFileUtils.Companion.getAvailableRemotePath +import com.owncloud.android.utils.RemoteFileUtils.getAvailableRemotePath import com.owncloud.android.utils.SecurityUtils import com.owncloud.android.utils.UPLOAD_NOTIFICATION_CHANNEL_ID import kotlinx.coroutines.CoroutineScope diff --git a/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromFileSystemWorker.kt b/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromFileSystemWorker.kt index 7bd883ef8a5..2d1a81209c2 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromFileSystemWorker.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromFileSystemWorker.kt @@ -57,7 +57,7 @@ import com.owncloud.android.lib.resources.files.chunks.ChunkedUploadFromFileSyst import com.owncloud.android.lib.resources.files.services.implementation.OCChunkService import com.owncloud.android.presentation.authentication.AccountUtils import com.owncloud.android.utils.NotificationUtils -import com.owncloud.android.utils.RemoteFileUtils.Companion.getAvailableRemotePath +import com.owncloud.android.utils.RemoteFileUtils.getAvailableRemotePath import com.owncloud.android.utils.SecurityUtils import com.owncloud.android.utils.UPLOAD_NOTIFICATION_CHANNEL_ID import kotlinx.coroutines.CoroutineScope From 18624222ae1a85356bb480e8a88cc3ed2f73bfbe Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Tue, 28 Jan 2025 13:17:08 +0100 Subject: [PATCH 55/74] feat: disable CyclomaticComplexMethod rule from detekt.yml --- config/detekt/detekt.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.yml index 3bf851de6f7..4ea88d70896 100644 --- a/config/detekt/detekt.yml +++ b/config/detekt/detekt.yml @@ -97,7 +97,7 @@ complexity: includeStaticDeclarations: false includePrivateDeclarations: false CyclomaticComplexMethod: - active: true + active: false threshold: 15 ignoreSingleWhenExpression: false ignoreSimpleWhenEntries: false From 231a761f3f3831cc3e7ef1fdbb86082bee581b53 Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Tue, 28 Jan 2025 13:34:58 +0100 Subject: [PATCH 56/74] style: removed optional Unit return type --- .../domain/files/usecases/DisableThumbnailsForFileUseCase.kt | 2 +- .../android/domain/files/usecases/SaveFileOrFolderUseCase.kt | 2 +- .../domain/sharing/shares/usecases/DeleteShareAsyncUseCase.kt | 2 +- .../sharing/shares/usecases/EditPrivateShareAsyncUseCase.kt | 2 +- .../transfers/usecases/ClearSuccessfulTransfersUseCase.kt | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/files/usecases/DisableThumbnailsForFileUseCase.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/files/usecases/DisableThumbnailsForFileUseCase.kt index 53120803892..2319d116372 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/files/usecases/DisableThumbnailsForFileUseCase.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/files/usecases/DisableThumbnailsForFileUseCase.kt @@ -25,7 +25,7 @@ class DisableThumbnailsForFileUseCase( private val fileRepository: FileRepository ) : BaseUseCaseWithResult() { - override fun run(params: Params): Unit = + override fun run(params: Params) = fileRepository.disableThumbnailsForFile(params.fileId) data class Params(val fileId: Long) diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/files/usecases/SaveFileOrFolderUseCase.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/files/usecases/SaveFileOrFolderUseCase.kt index 79c9184b399..7e4cdbb5a3c 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/files/usecases/SaveFileOrFolderUseCase.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/files/usecases/SaveFileOrFolderUseCase.kt @@ -26,7 +26,7 @@ import com.owncloud.android.domain.files.model.OCFile class SaveFileOrFolderUseCase( private val fileRepository: FileRepository ) : BaseUseCaseWithResult() { - override fun run(params: Params): Unit = fileRepository.saveFile(params.fileToSave) + override fun run(params: Params) = fileRepository.saveFile(params.fileToSave) data class Params(val fileToSave: OCFile) } diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/sharing/shares/usecases/DeleteShareAsyncUseCase.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/sharing/shares/usecases/DeleteShareAsyncUseCase.kt index 5052ee8c74e..495e2eb91ba 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/sharing/shares/usecases/DeleteShareAsyncUseCase.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/sharing/shares/usecases/DeleteShareAsyncUseCase.kt @@ -25,7 +25,7 @@ import com.owncloud.android.domain.sharing.shares.ShareRepository class DeleteShareAsyncUseCase( private val shareRepository: ShareRepository ) : BaseUseCaseWithResult() { - override fun run(params: Params): Unit = + override fun run(params: Params) = shareRepository.deleteShare( remoteId = params.remoteId, accountName = params.accountName, diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/sharing/shares/usecases/EditPrivateShareAsyncUseCase.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/sharing/shares/usecases/EditPrivateShareAsyncUseCase.kt index 210c4214f2b..18c9607bda8 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/sharing/shares/usecases/EditPrivateShareAsyncUseCase.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/sharing/shares/usecases/EditPrivateShareAsyncUseCase.kt @@ -26,7 +26,7 @@ class EditPrivateShareAsyncUseCase( private val shareRepository: ShareRepository ) : BaseUseCaseWithResult() { - override fun run(params: Params): Unit = + override fun run(params: Params) = shareRepository.updatePrivateShare( params.remoteId, params.permissions, diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/transfers/usecases/ClearSuccessfulTransfersUseCase.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/transfers/usecases/ClearSuccessfulTransfersUseCase.kt index 87450a33c9c..f625225b68c 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/transfers/usecases/ClearSuccessfulTransfersUseCase.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/transfers/usecases/ClearSuccessfulTransfersUseCase.kt @@ -26,7 +26,7 @@ import com.owncloud.android.domain.transfers.TransferRepository class ClearSuccessfulTransfersUseCase( private val transferRepository: TransferRepository, ) : BaseUseCase() { - override fun run(params: Unit): Unit = + override fun run(params: Unit) = transferRepository.clearSuccessfulTransfers() } From 025440ba66afcc45bf515d97a68240f7eff9c8ef Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Tue, 28 Jan 2025 13:58:17 +0100 Subject: [PATCH 57/74] style: consistent braces on `if` statements --- .../android/presentation/authentication/LoginActivity.kt | 4 +++- .../presentation/documentsprovider/cursors/SpaceCursor.kt | 4 +++- .../presentation/files/filelist/MainFileListViewModel.kt | 8 ++++++-- .../presentation/security/biometric/BiometricViewModel.kt | 4 +++- .../settings/security/SettingsSecurityFragment.kt | 8 ++++---- .../sharing/shares/PublicShareDialogFragment.kt | 4 +++- .../java/com/owncloud/android/providers/MdmProvider.kt | 4 +++- .../android/ui/preview/PreviewImagePagerAdapter.kt | 4 +++- .../android/lib/common/utils/OCFileLoggingTree.kt | 4 +++- .../lib/resources/users/GetRemoteUserQuotaOperation.kt | 4 +++- .../java/com/owncloud/android/data/extensions/FileExt.kt | 3 ++- .../java/com/owncloud/android/data/files/db/FileDao.kt | 4 +++- .../domain/server/usecases/GetServerInfoAsyncUseCase.kt | 4 +++- 13 files changed, 42 insertions(+), 17 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/LoginActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/LoginActivity.kt index 1c5e7da85f8..16094f3f655 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/LoginActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/LoginActivity.kt @@ -802,7 +802,9 @@ class LoginActivity : AppCompatActivity(), SslUntrustedCertDialog.OnSslUntrusted setResult(Activity.RESULT_CANCELED) goToUrl(url = getString(R.string.welcome_link_url)) } - } else isVisible = false + } else { + isVisible = false + } } val legacyWebfingerLookupServer = mdmProvider.getBrandingString(NO_MDM_RESTRICTION_YET, R.string.webfinger_lookup_server) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/documentsprovider/cursors/SpaceCursor.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/documentsprovider/cursors/SpaceCursor.kt index db726d07491..4f856018708 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/documentsprovider/cursors/SpaceCursor.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/documentsprovider/cursors/SpaceCursor.kt @@ -42,7 +42,9 @@ class SpaceCursor(projection: Array?) : MatrixCursor(projection ?: DEFAU fun addSpace(space: OCSpace, rootFolder: OCFile, context: Context?) { val flags = if (rootFolder.hasAddFilePermission && rootFolder.hasAddSubdirectoriesPermission) { Document.FLAG_DIR_SUPPORTS_CREATE - } else 0 + } else { + 0 + } val name = if (space.isPersonal) context?.getString(R.string.bottom_nav_personal) else space.name diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListViewModel.kt index c484a7ac4b4..6d629b8352c 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListViewModel.kt @@ -227,14 +227,18 @@ class MainFileListViewModel( parentDir = if (fileById != null && (!fileById.sharedByLink || fileById.sharedWithSharee != true) && fileById.spaceId == null) { getFileByRemotePathUseCase(GetFileByRemotePathUseCase.Params(fileById.owner, ROOT_PATH)).getDataOrNull() - } else fileById + } else { + fileById + } } FileListOption.AV_OFFLINE -> { val fileById = fileByIdResult.getDataOrNull() parentDir = if (fileById != null && (!fileById.isAvailableOffline)) { getFileByRemotePathUseCase(GetFileByRemotePathUseCase.Params(fileById.owner, ROOT_PATH)).getDataOrNull() - } else fileById + } else { + fileById + } } FileListOption.SPACES_LIST -> { diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/biometric/BiometricViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/biometric/BiometricViewModel.kt index 43ab030df4c..f2340a2c114 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/biometric/BiometricViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/biometric/BiometricViewModel.kt @@ -149,7 +149,9 @@ class BiometricViewModel( fun isBiometricLockAvailable(): Boolean = if (!BiometricManager.isHardwareDetected()) { // Biometric not supported false - } else BiometricManager.hasEnrolledBiometric() // Biometric not enrolled + } else { + BiometricManager.hasEnrolledBiometric() // Biometric not enrolled + } companion object { private const val ANDROID_KEY_STORE = "AndroidKeyStore" diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/security/SettingsSecurityFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/security/SettingsSecurityFragment.kt index 240edcc2018..dbd6ba69cce 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/security/SettingsSecurityFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/security/SettingsSecurityFragment.kt @@ -59,7 +59,7 @@ class SettingsSecurityFragment : PreferenceFragmentCompat() { private val enablePasscodeLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> - if (result.resultCode != Activity.RESULT_OK) return@registerForActivityResult + if (result.resultCode != Activity.RESULT_OK) { return@registerForActivityResult } else { prefPasscode?.isChecked = true prefBiometric?.isChecked = securityViewModel.getBiometricsState() @@ -71,7 +71,7 @@ class SettingsSecurityFragment : PreferenceFragmentCompat() { private val disablePasscodeLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> - if (result.resultCode != Activity.RESULT_OK) return@registerForActivityResult + if (result.resultCode != Activity.RESULT_OK) { return@registerForActivityResult } else { prefPasscode?.isChecked = false @@ -83,7 +83,7 @@ class SettingsSecurityFragment : PreferenceFragmentCompat() { private val enablePatternLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> - if (result.resultCode != Activity.RESULT_OK) return@registerForActivityResult + if (result.resultCode != Activity.RESULT_OK) { return@registerForActivityResult } else { prefPattern?.isChecked = true prefBiometric?.isChecked = securityViewModel.getBiometricsState() @@ -95,7 +95,7 @@ class SettingsSecurityFragment : PreferenceFragmentCompat() { private val disablePatternLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> - if (result.resultCode != Activity.RESULT_OK) return@registerForActivityResult + if (result.resultCode != Activity.RESULT_OK) { return@registerForActivityResult } else { prefPattern?.isChecked = false diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/shares/PublicShareDialogFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/shares/PublicShareDialogFragment.kt index daffcdb5573..ae472e333ee 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/shares/PublicShareDialogFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/shares/PublicShareDialogFragment.kt @@ -148,7 +148,9 @@ class PublicShareDialogFragment : DialogFragment() { capabilities?.filesSharingPublicExpireDateDays!! ) .time - } else -1 + } else { + -1 + } private val capabilityViewModel: CapabilityViewModel by viewModel { parametersOf( diff --git a/owncloudApp/src/main/java/com/owncloud/android/providers/MdmProvider.kt b/owncloudApp/src/main/java/com/owncloud/android/providers/MdmProvider.kt index d6c7a8f9871..caba0ac6328 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/providers/MdmProvider.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/providers/MdmProvider.kt @@ -112,7 +112,9 @@ class MdmProvider( return if (isMdmFlavor()) { preferencesProvider.getString(key = mdmKey, defaultValue = setupValue) ?: throw IllegalStateException("Key $stringKey is not supported") - } else setupValue + } else { + setupValue + } } fun getBrandingBoolean( diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImagePagerAdapter.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImagePagerAdapter.kt index 31e7b7cc894..964cd8f5260 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImagePagerAdapter.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImagePagerAdapter.kt @@ -160,7 +160,9 @@ class PreviewImagePagerAdapter( // trigger the creation of new PreviewImageFragment to replace current FileDownloadFragment // only if the download succeeded. If not trigger an error notifyDataSetChanged() - } else fragment?.onSyncEvent(action, success, file) + } else { + fragment?.onSyncEvent(action, success, file) + } } } } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/utils/OCFileLoggingTree.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/utils/OCFileLoggingTree.kt index a4c0a0cb91c..1e2993df7a6 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/utils/OCFileLoggingTree.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/utils/OCFileLoggingTree.kt @@ -104,7 +104,7 @@ class OCFileLoggingTree( element.lineNumber // format ensures line numbers have at least 3 places to align consecutive output from the same file ) return "(${element.fileName}:${element.lineNumber})" - } else + } else { return String.format( Locale.US, "(%s:%d) %s.%s()", @@ -114,6 +114,8 @@ class OCFileLoggingTree( super.createStackElementTag(element)?.replaceFirst(element.fileName.takeWhile { it != '.' }, ""), element.methodName ) + } + } @SuppressLint("LogNotTimber") diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/users/GetRemoteUserQuotaOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/users/GetRemoteUserQuotaOperation.kt index 7ceaab11f7c..01d50b0848c 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/users/GetRemoteUserQuotaOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/users/GetRemoteUserQuotaOperation.kt @@ -116,7 +116,9 @@ class GetRemoteUserQuotaOperation : RemoteOperation() { val roundedRelativeQuota = if (totalQuota > 0) { val relativeQuota = (quotaUsed * 100).toDouble() / totalQuota (relativeQuota * 100).roundToLong() / 100.0 - } else 0.0 + } else { + 0.0 + } RemoteQuota(quotaAvailable, quotaUsed, totalQuota, roundedRelativeQuota) } diff --git a/owncloudData/src/main/java/com/owncloud/android/data/extensions/FileExt.kt b/owncloudData/src/main/java/com/owncloud/android/data/extensions/FileExt.kt index e372da96fe1..5fa12e4e583 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/extensions/FileExt.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/extensions/FileExt.kt @@ -48,7 +48,8 @@ fun File.moveRecursively( val relPath = src.toRelativeString(this) val dstFile = File(target, relPath) if (dstFile.exists() && !(src.isDirectory && dstFile.isDirectory)) { - val stillExists = if (!overwrite) true else { + val stillExists = if (!overwrite) { true } + else { if (dstFile.isDirectory) !dstFile.deleteRecursively() else diff --git a/owncloudData/src/main/java/com/owncloud/android/data/files/db/FileDao.kt b/owncloudData/src/main/java/com/owncloud/android/data/files/db/FileDao.kt index a3d6ab3ee9b..5f500c2c6e0 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/files/db/FileDao.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/files/db/FileDao.kt @@ -485,7 +485,9 @@ interface FileDao { AVAILABLE_OFFLINE_PARENT.ordinal } else if (currentFileAvailableOfflineStatus == AVAILABLE_OFFLINE.ordinal) { AVAILABLE_OFFLINE.ordinal - } else NOT_AVAILABLE_OFFLINE.ordinal + } else { + NOT_AVAILABLE_OFFLINE.ordinal + } companion object { diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/server/usecases/GetServerInfoAsyncUseCase.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/server/usecases/GetServerInfoAsyncUseCase.kt index 58f784175c5..387f9fbc8f4 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/server/usecases/GetServerInfoAsyncUseCase.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/server/usecases/GetServerInfoAsyncUseCase.kt @@ -58,7 +58,9 @@ class GetServerInfoAsyncUseCase( !url.lowercase(Locale.getDefault()).startsWith(HTTPS_PREFIX) ) { "$HTTPS_PREFIX$url" - } else url + } else { + url + } companion object { const val TRAILING_SLASH = '/' From 6b7df4e8a230115f8c148e7b485c776fe197ede1 Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Tue, 28 Jan 2025 15:11:38 +0100 Subject: [PATCH 58/74] style: consistent braces on `when` statements --- .../android/extensions/ThrowableExt.kt | 7 +-- .../files/details/FileDetailsFragment.kt | 44 +++++++++----- .../files/filelist/MainFileListFragment.kt | 4 +- .../security/passcode/PassCodeActivity.kt | 4 +- .../presentation/sharing/ShareActivity.kt | 4 +- .../android/providers/FileContentProvider.kt | 53 +++++++++++------ .../android/ui/activity/DrawerActivity.kt | 12 ++-- .../ui/activity/FileDisplayActivity.kt | 4 +- .../ui/errorhandling/ErrorMessageAdapter.kt | 58 +++++++------------ .../ui/preview/PreviewAudioFragment.kt | 4 +- .../ui/preview/PreviewImageActivity.kt | 4 +- .../ui/preview/PreviewImageFragment.kt | 4 +- .../ui/preview/PreviewVideoActivity.kt | 4 +- .../android/data/RemoteOperationHandler.kt | 4 +- 14 files changed, 118 insertions(+), 92 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/extensions/ThrowableExt.kt b/owncloudApp/src/main/java/com/owncloud/android/extensions/ThrowableExt.kt index c2feb639f63..fd0eebe6880 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/extensions/ThrowableExt.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/extensions/ThrowableExt.kt @@ -71,14 +71,11 @@ fun Throwable.parseError( is CopyIntoDescendantException -> resources.getString(R.string.copy_file_invalid_into_descendent) is CopyIntoSameFolderException -> resources.getString(R.string.copy_file_invalid_overwrite) is FileAlreadyExistsException -> resources.getString(R.string.file_already_exists) - is FileNameException -> { - val stringId = when (this.type) { + is FileNameException -> resources.getString(when (this.type) { FileNameException.FileNameExceptionType.FILE_NAME_EMPTY -> R.string.filename_empty FileNameException.FileNameExceptionType.FILE_NAME_FORBIDDEN_CHARACTERS -> R.string.filename_forbidden_characters_from_server FileNameException.FileNameExceptionType.FILE_NAME_TOO_LONG -> R.string.filename_too_long - } - resources.getString(stringId) - } + }) is FileNotFoundException -> resources.getString(R.string.common_not_found) is ForbiddenException -> resources.getString(R.string.uploads_view_upload_status_failed_permission_error) is IncorrectAddressException -> resources.getString(R.string.auth_incorrect_address_title) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/details/FileDetailsFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/details/FileDetailsFragment.kt index 17131a69291..08dc3e1d6b6 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/details/FileDetailsFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/details/FileDetailsFragment.kt @@ -185,23 +185,33 @@ class FileDetailsFragment : FileFragment() { } is UIResult.Loading -> {} - is UIResult.Success -> when (uiResult.data) { - SynchronizeFileUseCase.SyncType.AlreadySynchronized -> showMessageInSnackbar(getString(R.string.sync_file_nothing_to_do_msg)) - is SynchronizeFileUseCase.SyncType.ConflictDetected -> { - val showConflictActivityIntent = Intent(requireActivity(), ConflictsResolveActivity::class.java) - showConflictActivityIntent.putExtra(ConflictsResolveActivity.EXTRA_FILE, file) - startActivity(showConflictActivityIntent) - } + is UIResult.Success -> { + when (uiResult.data) { + SynchronizeFileUseCase.SyncType.AlreadySynchronized -> { + showMessageInSnackbar(getString(R.string.sync_file_nothing_to_do_msg)) + } + is SynchronizeFileUseCase.SyncType.ConflictDetected -> { + val showConflictActivityIntent = Intent(requireActivity(), ConflictsResolveActivity::class.java) + showConflictActivityIntent.putExtra(ConflictsResolveActivity.EXTRA_FILE, file) + startActivity(showConflictActivityIntent) + } - is SynchronizeFileUseCase.SyncType.DownloadEnqueued -> { - fileDetailsViewModel.startListeningToWorkInfo(uiResult.data.workerId) - } + is SynchronizeFileUseCase.SyncType.DownloadEnqueued -> { + fileDetailsViewModel.startListeningToWorkInfo(uiResult.data.workerId) + } - SynchronizeFileUseCase.SyncType.FileNotFound -> showMessageInSnackbar(getString(R.string.sync_file_not_found_msg)) + SynchronizeFileUseCase.SyncType.FileNotFound -> { + showMessageInSnackbar(getString(R.string.sync_file_not_found_msg)) + } - is SynchronizeFileUseCase.SyncType.UploadEnqueued -> fileDetailsViewModel.startListeningToWorkInfo(uiResult.data.workerId) + is SynchronizeFileUseCase.SyncType.UploadEnqueued -> { + fileDetailsViewModel.startListeningToWorkInfo(uiResult.data.workerId) + } - null -> showMessageInSnackbar(getString(R.string.common_error_unknown)) + null -> { + showMessageInSnackbar(getString(R.string.common_error_unknown)) + } + } } } }) @@ -323,7 +333,9 @@ class FileDetailsFragment : FileFragment() { true } - else -> super.onOptionsItemSelected(item) + else -> { + super.onOptionsItemSelected(item) + } } } @@ -579,7 +591,9 @@ class FileDetailsFragment : FileFragment() { fileDisplayActivity.startTextPreview(fileWaitingToPreview) } - else -> fileDisplayActivity.openOCFile(fileWaitingToPreview) + else -> { + fileDisplayActivity.openOCFile(fileWaitingToPreview) + } } fileOperationsViewModel.setLastUsageFile(fileWaitingToPreview) } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt index 26dd4d451ec..a803014f461 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/files/filelist/MainFileListFragment.kt @@ -866,7 +866,9 @@ class MainFileListFragment : Fragment(), collectLatestLifecycleFlow(fileOperationsViewModel.checkIfFileIsLocalAndNotAvailableOfflineSharedFlow) { val fileActivity = (requireActivity() as FileActivity) when (it) { - is UIResult.Loading -> fileActivity.showLoadingDialog(R.string.common_loading) + is UIResult.Loading -> { + fileActivity.showLoadingDialog(R.string.common_loading) + } is UIResult.Success -> { fileActivity.dismissLoadingDialog() it.data?.let { result -> onShowRemoveDialog(filesToRemove, result) } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt index b690437b01c..006b446e1a5 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/security/passcode/PassCodeActivity.kt @@ -451,7 +451,9 @@ class PassCodeActivity : AppCompatActivity(), NumberKeyboardListener, EnableBiom true } - else -> super.onKeyUp(keyCode, event) + else -> { + super.onKeyUp(keyCode, event) + } } companion object { diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareActivity.kt index 7b776c9731b..3fc1c72b64b 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareActivity.kt @@ -125,7 +125,9 @@ class ShareActivity : FileActivity(), ShareFragmentListener { data?.authority ) } - else -> Timber.e("Unexpected intent $intent") + else -> { + Timber.e("Unexpected intent $intent") + } } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/providers/FileContentProvider.kt b/owncloudApp/src/main/java/com/owncloud/android/providers/FileContentProvider.kt index 3a9c2a88f12..2f7906723c7 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/providers/FileContentProvider.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/providers/FileContentProvider.kt @@ -160,14 +160,13 @@ class FileContentProvider(val executors: Executors = Executors()) : ContentProvi "", whereArgs ) } - ROOT_DIRECTORY -> - count = db.delete(ProviderTableMeta.FILE_TABLE_NAME, where, whereArgs) - SHARES -> count = db.delete(ProviderTableMeta.OCSHARES_TABLE_NAME, where, whereArgs) - CAPABILITIES -> count = db.delete(ProviderTableMeta.CAPABILITIES_TABLE_NAME, where, whereArgs) - UPLOADS -> count = db.delete(ProviderTableMeta.UPLOADS_TABLE_NAME, where, whereArgs) - CAMERA_UPLOADS_SYNC -> count = db.delete(ProviderTableMeta.CAMERA_UPLOADS_SYNC_TABLE_NAME, where, whereArgs) - QUOTAS -> count = db.delete(ProviderTableMeta.USER_QUOTAS_TABLE_NAME, where, whereArgs) - else -> throw IllegalArgumentException("Unknown uri: $uri") + ROOT_DIRECTORY -> { count = db.delete(ProviderTableMeta.FILE_TABLE_NAME, where, whereArgs) } + SHARES -> { count = db.delete(ProviderTableMeta.OCSHARES_TABLE_NAME, where, whereArgs) } + CAPABILITIES -> { count = db.delete(ProviderTableMeta.CAPABILITIES_TABLE_NAME, where, whereArgs) } + UPLOADS -> { count = db.delete(ProviderTableMeta.UPLOADS_TABLE_NAME, where, whereArgs) } + CAMERA_UPLOADS_SYNC -> { count = db.delete(ProviderTableMeta.CAMERA_UPLOADS_SYNC_TABLE_NAME, where, whereArgs) } + QUOTAS -> { count = db.delete(ProviderTableMeta.USER_QUOTAS_TABLE_NAME, where, whereArgs) } + else -> { throw IllegalArgumentException("Unknown uri: $uri") } } return count } @@ -267,7 +266,9 @@ class FileContentProvider(val executors: Executors = Executors()) : ContentProvi if (quotaId <= 0) throw SQLException("ERROR $uri") ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_QUOTAS, quotaId) } - else -> throw IllegalArgumentException("Unknown uri id: $uri") + else -> { + throw IllegalArgumentException("Unknown uri id: $uri") + } } override fun onCreate(): Boolean { @@ -315,7 +316,9 @@ class FileContentProvider(val executors: Executors = Executors()) : ContentProvi sqlQuery.tables = ProviderTableMeta.FILE_TABLE_NAME when (uriMatcher.match(uri)) { - ROOT_DIRECTORY -> sqlQuery.projectionMap = fileProjectionMap + ROOT_DIRECTORY -> { + sqlQuery.projectionMap = fileProjectionMap + } DIRECTORY -> { val folderId = uri.pathSegments[1] sqlQuery.appendWhere( @@ -364,7 +367,9 @@ class FileContentProvider(val executors: Executors = Executors()) : ContentProvi } sqlQuery.projectionMap = quotaProjectionMap } - else -> throw IllegalArgumentException("Unknown uri id: $uri") + else -> { + throw IllegalArgumentException("Unknown uri id: $uri") + } } val order: String? = if (TextUtils.isEmpty(sortOrder)) { @@ -413,19 +418,29 @@ class FileContentProvider(val executors: Executors = Executors()) : ContentProvi throw IllegalArgumentException("Selection not allowed, use parameterized queries") } return when (uriMatcher.match(uri)) { - DIRECTORY -> 0 //updateFolderSize(db, selectionArgs[0]); - SHARES -> db.update(ProviderTableMeta.OCSHARES_TABLE_NAME, values, selection, selectionArgs) - CAPABILITIES -> db.update(ProviderTableMeta.CAPABILITIES_TABLE_NAME, values, selection, selectionArgs) + DIRECTORY -> { + 0 //updateFolderSize(db, selectionArgs[0]); + } + SHARES -> { + db.update(ProviderTableMeta.OCSHARES_TABLE_NAME, values, selection, selectionArgs) + } + CAPABILITIES -> { + db.update(ProviderTableMeta.CAPABILITIES_TABLE_NAME, values, selection, selectionArgs) + } UPLOADS -> { val ret = db.update(ProviderTableMeta.UPLOADS_TABLE_NAME, values, selection, selectionArgs) trimSuccessfulUploads(db) ret } - CAMERA_UPLOADS_SYNC -> db.update(ProviderTableMeta.CAMERA_UPLOADS_SYNC_TABLE_NAME, values, selection, selectionArgs) - QUOTAS -> db.update(ProviderTableMeta.USER_QUOTAS_TABLE_NAME, values, selection, selectionArgs) - else -> db.update( - ProviderTableMeta.FILE_TABLE_NAME, values, selection, selectionArgs - ) + CAMERA_UPLOADS_SYNC -> { + db.update(ProviderTableMeta.CAMERA_UPLOADS_SYNC_TABLE_NAME, values, selection, selectionArgs) + } + QUOTAS -> { + db.update(ProviderTableMeta.USER_QUOTAS_TABLE_NAME, values, selection, selectionArgs) + } + else -> { + db.update(ProviderTableMeta.FILE_TABLE_NAME, values, selection, selectionArgs) + } } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.kt index a4f61d56312..d01e9e27f9c 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.kt @@ -189,10 +189,10 @@ abstract class DrawerActivity : ToolbarActivity() { val settingsIntent = Intent(applicationContext, SettingsActivity::class.java) startActivity(settingsIntent) } - R.id.drawer_menu_feedback -> openFeedback() - R.id.drawer_menu_help -> openHelp() - R.id.drawer_menu_privacy_policy -> openPrivacyPolicy() - else -> Timber.i("Unknown drawer menu item clicked: %s", menuItem.title) + R.id.drawer_menu_feedback -> { openFeedback() } + R.id.drawer_menu_help -> { openHelp() } + R.id.drawer_menu_privacy_policy -> { openPrivacyPolicy() } + else -> { Timber.i("Unknown drawer menu item clicked: %s", menuItem.title) } } true } @@ -316,8 +316,8 @@ abstract class DrawerActivity : ToolbarActivity() { } } } - is UIResult.Loading -> getAccountQuotaText()?.text = getString(R.string.drawer_loading_quota) - is UIResult.Error -> getAccountQuotaText()?.text = getString(R.string.drawer_unavailable_used_storage) + is UIResult.Loading -> { getAccountQuotaText()?.text = getString(R.string.drawer_loading_quota) } + is UIResult.Error -> { getAccountQuotaText()?.text = getString(R.string.drawer_unavailable_used_storage) } } } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt index 3ae2e34bb9f..e7d508def32 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt @@ -1350,7 +1350,9 @@ class FileDisplayActivity : FileActivity(), /** Nothing to do atm. If we are in details view, go back to file list */ } - is SynchronizeFileUseCase.SyncType.UploadEnqueued -> showSnackMessage(getString(R.string.upload_enqueued_msg)) + is SynchronizeFileUseCase.SyncType.UploadEnqueued -> { + showSnackMessage(getString(R.string.upload_enqueued_msg)) + } null -> { /* Nothing to do */ } } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/errorhandling/ErrorMessageAdapter.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/errorhandling/ErrorMessageAdapter.kt index 9614d60e9bb..a2dc0867e63 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/errorhandling/ErrorMessageAdapter.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/errorhandling/ErrorMessageAdapter.kt @@ -79,12 +79,10 @@ class ErrorMessageAdapter { if (throwable == null) { return when (transferOperation) { - is Download -> { - formatter.format( - R.string.downloader_download_succeeded_content, - File(transferOperation.downloadPath).name - ) - } + is Download -> formatter.format( + R.string.downloader_download_succeeded_content, + File(transferOperation.downloadPath).name + ) is TransferOperation.Upload -> formatter.format( R.string.uploader_upload_succeeded_content_single, transferOperation.fileName @@ -96,9 +94,7 @@ class ErrorMessageAdapter { R.string.downloader_download_failed_content, File(transferOperation.downloadPath).name ) - is TransferOperation.Upload -> { - getMessageForFailedUpload(formatter, throwable, transferOperation) - } + is TransferOperation.Upload -> getMessageForFailedUpload(formatter, throwable, transferOperation) } return throwable.parseError(genericMessage, resources, true).toString() } @@ -118,23 +114,17 @@ class ErrorMessageAdapter { R.string.error__upload__local_file_not_copied, transferOperation.fileName, R.string.app_name ) - is ForbiddenException -> { - formatter.format( - R.string.forbidden_permissions, - R.string.uploader_upload_forbidden_permissions - ) - } - is InvalidCharacterException -> { - formatter.format( - R.string.filename_forbidden_characters_from_server - ) - } - is QuotaExceededException -> - formatter.format(R.string.failed_upload_quota_exceeded_text) - is FileNotFoundException -> { - formatter.format(R.string.uploads_view_upload_status_failed_folder_error) - } - else -> formatter.format(R.string.uploader_upload_failed_content_single, transferOperation.fileName) + is ForbiddenException -> formatter.format( + R.string.forbidden_permissions, + R.string.uploader_upload_forbidden_permissions + ) + is InvalidCharacterException -> formatter.format(R.string.filename_forbidden_characters_from_server) + is QuotaExceededException -> formatter.format(R.string.failed_upload_quota_exceeded_text) + is FileNotFoundException -> formatter.format(R.string.uploads_view_upload_status_failed_folder_error) + else -> formatter.format( + R.string.uploader_upload_failed_content_single, + transferOperation.fileName + ) } @@ -154,26 +144,22 @@ class ErrorMessageAdapter { val formatter = Formatter(resources) return when (result.code) { - ResultCode.FORBIDDEN -> { - formatter.format( - R.string.filename_forbidden_characters_from_server - ) - } + ResultCode.FORBIDDEN -> + formatter.format(R.string.filename_forbidden_characters_from_server) ResultCode.INVALID_CHARACTER_DETECT_IN_SERVER -> formatter.format(R.string.filename_forbidden_characters_from_server) ResultCode.QUOTA_EXCEEDED -> formatter.format(R.string.failed_upload_quota_exceeded_text) - ResultCode.FILE_NOT_FOUND -> { + ResultCode.FILE_NOT_FOUND -> formatter.format(R.string.rename_local_fail_msg) - } ResultCode.INVALID_LOCAL_FILE_NAME -> formatter.format(R.string.rename_local_fail_msg) ResultCode.INVALID_CHARACTER_IN_NAME -> formatter.format(R.string.filename_forbidden_characters) - ResultCode.INVALID_OVERWRITE -> { + ResultCode.INVALID_OVERWRITE -> + formatter.format(R.string.move_file_error) + ResultCode.CONFLICT -> formatter.format(R.string.move_file_error) - } - ResultCode.CONFLICT -> formatter.format(R.string.move_file_error) ResultCode.INVALID_COPY_INTO_DESCENDANT -> formatter.format(R.string.copy_file_invalid_into_descendent) else -> getCommonMessageForResult(result, resources) diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewAudioFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewAudioFragment.kt index ad07c8fe194..9353ef46096 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewAudioFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewAudioFragment.kt @@ -312,7 +312,9 @@ class PreviewAudioFragment : FileFragment() { true } - else -> super.onOptionsItemSelected(item) + else -> { + super.onOptionsItemSelected(item) + } } private fun seeDetails() { diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.kt index eed049e8e62..e86dec967e1 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.kt @@ -153,7 +153,9 @@ class PreviewImageActivity : FileActivity(), showErrorInSnackbar(R.string.remove_fail_msg, uiResult.getThrowableOrNull()) } - is UIResult.Loading -> showLoadingDialog(R.string.wait_a_moment) + is UIResult.Loading -> { + showLoadingDialog(R.string.wait_a_moment) + } is UIResult.Success -> { // Refresh the spaces and update the quota diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageFragment.kt index 77e1bd7411a..b8454472c92 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageFragment.kt @@ -259,7 +259,9 @@ class PreviewImageFragment : FileFragment() { true } - else -> super.onOptionsItemSelected(item) + else -> { + super.onOptionsItemSelected(item) + } } private fun seeDetails() { diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewVideoActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewVideoActivity.kt index 09ae1241779..af6476b121e 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewVideoActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewVideoActivity.kt @@ -190,7 +190,9 @@ class PreviewVideoActivity : FileActivity(), Player.Listener, OnPrepareVideoPlay showErrorInSnackbar(R.string.remove_fail_msg, uiResult.getThrowableOrNull()) } - is UIResult.Loading -> showLoadingDialog(R.string.wait_a_moment) + is UIResult.Loading -> { + showLoadingDialog(R.string.wait_a_moment) + } is UIResult.Success -> { // Refresh the spaces and update the quota diff --git a/owncloudData/src/main/java/com/owncloud/android/data/RemoteOperationHandler.kt b/owncloudData/src/main/java/com/owncloud/android/data/RemoteOperationHandler.kt index 5f0c25e0d7c..c0b9e9c8ea3 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/RemoteOperationHandler.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/RemoteOperationHandler.kt @@ -92,11 +92,9 @@ private fun handleRemoteOperationResult( when (remoteOperationResult.code) { RemoteOperationResult.ResultCode.WRONG_CONNECTION -> throw NoConnectionWithServerException() RemoteOperationResult.ResultCode.NO_NETWORK_CONNECTION -> throw NoNetworkConnectionException() - RemoteOperationResult.ResultCode.TIMEOUT -> { + RemoteOperationResult.ResultCode.TIMEOUT -> if (remoteOperationResult.exception is SocketTimeoutException) throw ServerResponseTimeoutException() else throw ServerConnectionTimeoutException() - } - RemoteOperationResult.ResultCode.HOST_NOT_AVAILABLE -> throw ServerNotReachableException() RemoteOperationResult.ResultCode.SERVICE_UNAVAILABLE -> throw ServiceUnavailableException() RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED -> throw remoteOperationResult.exception as CertificateCombinedException From b058ab8aba8cdbee4affbc8b79518a5d3c9354dd Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Tue, 28 Jan 2025 16:23:42 +0100 Subject: [PATCH 59/74] refactor: use `apply` instead of `also` when possible --- .../com/owncloud/android/workers/DownloadFileWorker.kt | 4 ++-- .../android/workers/UploadFileFromContentUriWorker.kt | 8 ++++---- .../android/workers/UploadFileFromFileSystemWorker.kt | 8 ++++---- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/workers/DownloadFileWorker.kt b/owncloudApp/src/main/java/com/owncloud/android/workers/DownloadFileWorker.kt index e6ac9b0497f..8e12897fb46 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/workers/DownloadFileWorker.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/workers/DownloadFileWorker.kt @@ -165,8 +165,8 @@ class DownloadFileWorker( ocFile.remotePath, temporalFolderPath, spaceWebDavUrl, - ).also { - it.addDatatransferProgressListener(this) + ).apply { + addDatatransferProgressListener(this@DownloadFileWorker) } val client = getClientForThisDownload() diff --git a/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromContentUriWorker.kt b/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromContentUriWorker.kt index 6a3581e43b6..3036dff1878 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromContentUriWorker.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromContentUriWorker.kt @@ -268,8 +268,8 @@ class UploadFileFromContentUriWorker( lastModifiedTimestamp = lastModified, requiredEtag = null, spaceWebDavUrl = spaceWebDavUrl, - ).also { - it.addDataTransferProgressListener(this) + ).apply { + addDataTransferProgressListener(this@UploadFileFromContentUriWorker) } executeRemoteOperation { uploadFileOperation.execute(client) } @@ -293,8 +293,8 @@ class UploadFileFromContentUriWorker( mimeType = mimeType, lastModifiedTimestamp = lastModified, requiredEtag = null, - ).also { - it.addDataTransferProgressListener(this) + ).apply { + addDataTransferProgressListener(this@UploadFileFromContentUriWorker) } executeRemoteOperation { uploadFileOperation.execute(client) } diff --git a/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromFileSystemWorker.kt b/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromFileSystemWorker.kt index 2d1a81209c2..9a11a99b50f 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromFileSystemWorker.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromFileSystemWorker.kt @@ -247,8 +247,8 @@ class UploadFileFromFileSystemWorker( lastModifiedTimestamp = lastModified, requiredEtag = eTagInConflict, spaceWebDavUrl = spaceWebDavUrl, - ).also { - it.addDataTransferProgressListener(this) + ).apply { + addDataTransferProgressListener(this@UploadFileFromFileSystemWorker) } val result = executeRemoteOperation { uploadFileOperation.execute(client) } @@ -276,8 +276,8 @@ class UploadFileFromFileSystemWorker( mimeType = mimetype, lastModifiedTimestamp = lastModified, requiredEtag = eTagInConflict, - ).also { - it.addDataTransferProgressListener(this) + ).apply { + addDataTransferProgressListener(this@UploadFileFromFileSystemWorker) } val result = executeRemoteOperation { uploadFileOperation.execute(client) } From 9184072613f1ef11db93678d1af644d59466ee72 Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Wed, 29 Jan 2025 08:56:54 +0100 Subject: [PATCH 60/74] refactor: use more specific exception --- .../owncloud/android/workers/UploadFileFromContentUriWorker.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromContentUriWorker.kt b/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromContentUriWorker.kt index 3036dff1878..cefccde4abd 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromContentUriWorker.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/workers/UploadFileFromContentUriWorker.kt @@ -172,7 +172,7 @@ class UploadFileFromContentUriWorker( val documentFile = DocumentFile.fromSingleUri(appContext, contentUri) if (documentFile?.canRead() != true) { // Permissions not granted. Throw an exception to ask for them. - throw Throwable("Cannot read the file") + throw LocalFileNotFoundException() } } From a9f60301a2b7018c2b917366d05369d1882a4757 Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Wed, 29 Jan 2025 08:58:12 +0100 Subject: [PATCH 61/74] feat: disable TooGenericExceptionThrown rule from detekt.yml --- config/detekt/detekt.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.yml index 4ea88d70896..53cbbf10d36 100644 --- a/config/detekt/detekt.yml +++ b/config/detekt/detekt.yml @@ -281,7 +281,7 @@ exceptions: - 'Throwable' allowedExceptionNameRegex: '_|(ignore|expected).*' TooGenericExceptionThrown: - active: true + active: false exceptionNames: - 'Error' - 'Exception' From d357775793d0372cf3ae3ddeaeb64a80d0a79435 Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Wed, 29 Jan 2025 09:08:40 +0100 Subject: [PATCH 62/74] feat: disable some complexity rules from detekt.yml --- config/detekt/detekt.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.yml index 53cbbf10d36..c9d48d2bf9b 100644 --- a/config/detekt/detekt.yml +++ b/config/detekt/detekt.yml @@ -86,7 +86,7 @@ comments: complexity: active: true CognitiveComplexMethod: - active: true + active: false threshold: 20 ComplexCondition: active: true @@ -136,7 +136,7 @@ complexity: threshold: 3 ignoreArgumentsMatchingNames: false NestedBlockDepth: - active: true + active: false threshold: 5 NestedScopeFunctions: active: false @@ -754,7 +754,7 @@ style: ignoreActualFunction: true excludedFunctions: [] LoopWithTooManyJumpStatements: - active: true + active: false maxJumpCount: 1 MagicNumber: active: false From 56fc727896a667954a71bb4b25e74a4c01842e2b Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Wed, 29 Jan 2025 11:46:33 +0100 Subject: [PATCH 63/74] refactor: avoid swallowed exceptions --- owncloudApp/src/main/java/com/owncloud/android/MainApp.kt | 1 + .../main/java/com/owncloud/android/extensions/ActivityExt.kt | 1 + .../android/presentation/accounts/ManageAccountsAdapter.kt | 2 +- .../documentsprovider/DocumentsStorageProvider.kt | 1 + .../android/presentation/sharing/RemoveShareDialogFragment.kt | 1 + .../android/presentation/sharing/ShareFileFragment.kt | 1 + .../presentation/sharing/sharees/EditPrivateShareFragment.kt | 1 + .../presentation/sharing/sharees/SearchShareesFragment.kt | 1 + .../presentation/sharing/shares/PublicShareDialogFragment.kt | 1 + .../android/presentation/transfers/TransfersAdapter.kt | 2 +- .../java/com/owncloud/android/ui/activity/DrawerActivity.kt | 2 +- .../com/owncloud/android/ui/activity/FolderPickerActivity.kt | 1 + .../com/owncloud/android/ui/preview/PreviewAudioFragment.kt | 1 + .../usecases/synchronization/SynchronizeFileUseCase.kt | 1 + .../com/owncloud/android/workers/AutomaticUploadsWorker.kt | 2 ++ .../android/workers/AvailableOfflinePeriodicWorker.kt | 1 + .../com/owncloud/android/workers/OldLogsCollectorWorker.kt | 2 ++ ...RemoveLocallyFilesWithLastUsageOlderThanGivenTimeWorker.kt | 2 ++ .../android/lib/resources/status/GetRemoteStatusOperation.kt | 2 ++ .../owncloud/android/lib/resources/status/OwnCloudVersion.kt | 2 ++ .../main/java/com/owncloud/android/data/extensions/FileExt.kt | 3 +++ .../android/data/files/repository/OCFileRepository.kt | 2 +- .../android/data/server/repository/OCServerInfoRepository.kt | 4 ++-- 23 files changed, 31 insertions(+), 6 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/MainApp.kt b/owncloudApp/src/main/java/com/owncloud/android/MainApp.kt index 5d5db83472b..3af6a25362e 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/MainApp.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/MainApp.kt @@ -345,6 +345,7 @@ class MainApp : Application() { val longVersionCode: Long = PackageInfoCompat.getLongVersionCode(pInfo) longVersionCode.toInt() } catch (e: PackageManager.NameNotFoundException) { + Timber.w(e, "Version code not found, using 0 as fallback") 0 } diff --git a/owncloudApp/src/main/java/com/owncloud/android/extensions/ActivityExt.kt b/owncloudApp/src/main/java/com/owncloud/android/extensions/ActivityExt.kt index e92e75ccf12..66d6ccac07f 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/extensions/ActivityExt.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/extensions/ActivityExt.kt @@ -230,6 +230,7 @@ fun Activity.openFileWithIntent(intentForSavedMimeType: Intent, intentForGuessed ) ) } catch (anfe: ActivityNotFoundException) { + Timber.i(anfe, "No app found for file type") showMessageInSnackbar( message = this.getString( R.string.file_list_no_app_for_file_type diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/accounts/ManageAccountsAdapter.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/accounts/ManageAccountsAdapter.kt index eaaf9b4ba03..8e7c646966b 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/accounts/ManageAccountsAdapter.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/accounts/ManageAccountsAdapter.kt @@ -84,7 +84,7 @@ class ManageAccountsAdapter( holder.binding.name.text = oca.displayName } catch (e: Exception) { Timber.w( - "Account not found right after being read :\\ ; using account name instead of display name" + e, "Account not found right after being read :\\ ; using account name instead of display name" ) holder.binding.name.text = AccountUtils.getUsernameOfAccount(account.name) } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/documentsprovider/DocumentsStorageProvider.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/documentsprovider/DocumentsStorageProvider.kt index 3d2c1be78f6..499399e89b0 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/documentsprovider/DocumentsStorageProvider.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/documentsprovider/DocumentsStorageProvider.kt @@ -170,6 +170,7 @@ class DocumentsStorageProvider : DocumentsProvider() { } } } catch (e: IOException) { + Timber.e(e, "Couldn't open document") throw FileNotFoundException("Failed to open document with id $documentId and mode $mode") } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/RemoveShareDialogFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/RemoveShareDialogFragment.kt index c3854d4f572..8d9eca34633 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/RemoveShareDialogFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/RemoveShareDialogFragment.kt @@ -68,6 +68,7 @@ class RemoveShareDialogFragment : ConfirmationDialogFragment(), ConfirmationDial try { listener = activity as ShareFragmentListener? } catch (e: IllegalStateException) { + Timber.e(e, "The activity attached doesn't implement OnShareFragmentInteractionListener") throw IllegalStateException(requireActivity().toString() + " must implement OnShareFragmentInteractionListener") } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareFileFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareFileFragment.kt index 5fe32a69785..00a24ea730f 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareFileFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/ShareFileFragment.kt @@ -284,6 +284,7 @@ class ShareFileFragment : Fragment(), ShareUserListAdapter.ShareUserAdapterListe try { listener = context as ShareFragmentListener? } catch (e: ClassCastException) { + Timber.e(e, "The activity attached doesn't implement OnShareFragmentInteractionListener") throw ClassCastException(activity.toString() + " must implement OnShareFragmentInteractionListener") } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/EditPrivateShareFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/EditPrivateShareFragment.kt index 93c270d2806..46b85b95afe 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/EditPrivateShareFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/EditPrivateShareFragment.kt @@ -148,6 +148,7 @@ class EditPrivateShareFragment : DialogFragment() { try { listener = activity as ShareFragmentListener? } catch (e: IllegalStateException) { + Timber.e(e, "The activity attached doesn't implement OnShareFragmentInteractionListener") throw IllegalStateException(requireActivity().toString() + " must implement OnShareFragmentInteractionListener") } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/SearchShareesFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/SearchShareesFragment.kt index d9d1de9f94e..925ff311ec8 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/SearchShareesFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/sharees/SearchShareesFragment.kt @@ -190,6 +190,7 @@ class SearchShareesFragment : Fragment(), try { listener = activity as ShareFragmentListener? } catch (e: ClassCastException) { + Timber.e(e, "The activity attached doesn't implement OnFragmentInteractionListener") throw ClassCastException(requireActivity().toString() + " must implement OnFragmentInteractionListener") } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/shares/PublicShareDialogFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/shares/PublicShareDialogFragment.kt index ae472e333ee..4a70511cb4a 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/shares/PublicShareDialogFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/shares/PublicShareDialogFragment.kt @@ -610,6 +610,7 @@ class PublicShareDialogFragment : DialogFragment() { try { listener = activity as ShareFragmentListener? } catch (e: IllegalStateException) { + Timber.e(e, "The activity attached doesn't implement OnShareFragmentInteractionListener") throw IllegalStateException(activity?.toString() + " must implement OnShareFragmentInteractionListener") } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/transfers/TransfersAdapter.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/transfers/TransfersAdapter.kt index c635ea91c8c..8eda5b04f08 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/transfers/TransfersAdapter.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/transfers/TransfersAdapter.kt @@ -147,7 +147,7 @@ class TransfersAdapter( DisplayUtils.convertIdn(account.name.substring(account.name.lastIndexOf("@") + 1), false) uploadAccount.text = accountName } catch (e: Exception) { - Timber.w("Couldn't get display name for account, using old style") + Timber.w(e, "Couldn't get display name for account, using old style") uploadAccount.text = transferItem.transfer.accountName } diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.kt index d01e9e27f9c..cd1e1a7e39d 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.kt @@ -446,7 +446,7 @@ abstract class DrawerActivity : ToolbarActivity() { val ocAccount = OwnCloudAccount(account, this) getDrawerUserName()?.text = ocAccount.displayName } catch (e: Exception) { - Timber.w("Couldn't read display name of account; using account name instead") + Timber.w(e, "Couldn't read display name of account; using account name instead") getDrawerUserName()?.text = drawerViewModel.getUsernameOfAccount(account.name) } diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FolderPickerActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FolderPickerActivity.kt index df437106b7d..6654096bbf2 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FolderPickerActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FolderPickerActivity.kt @@ -351,6 +351,7 @@ open class FolderPickerActivity : FileActivity(), val currentDir = try { getCurrentFolder() } catch (e: NullPointerException) { + Timber.i(e, "Couldn't retrieve current folder, so using file property") file } diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewAudioFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewAudioFragment.kt index 9353ef46096..b3bd4d92712 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewAudioFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewAudioFragment.kt @@ -180,6 +180,7 @@ class PreviewAudioFragment : FileFragment() { imagePreview?.setImageResource(R.drawable.ic_place_holder_music_cover_art) } } catch (t: Throwable) { + Timber.i(t, "Couldn't extract cover art, setting default image instead") imagePreview?.setImageResource(R.drawable.ic_place_holder_music_cover_art) } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/usecases/synchronization/SynchronizeFileUseCase.kt b/owncloudApp/src/main/java/com/owncloud/android/usecases/synchronization/SynchronizeFileUseCase.kt index e292f902792..c10d3ad3faf 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/usecases/synchronization/SynchronizeFileUseCase.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/usecases/synchronization/SynchronizeFileUseCase.kt @@ -53,6 +53,7 @@ class SynchronizeFileUseCase( spaceId = fileToSynchronize.spaceId ) } catch (exception: FileNotFoundException) { + Timber.i(exception, "File does not exist anymore in remote") // 1.1 File does not exist anymore in remote val localFile = fileToSynchronize.id?.let { fileRepository.getFileById(it) } // If it still exists locally, but file has different path, another operation could have been done simultaneously diff --git a/owncloudApp/src/main/java/com/owncloud/android/workers/AutomaticUploadsWorker.kt b/owncloudApp/src/main/java/com/owncloud/android/workers/AutomaticUploadsWorker.kt index 1508b89a0e9..e0a3866bce5 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/workers/AutomaticUploadsWorker.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/workers/AutomaticUploadsWorker.kt @@ -88,6 +88,7 @@ class AutomaticUploadsWorker( checkSourcePathIsAValidUriOrThrowException(pictureUploadsConfiguration.sourcePath) syncFolder(pictureUploadsConfiguration) } catch (illegalArgumentException: IllegalArgumentException) { + Timber.e(illegalArgumentException, "Source path for picture uploads is not valid") showNotificationToUpdateUri(SyncType.PICTURE_UPLOADS) return Result.failure() } @@ -97,6 +98,7 @@ class AutomaticUploadsWorker( checkSourcePathIsAValidUriOrThrowException(videoUploadsConfiguration.sourcePath) syncFolder(videoUploadsConfiguration) } catch (illegalArgumentException: IllegalArgumentException) { + Timber.e(illegalArgumentException, "Source path for video uploads is not valid") showNotificationToUpdateUri(SyncType.VIDEO_UPLOADS) return Result.failure() } diff --git a/owncloudApp/src/main/java/com/owncloud/android/workers/AvailableOfflinePeriodicWorker.kt b/owncloudApp/src/main/java/com/owncloud/android/workers/AvailableOfflinePeriodicWorker.kt index 9695db105bf..12094f32a66 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/workers/AvailableOfflinePeriodicWorker.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/workers/AvailableOfflinePeriodicWorker.kt @@ -51,6 +51,7 @@ class AvailableOfflinePeriodicWorker( Result.success() } catch (exception: Exception) { + Timber.e(exception, "Sync of available offline files failed") Result.failure() } diff --git a/owncloudApp/src/main/java/com/owncloud/android/workers/OldLogsCollectorWorker.kt b/owncloudApp/src/main/java/com/owncloud/android/workers/OldLogsCollectorWorker.kt index 08889d6a82a..318c629c239 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/workers/OldLogsCollectorWorker.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/workers/OldLogsCollectorWorker.kt @@ -46,8 +46,10 @@ class OldLogsCollectorWorker( removeOldLogs(logsFiles) Result.success() } catch (ioException: IOException) { + Timber.e(ioException, "An error occurred trying to access the file") Result.failure() } catch (securityException: SecurityException) { + Timber.e(securityException, "A security violation was produced") Result.failure() } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/workers/RemoveLocallyFilesWithLastUsageOlderThanGivenTimeWorker.kt b/owncloudApp/src/main/java/com/owncloud/android/workers/RemoveLocallyFilesWithLastUsageOlderThanGivenTimeWorker.kt index 5b94e3be523..15250ce60ae 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/workers/RemoveLocallyFilesWithLastUsageOlderThanGivenTimeWorker.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/workers/RemoveLocallyFilesWithLastUsageOlderThanGivenTimeWorker.kt @@ -30,6 +30,7 @@ import com.owncloud.android.ui.preview.PreviewVideoActivity import com.owncloud.android.usecases.files.RemoveLocallyFilesWithLastUsageOlderThanGivenTimeUseCase import org.koin.core.component.KoinComponent import org.koin.core.component.inject +import timber.log.Timber import java.util.concurrent.TimeUnit class RemoveLocallyFilesWithLastUsageOlderThanGivenTimeWorker( @@ -50,6 +51,7 @@ class RemoveLocallyFilesWithLastUsageOlderThanGivenTimeWorker( ) Result.success() } catch (exception: Exception) { + Timber.e(exception, "An error occurred when trying to remove local files") Result.failure() } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/GetRemoteStatusOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/GetRemoteStatusOperation.kt index 3be9c82b8df..0f456b116b7 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/GetRemoteStatusOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/GetRemoteStatusOperation.kt @@ -31,6 +31,7 @@ import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCo import com.owncloud.android.lib.resources.status.HttpScheme.HTTPS_PREFIX import com.owncloud.android.lib.resources.status.HttpScheme.HTTP_PREFIX import org.json.JSONException +import timber.log.Timber /** * Checks if the server is valid @@ -63,6 +64,7 @@ class GetRemoteStatusOperation : RemoteOperation() { updateClientBaseUrl(client, result.data.baseUrl) return result } catch (e: JSONException) { + Timber.e(e, "JSON is not correct") RemoteOperationResult(ResultCode.INSTANCE_NOT_CONFIGURED) } catch (e: Exception) { RemoteOperationResult(e) diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/OwnCloudVersion.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/OwnCloudVersion.kt index 226bcade362..2a8f6749675 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/OwnCloudVersion.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/status/OwnCloudVersion.kt @@ -27,6 +27,7 @@ package com.owncloud.android.lib.resources.status import android.os.Parcel import android.os.Parcelable +import timber.log.Timber class OwnCloudVersion(version: String) : Comparable, Parcelable { @@ -94,6 +95,7 @@ class OwnCloudVersion(version: String) : Comparable, Parcelable isVersionValid = true } catch (e: Exception) { + Timber.w(e, "Version is invalid") isVersionValid = false // if invalid, the instance will respond as if server is 8.1, minimum with capabilities API, // and "dead" : https://github.com/owncloud/core/wiki/Maintenance-and-Release-Schedule diff --git a/owncloudData/src/main/java/com/owncloud/android/data/extensions/FileExt.kt b/owncloudData/src/main/java/com/owncloud/android/data/extensions/FileExt.kt index 5fa12e4e583..b59ffaa3e63 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/extensions/FileExt.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/extensions/FileExt.kt @@ -20,6 +20,7 @@ package com.owncloud.android.data.extensions +import timber.log.Timber import java.io.File import java.io.IOException @@ -86,6 +87,7 @@ fun File.moveRecursively( src.delete() } } catch (e: IOException) { + Timber.e(e, "An error occurred while trying to move the file") src.delete() dstFile.delete() } @@ -96,6 +98,7 @@ fun File.moveRecursively( return true } catch (e: TerminateException) { + Timber.e(e, "The process terminated unexpectedly") return false } } diff --git a/owncloudData/src/main/java/com/owncloud/android/data/files/repository/OCFileRepository.kt b/owncloudData/src/main/java/com/owncloud/android/data/files/repository/OCFileRepository.kt index 072538e4f5b..e272d465cfc 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/files/repository/OCFileRepository.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/files/repository/OCFileRepository.kt @@ -447,7 +447,7 @@ class OCFileRepository( spaceWebDavUrl = spaceWebDavUrl, ) } catch (fileNotFoundException: FileNotFoundException) { - Timber.i("File ${ocFile.fileName} was not found in server. Let's remove it from local storage") + Timber.i(fileNotFoundException, "File ${ocFile.fileName} was not found in server. Let's remove it from local storage") } } ocFile.etagInConflict?.let { diff --git a/owncloudData/src/main/java/com/owncloud/android/data/server/repository/OCServerInfoRepository.kt b/owncloudData/src/main/java/com/owncloud/android/data/server/repository/OCServerInfoRepository.kt index 6547add0bd3..db1bd847126 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/server/repository/OCServerInfoRepository.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/server/repository/OCServerInfoRepository.kt @@ -56,7 +56,7 @@ class OCServerInfoRepository( val openIDConnectServerConfiguration = try { oidcRemoteOAuthDataSource.performOIDCDiscovery(serverInfo.baseUrl) } catch (exception: Exception) { - Timber.d("OIDC discovery not found") + Timber.d(exception, "OIDC discovery not found") null } @@ -85,7 +85,7 @@ class OCServerInfoRepository( resource = serverUrl, ).firstOrNull() } catch (exception: Exception) { - Timber.d("Cant retrieve the oidc issuer from webfinger.") + Timber.d(exception, "Cant retrieve the oidc issuer from webfinger.") null } From e6115ad6c86d9a52673c1b31c030149df26607dc Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Wed, 29 Jan 2025 12:59:24 +0100 Subject: [PATCH 64/74] refactor: not printing stack trace for exceptions --- .../owncloud/android/presentation/logging/LogsListActivity.kt | 1 - 1 file changed, 1 deletion(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/logging/LogsListActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/logging/LogsListActivity.kt index f6754f5aa1c..c44260d8c44 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/logging/LogsListActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/logging/LogsListActivity.kt @@ -179,7 +179,6 @@ class LogsListActivity : AppCompatActivity() { } } } catch (e: IOException) { - e.printStackTrace() Timber.e(e, "There was a problem to download the file to Downloads folder.") } } From 969cc00b91a47042f35065adc4985ba8a6907075 Mon Sep 17 00:00:00 2001 From: joragua Date: Wed, 29 Jan 2025 14:25:42 +0100 Subject: [PATCH 65/74] refactor: fix for KtLint report --- .../security/SettingsSecurityFragment.kt | 20 +++++++++++-------- .../android/data/extensions/FileExt.kt | 5 +++-- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/security/SettingsSecurityFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/security/SettingsSecurityFragment.kt index dbd6ba69cce..dfd076b612c 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/security/SettingsSecurityFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/settings/security/SettingsSecurityFragment.kt @@ -59,8 +59,9 @@ class SettingsSecurityFragment : PreferenceFragmentCompat() { private val enablePasscodeLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> - if (result.resultCode != Activity.RESULT_OK) { return@registerForActivityResult } - else { + if (result.resultCode != Activity.RESULT_OK) { + return@registerForActivityResult + } else { prefPasscode?.isChecked = true prefBiometric?.isChecked = securityViewModel.getBiometricsState() @@ -71,8 +72,9 @@ class SettingsSecurityFragment : PreferenceFragmentCompat() { private val disablePasscodeLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> - if (result.resultCode != Activity.RESULT_OK) { return@registerForActivityResult } - else { + if (result.resultCode != Activity.RESULT_OK) { + return@registerForActivityResult + } else { prefPasscode?.isChecked = false // Do not allow to use biometric lock, lock delay nor access from document provider since Passcode lock has been disabled @@ -83,8 +85,9 @@ class SettingsSecurityFragment : PreferenceFragmentCompat() { private val enablePatternLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> - if (result.resultCode != Activity.RESULT_OK) { return@registerForActivityResult } - else { + if (result.resultCode != Activity.RESULT_OK) { + return@registerForActivityResult + } else { prefPattern?.isChecked = true prefBiometric?.isChecked = securityViewModel.getBiometricsState() @@ -95,8 +98,9 @@ class SettingsSecurityFragment : PreferenceFragmentCompat() { private val disablePatternLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> - if (result.resultCode != Activity.RESULT_OK) { return@registerForActivityResult } - else { + if (result.resultCode != Activity.RESULT_OK) { + return@registerForActivityResult + } else { prefPattern?.isChecked = false // Do not allow to use biometric lock, lock delay nor access from document provider since Pattern lock has been disabled diff --git a/owncloudData/src/main/java/com/owncloud/android/data/extensions/FileExt.kt b/owncloudData/src/main/java/com/owncloud/android/data/extensions/FileExt.kt index b59ffaa3e63..26b40952113 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/extensions/FileExt.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/extensions/FileExt.kt @@ -49,8 +49,9 @@ fun File.moveRecursively( val relPath = src.toRelativeString(this) val dstFile = File(target, relPath) if (dstFile.exists() && !(src.isDirectory && dstFile.isDirectory)) { - val stillExists = if (!overwrite) { true } - else { + val stillExists = if (!overwrite) { + true + } else { if (dstFile.isDirectory) !dstFile.deleteRecursively() else From 0b7d1ba5fda137dbf14fe7dc00aa02b6d86639a5 Mon Sep 17 00:00:00 2001 From: joragua Date: Wed, 29 Jan 2025 14:48:10 +0100 Subject: [PATCH 66/74] refactor: added `catch` blocks for specific instances of exception --- .../presentation/avatar/AvatarManager.kt | 9 +++-- .../common/http/methods/webdav/DavMethod.kt | 37 +++++++++---------- 2 files changed, 23 insertions(+), 23 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/avatar/AvatarManager.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/avatar/AvatarManager.kt index f880f5407ad..aba2d17e711 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/avatar/AvatarManager.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/avatar/AvatarManager.kt @@ -126,12 +126,13 @@ class AvatarManager : KoinComponent { Timber.d("User avatar saved into cache -> %s", imageKey) return BitmapUtils.bitmapToCircularBitmapDrawable(appContext.resources, bitmap) } - } catch (t: Throwable) { + } catch (t: OutOfMemoryError) { // the app should never break due to a problem with avatars Timber.e(t, "Generation of avatar for $imageKey failed") - if (t is OutOfMemoryError) { - System.gc() - } + System.gc() + null + } catch (t: Throwable) { + Timber.e(t, "Generation of avatar for $imageKey failed") null } } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/DavMethod.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/DavMethod.kt index d3dec99e0d5..41244d24929 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/DavMethod.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/common/http/methods/webdav/DavMethod.kt @@ -67,27 +67,26 @@ abstract class DavMethod protected constructor(url: URL) : HttpBaseMethod(url) { ) onDavExecute(davResource!!) - } catch (httpException: HttpException) { + } catch (httpException: RedirectException) { // Modify responses with information gathered from exceptions - if (httpException is RedirectException) { - response = Response.Builder() - .header( - HttpConstants.LOCATION_HEADER, httpException.redirectLocation - ) - .code(httpException.code) - .request(request) - .message(httpException.message ?: "") - .protocol(Protocol.HTTP_1_1) + response = Response.Builder() + .header( + HttpConstants.LOCATION_HEADER, httpException.redirectLocation + ) + .code(httpException.code) + .request(request) + .message(httpException.message ?: "") + .protocol(Protocol.HTTP_1_1) + .build() + httpException.code + } catch (httpException: HttpException) { + // The check below should be included in okhttp library, method ResponseBody.create( + // TODO check most recent versions of okhttp to see if this is already fixed and try to update if so + if (response.body?.contentType() != null) { + val responseBody = (httpException.responseBody ?: "").toResponseBody(response.body?.contentType()) + response = response.newBuilder() + .body(responseBody) .build() - } else { - // The check below should be included in okhttp library, method ResponseBody.create( - // TODO check most recent versions of okhttp to see if this is already fixed and try to update if so - if (response.body?.contentType() != null) { - val responseBody = (httpException.responseBody ?: "").toResponseBody(response.body?.contentType()) - response = response.newBuilder() - .body(responseBody) - .build() - } } httpException.code } From 5f323bf83ad559ef564957cb765919995dfc8c14 Mon Sep 17 00:00:00 2001 From: joragua Date: Thu, 30 Jan 2025 09:22:56 +0100 Subject: [PATCH 67/74] style: renamed some constructor parameters that were not following naming convention --- .../oauth/responses/OIDCDiscoveryResponse.kt | 28 +++++++++++++------ .../implementation/OCRemoteOAuthDataSource.kt | 18 ++++++------ .../android/data/oauth/RemoteOAuthUtils.kt | 18 ++++++------ 3 files changed, 37 insertions(+), 27 deletions(-) diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/oauth/responses/OIDCDiscoveryResponse.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/oauth/responses/OIDCDiscoveryResponse.kt index 52720bdd5e7..4446c31016a 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/oauth/responses/OIDCDiscoveryResponse.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/oauth/responses/OIDCDiscoveryResponse.kt @@ -26,18 +26,28 @@ */ package com.owncloud.android.lib.resources.oauth.responses +import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class OIDCDiscoveryResponse( - val authorization_endpoint: String, - val check_session_iframe: String?, - val end_session_endpoint: String?, + @Json(name = "authorization_endpoint") + val authorizationEndpoint: String, + @Json(name = "check_session_iframe") + val checkSessionIframe: String?, + @Json(name = "end_session_endpoint") + val endSessionEndpoint: String?, val issuer: String, - val registration_endpoint: String?, - val response_types_supported: List?, // To do: provisional, remove nullability ASAP - val scopes_supported: List?, - val token_endpoint: String, - val token_endpoint_auth_methods_supported: List?, - val userinfo_endpoint: String?, + @Json(name = "registration_endpoint") + val registrationEndpoint: String?, + @Json(name = "response_types_supported") + val responseTypesSupported: List?, // To do: provisional, remove nullability ASAP + @Json(name = "scopes_supported") + val scopesSupported: List?, + @Json(name = "token_endpoint") + val tokenEndpoint: String, + @Json(name = "token_endpoint_auth_methods_supported") + val tokenEndpointAuthMethodsSupported: List?, + @Json(name = "userinfo_endpoint") + val userinfoEndpoint: String?, ) diff --git a/owncloudData/src/main/java/com/owncloud/android/data/oauth/datasources/implementation/OCRemoteOAuthDataSource.kt b/owncloudData/src/main/java/com/owncloud/android/data/oauth/datasources/implementation/OCRemoteOAuthDataSource.kt index 351f0ac80ba..6c56878dd1c 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/oauth/datasources/implementation/OCRemoteOAuthDataSource.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/oauth/datasources/implementation/OCRemoteOAuthDataSource.kt @@ -85,16 +85,16 @@ class OCRemoteOAuthDataSource( **************************************************************************************************************/ private fun OIDCDiscoveryResponse.toModel(): OIDCServerConfiguration = OIDCServerConfiguration( - authorizationEndpoint = this.authorization_endpoint, - checkSessionIframe = this.check_session_iframe, - endSessionEndpoint = this.end_session_endpoint, + authorizationEndpoint = this.authorizationEndpoint, + checkSessionIframe = this.checkSessionIframe, + endSessionEndpoint = this.endSessionEndpoint, issuer = this.issuer, - registrationEndpoint = this.registration_endpoint, - responseTypesSupported = this.response_types_supported, - scopesSupported = this.scopes_supported, - tokenEndpoint = this.token_endpoint, - tokenEndpointAuthMethodsSupported = this.token_endpoint_auth_methods_supported, - userInfoEndpoint = this.userinfo_endpoint + registrationEndpoint = this.registrationEndpoint, + responseTypesSupported = this.responseTypesSupported, + scopesSupported = this.scopesSupported, + tokenEndpoint = this.tokenEndpoint, + tokenEndpointAuthMethodsSupported = this.tokenEndpointAuthMethodsSupported, + userInfoEndpoint = this.userinfoEndpoint ) private fun TokenRequest.toParams(): TokenRequestParams = diff --git a/owncloudData/src/test/java/com/owncloud/android/data/oauth/RemoteOAuthUtils.kt b/owncloudData/src/test/java/com/owncloud/android/data/oauth/RemoteOAuthUtils.kt index dc84a584620..920dbc9c426 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/oauth/RemoteOAuthUtils.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/oauth/RemoteOAuthUtils.kt @@ -31,16 +31,16 @@ import com.owncloud.android.testutil.oauth.OC_TOKEN_REQUEST_REFRESH import com.owncloud.android.testutil.oauth.OC_TOKEN_RESPONSE val OC_REMOTE_OIDC_DISCOVERY_RESPONSE = OIDCDiscoveryResponse( - authorization_endpoint = OC_OIDC_SERVER_CONFIGURATION.authorizationEndpoint, - check_session_iframe = OC_OIDC_SERVER_CONFIGURATION.checkSessionIframe, - end_session_endpoint = OC_OIDC_SERVER_CONFIGURATION.endSessionEndpoint, + authorizationEndpoint = OC_OIDC_SERVER_CONFIGURATION.authorizationEndpoint, + checkSessionIframe = OC_OIDC_SERVER_CONFIGURATION.checkSessionIframe, + endSessionEndpoint = OC_OIDC_SERVER_CONFIGURATION.endSessionEndpoint, issuer = OC_OIDC_SERVER_CONFIGURATION.issuer, - registration_endpoint = OC_OIDC_SERVER_CONFIGURATION.registrationEndpoint, - response_types_supported = OC_OIDC_SERVER_CONFIGURATION.responseTypesSupported, - scopes_supported = OC_OIDC_SERVER_CONFIGURATION.scopesSupported, - token_endpoint = OC_OIDC_SERVER_CONFIGURATION.tokenEndpoint, - token_endpoint_auth_methods_supported = OC_OIDC_SERVER_CONFIGURATION.tokenEndpointAuthMethodsSupported, - userinfo_endpoint = OC_OIDC_SERVER_CONFIGURATION.userInfoEndpoint + registrationEndpoint = OC_OIDC_SERVER_CONFIGURATION.registrationEndpoint, + responseTypesSupported = OC_OIDC_SERVER_CONFIGURATION.responseTypesSupported, + scopesSupported = OC_OIDC_SERVER_CONFIGURATION.scopesSupported, + tokenEndpoint = OC_OIDC_SERVER_CONFIGURATION.tokenEndpoint, + tokenEndpointAuthMethodsSupported = OC_OIDC_SERVER_CONFIGURATION.tokenEndpointAuthMethodsSupported, + userinfoEndpoint = OC_OIDC_SERVER_CONFIGURATION.userInfoEndpoint ) val OC_REMOTE_TOKEN_REQUEST_PARAMS_ACCESS = TokenRequestParams.Authorization( From 93328a3b3a168451af85661102944ce8f5d685f6 Mon Sep 17 00:00:00 2001 From: joragua Date: Thu, 30 Jan 2025 09:54:33 +0100 Subject: [PATCH 68/74] refactor: added missing messages in some exceptions --- .../presentation/authentication/AuthenticationViewModel.kt | 3 ++- .../android/presentation/authentication/LoginActivity.kt | 3 ++- .../android/lib/resources/files/RenameRemoteFileOperation.kt | 2 +- .../java/com/owncloud/android/data/RemoteOperationHandler.kt | 2 +- .../owncloud/android/data/providers/LocalStorageProvider.kt | 2 +- 5 files changed, 7 insertions(+), 5 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/AuthenticationViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/AuthenticationViewModel.kt index 69840f95125..9b321261067 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/AuthenticationViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/AuthenticationViewModel.kt @@ -163,7 +163,8 @@ class AuthenticationViewModel( viewModelScope.launch(coroutinesDispatcherProvider.io) { _loginResult.postValue(Event(UIResult.Loading())) - val serverInfo = serverInfo.value?.peekContent()?.getStoredData() ?: throw java.lang.IllegalArgumentException() + val serverInfo = serverInfo.value?.peekContent()?.getStoredData() ?: throw java.lang.IllegalArgumentException("Server info value cannot" + + " be null") // Authenticated WebFinger needed only for account creations. Logged accounts already know their instances. if (updateAccountWithUsername == null) { diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/LoginActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/LoginActivity.kt index 16094f3f655..00d88227c9c 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/LoginActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/authentication/LoginActivity.kt @@ -589,7 +589,8 @@ class LoginActivity : AppCompatActivity(), SslUntrustedCertDialog.OnSslUntrusted Timber.e("OAuth request to get authorization code failed. Error: [$authorizationError]." + " Error description: [$authorizationErrorDescription]") val authorizationException = - if (authorizationError == "access_denied") UnauthorizedException() else Throwable() + if (authorizationError == "access_denied") UnauthorizedException() else Throwable("An unknown authorization error has " + + "occurred") updateOAuthStatusIconAndText(authorizationException) } } diff --git a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/RenameRemoteFileOperation.kt b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/RenameRemoteFileOperation.kt index 2d712cdea37..94c44b4ffd8 100644 --- a/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/RenameRemoteFileOperation.kt +++ b/owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/files/RenameRemoteFileOperation.kt @@ -54,7 +54,7 @@ class RenameRemoteFileOperation( private var newRemotePath: String init { - var parent = (File(oldRemotePath)).parent ?: throw IllegalArgumentException() + var parent = (File(oldRemotePath)).parent ?: throw IllegalArgumentException("Parent path is null") if (!parent.endsWith(File.separator)) { parent = parent.plus(File.separator) } diff --git a/owncloudData/src/main/java/com/owncloud/android/data/RemoteOperationHandler.kt b/owncloudData/src/main/java/com/owncloud/android/data/RemoteOperationHandler.kt index c0b9e9c8ea3..fcfe3c876b1 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/RemoteOperationHandler.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/RemoteOperationHandler.kt @@ -143,6 +143,6 @@ private fun handleRemoteOperationResult( RemoteOperationResult.ResultCode.TOO_EARLY -> throw TooEarlyException() RemoteOperationResult.ResultCode.NETWORK_ERROR -> throw NetworkErrorException() RemoteOperationResult.ResultCode.RESOURCE_LOCKED -> throw ResourceLockedException() - else -> throw Exception() + else -> throw Exception("An unknown error has occurred") } } diff --git a/owncloudData/src/main/java/com/owncloud/android/data/providers/LocalStorageProvider.kt b/owncloudData/src/main/java/com/owncloud/android/data/providers/LocalStorageProvider.kt index a345eebc698..ddd6237db76 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/providers/LocalStorageProvider.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/providers/LocalStorageProvider.kt @@ -73,7 +73,7 @@ sealed class LocalStorageProvider(private val rootFolderName: String) { * Get expected remote path for a file creation, rename, move etc */ fun getExpectedRemotePath(remotePath: String, newName: String, isFolder: Boolean): String { - var parent = (File(remotePath)).parent ?: throw IllegalArgumentException() + var parent = (File(remotePath)).parent ?: throw IllegalArgumentException("Parent path is null") parent = if (parent.endsWith(File.separator)) parent else parent + File.separator var newRemotePath = parent + newName if (isFolder) { From 4c4479bf5141e146ea4938f01be7b2875d2a29b8 Mon Sep 17 00:00:00 2001 From: joragua Date: Thu, 30 Jan 2025 12:36:01 +0100 Subject: [PATCH 69/74] feat: disabled CastToNullableType rule from detekt.yml --- config/detekt/detekt.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.yml index c9d48d2bf9b..4071c65af7e 100644 --- a/config/detekt/detekt.yml +++ b/config/detekt/detekt.yml @@ -596,7 +596,7 @@ potential-bugs: CastNullableToNonNullableType: active: true CastToNullableType: - active: true + active: false Deprecation: active: false DontDowncastCollectionTypes: From 68bd29ba0e47825d46b21e34062b90fa966d365d Mon Sep 17 00:00:00 2001 From: joragua Date: Thu, 30 Jan 2025 13:00:57 +0100 Subject: [PATCH 70/74] refactor: reduced the number of conditions in some methods --- config/detekt/detekt.yml | 2 +- .../shares/PublicShareDialogFragment.kt | 11 +++++++---- .../ui/activity/FileDisplayActivity.kt | 6 ++++-- .../ui/activity/FolderPickerActivity.kt | 4 +++- .../files/FilterFileMenuOptionsUseCase.kt | 19 ++++++++++++------- 5 files changed, 27 insertions(+), 15 deletions(-) diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.yml index 4071c65af7e..07ec58ebdf4 100644 --- a/config/detekt/detekt.yml +++ b/config/detekt/detekt.yml @@ -90,7 +90,7 @@ complexity: threshold: 20 ComplexCondition: active: true - threshold: 5 + threshold: 6 ComplexInterface: active: false threshold: 10 diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/shares/PublicShareDialogFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/shares/PublicShareDialogFragment.kt index 4a70511cb4a..3853466b2e8 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/shares/PublicShareDialogFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/sharing/shares/PublicShareDialogFragment.kt @@ -873,10 +873,7 @@ class PublicShareDialogFragment : DialogFragment() { } // Set password label when opening the dialog - if (binding.shareViaLinkEditPermissionReadOnly.isChecked && - capabilities?.filesSharingPublicPasswordEnforcedReadOnly == CapabilityBooleanType.TRUE || - binding.shareViaLinkEditPermissionReadAndWrite.isChecked && - capabilities?.filesSharingPublicPasswordEnforcedReadWrite == CapabilityBooleanType.TRUE || + if (isReadOnlyPermission() || isReadAndWritePermission() || binding.shareViaLinkEditPermissionUploadFiles.isChecked && capabilities?.filesSharingPublicPasswordEnforcedUploadOnly == CapabilityBooleanType.TRUE) { setPasswordEnforced() @@ -935,6 +932,12 @@ class PublicShareDialogFragment : DialogFragment() { } } + private fun isReadOnlyPermission() = binding.shareViaLinkEditPermissionReadOnly.isChecked && + capabilities?.filesSharingPublicPasswordEnforcedReadOnly == CapabilityBooleanType.TRUE + + private fun isReadAndWritePermission() = binding.shareViaLinkEditPermissionReadAndWrite.isChecked && + capabilities?.filesSharingPublicPasswordEnforcedReadWrite == CapabilityBooleanType.TRUE + private fun setPasswordNotEnforced() { binding.shareViaLinkPasswordLabel.text = getString(R.string.share_via_link_password_label) binding.shareViaLinkPasswordSwitch.isVisible = true diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt index e7d508def32..e8b5586722b 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt @@ -961,8 +961,7 @@ class FileDisplayActivity : FileActivity(), // or it will show the root folder one if (intent.action == ACTION_DETAILS && chosenFile?.remotePath == OCFile.ROOT_PATH && secondFragment is FileDetailsFragment) return - if (chosenFile == null || (chosenFile.remotePath == OCFile.ROOT_PATH && (space == null || - (!space.isProject && !(space.isPersonal && isMultiPersonal))))) { + if (chosenFile == null || (chosenFile.remotePath == OCFile.ROOT_PATH && (space == null || isNotProjectSpaceAndMultiPersonalMode(space)))) { val title = when (fileListOption) { FileListOption.AV_OFFLINE -> getString(R.string.drawer_item_only_available_offline) @@ -984,6 +983,9 @@ class FileDisplayActivity : FileActivity(), } } + private fun isNotProjectSpaceAndMultiPersonalMode(space: OCSpace?) = !space!!.isProject && !(space.isPersonal && isMultiPersonal) + + /** * Updates the view associated to the activity after the finish of an operation trying to * remove a file. diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FolderPickerActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FolderPickerActivity.kt index 6654096bbf2..15b41d6084b 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FolderPickerActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/FolderPickerActivity.kt @@ -181,7 +181,7 @@ open class FolderPickerActivity : FileActivity(), // If current file is root folder else if (currentDirDisplayed.parentId == OCFile.ROOT_PARENT_ID) { // If we are not in COPY or CAMERA_FOLDER mode, or if we are in COPY or CAMERA_FOLDER mode and spaces are not allowed, close the activity - if ((pickerMode != PickerMode.COPY && pickerMode != PickerMode.CAMERA_FOLDER) || + if (pickerModeIsNotCopyAndCameraFolder() || (pickerMode == PickerMode.COPY && currentDirDisplayed.spaceId == null) || (pickerMode == PickerMode.CAMERA_FOLDER && currentDirDisplayed.spaceId == null)) { finish() @@ -241,6 +241,8 @@ open class FolderPickerActivity : FileActivity(), // Nothing to do. Details can't be opened here. } + private fun pickerModeIsNotCopyAndCameraFolder() = pickerMode != PickerMode.COPY && pickerMode != PickerMode.CAMERA_FOLDER + private fun initAndShowListOfFilesFragment(spaceId: String? = null) { val safeInitialFolder = if (file == null) { if (account == null) { diff --git a/owncloudApp/src/main/java/com/owncloud/android/usecases/files/FilterFileMenuOptionsUseCase.kt b/owncloudApp/src/main/java/com/owncloud/android/usecases/files/FilterFileMenuOptionsUseCase.kt index 9fee1785623..6e13a983320 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/usecases/files/FilterFileMenuOptionsUseCase.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/usecases/files/FilterFileMenuOptionsUseCase.kt @@ -80,6 +80,11 @@ class FilterFileMenuOptionsUseCase( val shareWithUsersAllowed = params.shareWithUsersAllowed val sendAllowed = params.sendAllowed + val noSyncAndPreviewing = !isAnyFileSynchronizing && !isAnyFileVideoPreviewing + val noSyncAndStreaming = !isAnyFileSynchronizing && !isAnyFileVideoStreaming + val shareViaLinkOrWithUsersAllowed = shareViaLinkAllowed || shareWithUsersAllowed + val noFilesDownloadedOrIsSingleFile = allFilesDownloaded(files) || isSingleFile(files) + // Select all if (displaySelectAll) { optionsToShow.add(FileMenuOption.SELECT_ALL) @@ -89,7 +94,7 @@ class FilterFileMenuOptionsUseCase( optionsToShow.add(FileMenuOption.SELECT_INVERSE) } // Share - if (!onlyAvailableOfflineFiles && (shareViaLinkAllowed || shareWithUsersAllowed) && resharingAllowed && + if (!onlyAvailableOfflineFiles && shareViaLinkOrWithUsersAllowed && resharingAllowed && isPersonalSpace && hasResharePermission) { optionsToShow.add(FileMenuOption.SHARE) } @@ -98,7 +103,7 @@ class FilterFileMenuOptionsUseCase( optionsToShow.add(FileMenuOption.OPEN_WITH) } // Download - if (!isAnyFileSynchronizing && !isAnyFileVideoPreviewing && !onlyAvailableOfflineFiles && !onlySharedByLinkFiles && + if (noSyncAndPreviewing && !onlyAvailableOfflineFiles && !onlySharedByLinkFiles && !anyFolder(files) && !anyFileDownloaded(files)) { optionsToShow.add(FileMenuOption.DOWNLOAD) } @@ -112,22 +117,22 @@ class FilterFileMenuOptionsUseCase( optionsToShow.add(FileMenuOption.CANCEL_SYNC) } // Rename - if (!isAnyFileSynchronizing && !isAnyFileVideoPreviewing && !onlyAvailableOfflineFiles && !onlySharedByLinkFiles && + if (noSyncAndPreviewing && !onlyAvailableOfflineFiles && !onlySharedByLinkFiles && hasRenamePermission) { optionsToShow.add(FileMenuOption.RENAME) } // Move - if (!isAnyFileSynchronizing && !isAnyFileVideoPreviewing && !onlyAvailableOfflineFiles && !onlySharedByLinkFiles && + if (noSyncAndPreviewing && !onlyAvailableOfflineFiles && !onlySharedByLinkFiles && hasMovePermission) { optionsToShow.add(FileMenuOption.MOVE) } // Copy - if (!isAnyFileSynchronizing && !isAnyFileVideoPreviewing && !onlyAvailableOfflineFiles && !onlySharedByLinkFiles) { + if (noSyncAndPreviewing && !onlyAvailableOfflineFiles && !onlySharedByLinkFiles) { optionsToShow.add(FileMenuOption.COPY) } // Send - if (!isAnyFileSynchronizing && !isAnyFileVideoStreaming && !onlyAvailableOfflineFiles && !anyFolder(files) && - (allFilesDownloaded(files) || isSingleFile(files)) && sendAllowed) { + if (noSyncAndStreaming && !onlyAvailableOfflineFiles && !anyFolder(files) && + noFilesDownloadedOrIsSingleFile && sendAllowed) { optionsToShow.add(FileMenuOption.SEND) } // Set as available offline From 172c14c86cb49e2eed307c9dba49c9b84e743643 Mon Sep 17 00:00:00 2001 From: joragua Date: Thu, 30 Jan 2025 13:03:44 +0100 Subject: [PATCH 71/74] refactor: renamed files so that they match the single-top declarations --- .../android/utils/{MdmConfigurations.kt => MDMConfigurations.kt} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename owncloudApp/src/main/java/com/owncloud/android/utils/{MdmConfigurations.kt => MDMConfigurations.kt} (100%) diff --git a/owncloudApp/src/main/java/com/owncloud/android/utils/MdmConfigurations.kt b/owncloudApp/src/main/java/com/owncloud/android/utils/MDMConfigurations.kt similarity index 100% rename from owncloudApp/src/main/java/com/owncloud/android/utils/MdmConfigurations.kt rename to owncloudApp/src/main/java/com/owncloud/android/utils/MDMConfigurations.kt From 6f6454589267f420bb370871f56746ef7db1ed8c Mon Sep 17 00:00:00 2001 From: Juan Carlos Garrote Date: Thu, 30 Jan 2025 14:39:57 +0100 Subject: [PATCH 72/74] chore: added calens file --- changelog/unreleased/4487 | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 changelog/unreleased/4487 diff --git a/changelog/unreleased/4487 b/changelog/unreleased/4487 new file mode 100644 index 00000000000..ea233bb9b43 --- /dev/null +++ b/changelog/unreleased/4487 @@ -0,0 +1,7 @@ +Enhancement: Detekt: static code analyzer + +The Kotlin static code analyzer Detekt has been introduced with the agreed rules, and +the left code smells have been fixed throughout the whole code. + +https://github.com/owncloud/android/issues/4506 +https://github.com/owncloud/android/pull/4487 From 9a7fba2f77169f47a29975d1e42962f4784c049f Mon Sep 17 00:00:00 2001 From: JuancaG05 <57049315+JuancaG05@users.noreply.github.com> Date: Thu, 30 Jan 2025 13:40:29 +0000 Subject: [PATCH 73/74] docs: calens changelog updated --- CHANGELOG.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3dff2421821..2e8490629b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,7 @@ ownCloud admins and users. * Enhancement - Added text labels for BottomNavigationView: [#4484](https://github.com/owncloud/android/issues/4484) * Enhancement - OCIS Light Users: [#4490](https://github.com/owncloud/android/issues/4490) * Enhancement - Enforce OIDC auth flow via branding: [#4500](https://github.com/owncloud/android/issues/4500) +* Enhancement - Detekt: static code analyzer: [#4506](https://github.com/owncloud/android/issues/4506) * Enhancement - Multi-Personal (1st round): [#4514](https://github.com/owncloud/android/issues/4514) * Enhancement - Technical improvements for user quota: [#4521](https://github.com/owncloud/android/issues/4521) @@ -135,6 +136,14 @@ ownCloud admins and users. https://github.com/owncloud/android/issues/4500 https://github.com/owncloud/android/pull/4516 +* Enhancement - Detekt: static code analyzer: [#4506](https://github.com/owncloud/android/issues/4506) + + The Kotlin static code analyzer Detekt has been introduced with the agreed + rules, and the left code smells have been fixed throughout the whole code. + + https://github.com/owncloud/android/issues/4506 + https://github.com/owncloud/android/pull/4487 + * Enhancement - Multi-Personal (1st round): [#4514](https://github.com/owncloud/android/issues/4514) Support for multi-personal accounts has been added. This first approach displays From e61ea921cc413f48f6d1b4ec5ecaa8a2514b8114 Mon Sep 17 00:00:00 2001 From: Jesus Recio Date: Thu, 30 Jan 2025 14:44:48 +0100 Subject: [PATCH 74/74] fix: adapt and clean detekt.yml file to run in production --- .github/workflows/detekt.yml | 104 ++--------------------------------- 1 file changed, 4 insertions(+), 100 deletions(-) diff --git a/.github/workflows/detekt.yml b/.github/workflows/detekt.yml index 79445c53c7c..1ad121ec195 100644 --- a/.github/workflows/detekt.yml +++ b/.github/workflows/detekt.yml @@ -1,37 +1,18 @@ -# This is a basic workflow that is manually triggered - name: Detekt # Controls when the action will run. Workflow runs when manually triggered using the UI # or API. on: - workflow_dispatch: - # Inputs the workflow accepts. - inputs: - name: - # Friendly description to be shown in the UI instead of 'name' - description: 'Detekt' - # Default value if no value is explicitly provided - default: 'World' - # Input has to be provided for the workflow to run - required: true - # The data type of the input - type: string - push: - branches: - - feature/detekt - - feature/run_actions_parallel pull_request: branches: - - "master" + - "*" paths: - ".github/workflows/detekt.yml" # A workflow run is made up of one or more jobs that can run sequentially or in parallel jobs: - # This workflow contains a single job called "greet" - owncloudApp: + Detekt: # The type of runner that the job will run on runs-on: ubuntu-latest @@ -47,82 +28,5 @@ jobs: # See: https://github.com/gradle/actions/blob/main/setup-gradle/README.md - name: Setup Gradle uses: gradle/actions/setup-gradle@v4 - - name: module owncloudApp - run: ./gradlew detekt - - owncloudDomain: - # The type of runner that the job will run on - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v4 - - name: Set up JDK 17 - uses: actions/setup-java@v4 - with: - java-version: '17' - distribution: 'temurin' - - # Configure Gradle for optimal use in GitHub Actions, including caching of downloaded dependencies. - # See: https://github.com/gradle/actions/blob/main/setup-gradle/README.md - - name: Setup Gradle - uses: gradle/actions/setup-gradle@v4 - - name: module owncloudDomain - run: ./gradlew owncloudDomain:detekt - - owncloudData: - # The type of runner that the job will run on - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v4 - - name: Set up JDK 17 - uses: actions/setup-java@v4 - with: - java-version: '17' - distribution: 'temurin' - - # Configure Gradle for optimal use in GitHub Actions, including caching of downloaded dependencies. - # See: https://github.com/gradle/actions/blob/main/setup-gradle/README.md - - name: Setup Gradle - uses: gradle/actions/setup-gradle@v4 - - name: module owncloudData - run: ./gradlew owncloudData:detekt - - owncloudComLibrary: - # The type of runner that the job will run on - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v4 - - name: Set up JDK 17 - uses: actions/setup-java@v4 - with: - java-version: '17' - distribution: 'temurin' - - # Configure Gradle for optimal use in GitHub Actions, including caching of downloaded dependencies. - # See: https://github.com/gradle/actions/blob/main/setup-gradle/README.md - - name: Setup Gradle - uses: gradle/actions/setup-gradle@v4 - - name: module owncloudComLibrary - run: ./gradlew owncloudComLibrary:detekt - - - owncloudTestUtil: - # The type of runner that the job will run on - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v4 - - name: Set up JDK 17 - uses: actions/setup-java@v4 - with: - java-version: '17' - distribution: 'temurin' - - # Configure Gradle for optimal use in GitHub Actions, including caching of downloaded dependencies. - # See: https://github.com/gradle/actions/blob/main/setup-gradle/README.md - - name: Setup Gradle - uses: gradle/actions/setup-gradle@v4 - - name: module owncloudTestUtil - run: ./gradlew owncloudTestUtil:detekt + - name: detekt execution + run: ./gradlew detekt; ./gradlew owncloudDomain:detekt; ./gradlew owncloudData:detekt; ./gradlew owncloudComLibrary:detekt; ./gradlew owncloudTestUtil:detekt