diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..a8232df --- /dev/null +++ b/.editorconfig @@ -0,0 +1,29 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +max_line_length = 100 +indent_size = 4 +indent_style = space +insert_final_newline = true +tab_width = 4 +ij_continuation_indent_size = 8 +ij_formatter_off_tag = @formatter:off +ij_formatter_on_tag = @formatter:on +ij_formatter_tags_enabled = false +ij_smart_tabs = false +ij_visual_guides = none +ij_wrap_on_typing = false + +# Specific settings for YAML files +[{*.yml,*.yaml}] +indent_size = 2 + +[*.{kt,kts}] +ktlint_standard_annotation = disabled +ij_kotlin_allow_trailing_comma = false +ij_kotlin_allow_trailing_comma_on_call_site = false +ktlint_standard_multiline-expression-wrapping = disabled +ktlint_standard_string-template-indent = disabled +ktlint_standard_import-ordering = disabled diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..42a03ab --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @wireapp/integrations \ No newline at end of file diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..2921bf1 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,18 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + # Maven updates + - package-ecosystem: "gradle" + directory: "/" + schedule: + interval: "weekly" + + # Maintain dependencies for GitHub Actions + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml deleted file mode 100644 index db25aa4..0000000 --- a/.github/workflows/ci.yml +++ /dev/null @@ -1,65 +0,0 @@ -name: CI - -on: - push: - branches-ignore: - - master - - staging - - pull_request: - -jobs: - check: - runs-on: ubuntu-20.04 - steps: - - uses: actions/checkout@v2 - - - name: Setup JDK - uses: actions/setup-java@v1 - with: - java-version: 11.0.6 - - - name: Execute test with gradle - run: ./gradlew test - - # Send webhook to Wire using Slack Bot - - name: Webhook to Wire - uses: 8398a7/action-slack@v2 - with: - status: ${{ job.status }} - author_name: Poll Bot bare metal CI pipeline - env: - SLACK_WEBHOOK_URL: ${{ secrets.WEBHOOK_CI }} - # Send message only if previous step failed - if: failure() - - docker-build: - runs-on: ubuntu-20.04 - steps: - - uses: actions/checkout@v2 - - # setup docker actions https://github.com/docker/build-push-action - - name: Set up QEMU - uses: docker/setup-qemu-action@v1 - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v1 - - - name: Build image - id: docker_build - uses: docker/build-push-action@v2 - with: - # https://github.com/docker/build-push-action/issues/220 - context: . - tags: wire/ci-test-image - push: false - - # Send webhook to Wire using Slack Bot - - name: Webhook to Wire - uses: 8398a7/action-slack@v2 - with: - status: ${{ job.status }} - author_name: Docker CI pipeline - env: - SLACK_WEBHOOK_URL: ${{ secrets.WEBHOOK_CI }} - # Send message only if previous step failed - if: failure() diff --git a/.github/workflows/prod.yml b/.github/workflows/prod.yml deleted file mode 100644 index 468a0b5..0000000 --- a/.github/workflows/prod.yml +++ /dev/null @@ -1,189 +0,0 @@ -name: Release Pipeline - -on: - release: - types: [ published ] - -env: - DOCKER_IMAGE: wire-bot/poll - SERVICE_NAME: poll - -jobs: - deploy: - name: Build and deploy service - runs-on: ubuntu-20.04 - steps: - - uses: actions/checkout@v2 - - - name: Set Release Version - # use latest tag as release version - run: echo "RELEASE_VERSION=${GITHUB_REF:10}" >> $GITHUB_ENV - - # extract metadata for labels https://github.com/crazy-max/ghaction-docker-meta - - name: Docker meta - id: docker_meta - uses: crazy-max/ghaction-docker-meta@v1 - with: - images: eu.gcr.io/${{ env.DOCKER_IMAGE }} - - # setup docker actions https://github.com/docker/build-push-action - - name: Set up QEMU - uses: docker/setup-qemu-action@v1 - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v1 - # login to GCR repo - - name: Login to DockerHub - uses: docker/login-action@v1 - with: - registry: eu.gcr.io - username: _json_key - password: ${{ secrets.GCR_ACCESS_JSON }} - - - name: Build and push - id: docker_build - uses: docker/build-push-action@v2 - with: - tags: ${{ steps.docker_meta.outputs.tags }} - labels: ${{ steps.docker_meta.outputs.labels }} - # push only if this is indeed a taged release - push: ${{ startsWith(github.ref, 'refs/tags/') }} - build-args: | - release_version=${{ env.RELEASE_VERSION }} - - # Checkout our Kubernetes configuration - - name: Checkout Rubicon - uses: actions/checkout@v2 - with: - repository: zinfra/rubicon - # currently main branch is develop - ref: develop - path: rubicon - # private repo so use different git token - token: ${{ secrets.RUBICON_GIT_TOKEN }} - - # Update version to the one that was just built - - name: Change Version in Rubicon - env: - IMAGE: ${{ env.DOCKER_IMAGE }} - SERVICE: ${{ env.SERVICE_NAME }} - VERSION: ${{ env.RELEASE_VERSION }} - run: | - # go to directory with configuration - cd "rubicon/prod/services/$SERVICE" - # escape literals for the sed and set output with GCR - export SED_PREPARED=$(echo $IMAGE | awk '{ gsub("/", "\\/", $1); print "eu.gcr.io\\/"$1 }') - # update final yaml - sed -i".bak" "s/image: $SED_PREPARED.*/image: $SED_PREPARED:$VERSION/g" "$SERVICE.yaml" - # delete bakup file - rm "$SERVICE.yaml.bak" - - - name: Enable auth plugin - run: | - echo "USE_GKE_GCLOUD_AUTH_PLUGIN=True" >> $GITHUB_ENV - # Auth to GKE - - name: Authenticate to GKE - uses: google-github-actions/auth@v1 - with: - project_id: wire-bot - credentials_json: ${{ secrets.GKE_SA_KEY }} - service_account: kubernetes-deployment-agent@wire-bot.iam.gserviceaccount.com - - # Setup gcloud CLI - - name: Set up Cloud SDK - uses: google-github-actions/setup-gcloud@v1 - - # Prepare components - - name: Prepare gcloud components - run: | - gcloud components install gke-gcloud-auth-plugin - gcloud components update - gcloud --quiet auth configure-docker - - # Get the GKE credentials so we can deploy to the cluster - - name: Obtain k8s credentials - env: - GKE_CLUSTER: anayotto - GKE_ZONE: europe-west1-c - run: | - gcloud container clusters get-credentials "$GKE_CLUSTER" --zone "$GKE_ZONE" - - # K8s is set up, deploy the app - - name: Deploy the Service - env: - SERVICE: ${{ env.SERVICE_NAME }} - run: | - kubectl apply -f "rubicon/prod/services/$SERVICE/$SERVICE.yaml" - - # Commit all data to Rubicon and open PR - - name: Create Rubicon Pull Request - uses: peter-evans/create-pull-request@v3 - with: - path: rubicon - branch: ${{ env.SERVICE_NAME }}-release - token: ${{ secrets.RUBICON_GIT_TOKEN }} - labels: version-bump, automerge - title: ${{ env.SERVICE_NAME }} release ${{ env.RELEASE_VERSION }} - commit-message: ${{ env.SERVICE_NAME }} version bump to ${{ env.RELEASE_VERSION }} - body: | - This is automatic version bump from the pipeline. - - # Send webhook to Wire using Slack Bot - - name: Webhook to Wire - uses: 8398a7/action-slack@v2 - with: - status: ${{ job.status }} - author_name: ${{ env.SERVICE_NAME }} release pipeline - env: - SLACK_WEBHOOK_URL: ${{ secrets.WEBHOOK_RELEASE }} - # Notify every release - if: always() - - quay_publish: - name: Quay Publish Pipeline - runs-on: ubuntu-20.04 - steps: - - uses: actions/checkout@v2 - - name: Set Release Version - # use latest tag as release version - run: echo "RELEASE_VERSION=${GITHUB_REF:10}" >> $GITHUB_ENV - - # extract metadata for labels https://github.com/crazy-max/ghaction-docker-meta - - name: Docker meta - id: docker_meta - uses: crazy-max/ghaction-docker-meta@v1 - with: - images: quay.io/wire/poll-bot - - # setup docker actions https://github.com/docker/build-push-action - - name: Set up QEMU - uses: docker/setup-qemu-action@v1 - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v1 - # login to GCR repo - - name: Login to DockerHub - uses: docker/login-action@v1 - with: - registry: quay.io - username: ${{ secrets.QUAY_USERNAME }} - password: ${{ secrets.QUAY_PASSWORD }} - - - name: Build and push - id: docker_build - uses: docker/build-push-action@v2 - with: - tags: ${{ steps.docker_meta.outputs.tags }} - labels: ${{ steps.docker_meta.outputs.labels }} - push: true - build-args: | - release_version=${{ env.RELEASE_VERSION }} - - # Send webhook to Wire using Slack Bot - - name: Webhook to Wire - uses: 8398a7/action-slack@v2 - with: - status: ${{ job.status }} - author_name: ${{ env.SERVICE_NAME }} Quay Production Publish - env: - SLACK_WEBHOOK_URL: ${{ secrets.WEBHOOK_RELEASE }} - # Send message only if previous step failed - if: always() diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml new file mode 100644 index 0000000..0ef1c18 --- /dev/null +++ b/.github/workflows/pull-request.yml @@ -0,0 +1,32 @@ +name: Build + +on: + workflow_dispatch: + pull_request: + +jobs: + tests: + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: 'zulu' + java-version: '17' + - name: Lint + run: | + ./gradlew ktlintCheck + - name: Detekt + run: | + ./gradlew detekt + - name: Build + run: | + ./gradlew build --info + - name: Store reports + if: failure() + uses: actions/upload-artifact@v4 + with: + name: reports + path: | + **/build/reports/ + **/build/test-results/ diff --git a/.github/workflows/quay.yml b/.github/workflows/quay.yml deleted file mode 100644 index 0f8d033..0000000 --- a/.github/workflows/quay.yml +++ /dev/null @@ -1,55 +0,0 @@ -name: Quay Deployment - -on: - # manual dispatch - workflow_dispatch: - inputs: - tag: - description: 'Docker image tag.' - required: true -jobs: - publish: - name: Deploy to staging - runs-on: ubuntu-20.04 - steps: - - uses: actions/checkout@v2 - - # extract metadata for labels https://github.com/crazy-max/ghaction-docker-meta - - name: Docker meta - id: docker_meta - uses: crazy-max/ghaction-docker-meta@v1 - with: - images: quay.io/wire/poll-bot - - # setup docker actions https://github.com/docker/build-push-action - - name: Set up QEMU - uses: docker/setup-qemu-action@v1 - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v1 - # login to GCR repo - - name: Login to DockerHub - uses: docker/login-action@v1 - with: - registry: quay.io - username: ${{ secrets.QUAY_USERNAME }} - password: ${{ secrets.QUAY_PASSWORD }} - - - name: Build and push - id: docker_build - uses: docker/build-push-action@v2 - with: - tags: quay.io/wire/poll-bot:${{ github.event.inputs.tag }} - labels: ${{ steps.docker_meta.outputs.labels }} - push: true - build-args: | - release_version=${{ github.event.inputs.tag }} - # Send webhook to Wire using Slack Bot - - name: Webhook to Wire - uses: 8398a7/action-slack@v2 - with: - status: ${{ job.status }} - author_name: Poll Bot Quay Custom Tag Pipeline - env: - SLACK_WEBHOOK_URL: ${{ secrets.WEBHOOK_CI }} - # Send message only if previous step failed - if: always() diff --git a/.github/workflows/staging.yml b/.github/workflows/staging.yml deleted file mode 100644 index 0eae132..0000000 --- a/.github/workflows/staging.yml +++ /dev/null @@ -1,101 +0,0 @@ -name: Staging Deployment - -on: - push: - branches: - - staging - -env: - DOCKER_IMAGE: wire-bot/poll - SERVICE_NAME: polls - -jobs: - publish: - name: Deploy to staging - runs-on: ubuntu-20.04 - steps: - - uses: actions/checkout@v2 - - # use latest tag as release version in the docker container - - name: Set Release Version - run: echo "RELEASE_VERSION=${GITHUB_SHA}" >> $GITHUB_ENV - - # extract metadata for labels https://github.com/crazy-max/ghaction-docker-meta - - name: Docker meta - id: docker_meta - uses: crazy-max/ghaction-docker-meta@v1 - with: - images: eu.gcr.io/${{ env.DOCKER_IMAGE }} - - # setup docker actions https://github.com/docker/build-push-action - - name: Set up QEMU - uses: docker/setup-qemu-action@v1 - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v1 - # login to GCR repo - - name: Login to DockerHub - uses: docker/login-action@v1 - with: - registry: eu.gcr.io - username: _json_key - password: ${{ secrets.GCR_ACCESS_JSON }} - - - name: Build and push - id: docker_build - uses: docker/build-push-action@v2 - with: - tags: ${{ steps.docker_meta.outputs.tags }} - labels: ${{ steps.docker_meta.outputs.labels }} - push: true - build-args: | - release_version=${{ env.RELEASE_VERSION }} - - - name: Enable auth plugin - run: | - echo "USE_GKE_GCLOUD_AUTH_PLUGIN=True" >> $GITHUB_ENV - # Auth to GKE - - name: Authenticate to GKE - uses: google-github-actions/auth@v1 - with: - project_id: wire-bot - credentials_json: ${{ secrets.GKE_SA_KEY }} - service_account: kubernetes-deployment-agent@wire-bot.iam.gserviceaccount.com - - # Setup gcloud CLI - - name: Set up Cloud SDK - uses: google-github-actions/setup-gcloud@v1 - - # Prepare components - - name: Prepare gcloud components - run: | - gcloud components install gke-gcloud-auth-plugin - gcloud components update - gcloud --quiet auth configure-docker - - # Get the GKE credentials so we can deploy to the cluster - - name: Obtain k8s credentials - env: - GKE_CLUSTER: dagobah - GKE_ZONE: europe-west1-c - run: | - gcloud container clusters get-credentials "$GKE_CLUSTER" --zone "$GKE_ZONE" - - # K8s is set up, deploy the app - - name: Deploy the Service - env: - SERVICE: ${{ env.SERVICE_NAME }} - run: | - kubectl delete pod -l app=$SERVICE -n staging - kubectl describe pod -l app=$SERVICE -n staging - - # Send webhook to Wire using Slack Bot - - name: Webhook to Wire - uses: 8398a7/action-slack@v2 - with: - status: ${{ job.status }} - author_name: ${{ env.SERVICE_NAME }} staging pipeline - env: - SLACK_WEBHOOK_URL: ${{ secrets.WEBHOOK_CI }} - # Send message only if previous step failed - if: always() - diff --git a/build.gradle.kts b/build.gradle.kts index fdd6482..87db778 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,7 +1,11 @@ +import org.jlleitschuh.gradle.ktlint.reporter.ReporterType + plugins { - kotlin("jvm") version "1.5.30" + kotlin("jvm") version "2.1.20" application distribution + id("org.jlleitschuh.gradle.ktlint") version "12.2.0" + id("io.gitlab.arturbosch.detekt") version "1.23.7" id("net.nemerosa.versioning") version "3.1.0" } @@ -69,48 +73,57 @@ dependencies { implementation("org.flywaydb", "flyway-core", "7.8.2") } -tasks { - val jvmTarget = "1.8" - compileKotlin { - kotlinOptions.jvmTarget = jvmTarget - } - compileJava { - targetCompatibility = jvmTarget +ktlint { + verbose.set(true) + outputToConsole.set(true) + coloredOutput.set(true) + reporters { + reporter(ReporterType.CHECKSTYLE) + reporter(ReporterType.JSON) + reporter(ReporterType.HTML) } - compileTestKotlin { - kotlinOptions.jvmTarget = jvmTarget - } - compileTestJava { - targetCompatibility = jvmTarget + filter { + exclude { element -> + element.file.path.contains("generated/") + } } +} - distTar { - archiveFileName.set("app.tar") - } +detekt { + toolVersion = "1.23.7" + config.setFrom(file("$rootDir/config/detekt/detekt.yml")) + baseline = file("$rootDir/config/detekt/baseline.xml") + parallel = true + buildUponDefaultConfig = true + source.setFrom("src/main/kotlin") +} - withType { - useJUnitPlatform() - } +kotlin { + jvmToolchain(17) +} - register("fatJar") { - manifest { - attributes["Main-Class"] = mClass - } - duplicatesStrategy = DuplicatesStrategy.EXCLUDE - archiveFileName.set("polls.jar") - from(configurations.runtimeClasspath.get().map { if (it.isDirectory) it else zipTree(it) }) - from(sourceSets.main.get().output) +tasks.distTar { + archiveFileName.set("app.tar") +} + +tasks.test { + useJUnitPlatform() +} + +tasks.register("fatJar") { + manifest { + attributes["Main-Class"] = mClass } + duplicatesStrategy = DuplicatesStrategy.EXCLUDE + archiveFileName.set("polls.jar") + from(configurations.runtimeClasspath.get().map { if (it.isDirectory) it else zipTree(it) }) + from(sourceSets.main.get().output) +} - register("resolveDependencies") { - doLast { - project.allprojects.forEach { subProject -> - with(subProject) { - buildscript.configurations.forEach { if (it.isCanBeResolved) it.resolve() } - configurations.compileClasspath.get().resolve() - configurations.testCompileClasspath.get().resolve() - } - } - } +tasks.register("resolveDependencies") { + doLast { + buildscript.configurations.forEach { if (it.isCanBeResolved) it.resolve() } + configurations.compileClasspath.get().resolve() + configurations.testCompileClasspath.get().resolve() } } diff --git a/config/detekt/baseline.xml b/config/detekt/baseline.xml new file mode 100644 index 0000000..f8696c0 --- /dev/null +++ b/config/detekt/baseline.xml @@ -0,0 +1,8 @@ + + + + + CyclomaticComplexMethod:MessagesHandlingService.kt$MessagesHandlingService$private suspend fun handleText( token: String, message: Message ): Boolean + SpreadOperator:InputParser.kt$InputParser$(*delimiters) + + diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.yml new file mode 100644 index 0000000..ae69534 --- /dev/null +++ b/config/detekt/detekt.yml @@ -0,0 +1,783 @@ +build: + maxIssues: 0 + excludeCorrectable: false + weights: + # complexity: 2 + # LongParameterList: 1 + # style: 1 + # comments: 1 + +config: + validation: true + warningsAsErrors: false + checkExhaustiveness: 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' + # - 'MdOutputReport' + # - 'SarifOutputReport' + +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<])|([.?!:]$)' + KDocReferencesNonPublicProperty: + active: false + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**'] + OutdatedDocumentation: + active: false + matchTypeParameters: true + matchDeclarationsOrder: true + allowParamOnConstructorProperties: false + UndocumentedPublicClass: + active: false + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**'] + searchInNestedClass: true + searchInInnerClass: true + searchInInnerObject: true + searchInInnerInterface: true + searchInProtectedClass: false + UndocumentedPublicFunction: + active: false + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**'] + searchProtectedFunction: false + UndocumentedPublicProperty: + active: false + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**'] + searchProtectedProperty: false + +complexity: + active: true + CognitiveComplexMethod: + active: false + threshold: 15 + ComplexCondition: + active: true + threshold: 4 + ComplexInterface: + active: false + threshold: 10 + includeStaticDeclarations: false + includePrivateDeclarations: false + ignoreOverloaded: false + CyclomaticComplexMethod: + 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 + NestedScopeFunctions: + active: false + threshold: 1 + functions: + - 'kotlin.apply' + - 'kotlin.run' + - 'kotlin.with' + - 'kotlin.let' + - 'kotlin.also' + ReplaceSafeCallChainWithRun: + active: false + StringLiteralDuplication: + active: false + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**'] + threshold: 3 + ignoreAnnotation: true + excludeStringsWithLessThan5Characters: true + ignoreStringsRegex: '$^' + TooManyFunctions: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**'] + thresholdInFiles: 11 + thresholdInClasses: 11 + thresholdInInterfaces: 11 + thresholdInObjects: 11 + thresholdInEnums: 11 + ignoreDeprecated: false + ignorePrivate: false + ignoreOverridden: false + ignoreAnnotatedFunctions: [] + +coroutines: + active: true + GlobalCoroutineUsage: + active: false + InjectDispatcher: + active: true + dispatcherNames: + - 'IO' + - 'Default' + - 'Unconfined' + RedundantSuspendModifier: + active: true + SleepInsteadOfDelay: + active: true + SuspendFunSwallowedCancellation: + active: false + SuspendFunWithCoroutineScopeReceiver: + active: false + SuspendFunWithFlowReturnType: + active: true + +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: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/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/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**'] + exceptions: + - 'ArrayIndexOutOfBoundsException' + - 'Exception' + - 'IllegalArgumentException' + - 'IllegalMonitorStateException' + - 'IllegalStateException' + - 'IndexOutOfBoundsException' + - 'NullPointerException' + - 'RuntimeException' + - 'Throwable' + ThrowingNewInstanceOfSameException: + active: true + TooGenericExceptionCaught: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/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)' + 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: '$^' + 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/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**'] + functionPattern: '[a-z][a-zA-Z0-9]*' + excludeClassPattern: '$^' + FunctionParameterNaming: + active: true + parameterPattern: '[a-z][A-Za-z0-9]*' + excludeClassPattern: '$^' + InvalidPackageDeclaration: + active: true + 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: true + 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: '$^' + +performance: + active: true + ArrayPrimitive: + active: true + CouldBeSequence: + active: false + threshold: 3 + ForEachOnRange: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**'] + SpreadOperator: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**'] + UnnecessaryPartOfBinaryExpression: + active: false + UnnecessaryTemporaryInstantiation: + active: true + +potential-bugs: + active: true + AvoidReferentialEquality: + active: true + forbiddenTypePatterns: + - 'kotlin.String' + CastNullableToNonNullableType: + active: false + CastToNullableType: + active: false + Deprecation: + active: false + DontDowncastCollectionTypes: + active: false + DoubleMutabilityForCollection: + active: true + 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' + ElseCaseInsteadOfExhaustiveWhen: + active: false + ignoredSubjectTypes: [] + EqualsAlwaysReturnsTrueOrFalse: + active: true + EqualsWithHashCodeExist: + active: true + ExitOutsideMain: + active: false + ExplicitGarbageCollectionCall: + active: true + HasPlatformType: + active: true + IgnoredReturnValue: + active: true + restrictToConfig: true + returnValueAnnotations: + - 'CheckResult' + - '*.CheckResult' + - 'CheckReturnValue' + - '*.CheckReturnValue' + ignoreReturnValueAnnotations: + - 'CanIgnoreReturnValue' + - '*.CanIgnoreReturnValue' + returnValueTypes: + - 'kotlin.sequences.Sequence' + - 'kotlinx.coroutines.flow.*Flow' + - 'java.util.stream.*Stream' + 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/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**'] + ignoreOnClassesPattern: '' + MapGetWithNotNullAssertionOperator: + active: true + MissingPackageDeclaration: + active: false + excludes: ['**/*.kts'] + NullCheckOnMutableProperty: + active: false + NullableToStringCall: + active: false + PropertyUsedBeforeDeclaration: + active: false + UnconditionalJumpStatementInLoop: + active: false + UnnecessaryNotNullCheck: + active: false + UnnecessaryNotNullOperator: + active: true + UnnecessarySafeCall: + active: true + UnreachableCatchBlock: + active: true + UnreachableCode: + active: true + UnsafeCallOnNullableType: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**'] + UnsafeCast: + active: true + UnusedUnaryOperator: + active: true + UselessPostfixExpression: + active: true + WrongEqualsTypeParameter: + active: true + +style: + active: true + AlsoCouldBeApply: + active: false + BracesOnIfStatements: + active: false + singleLine: 'never' + multiLine: 'always' + BracesOnWhenStatements: + active: false + singleLine: 'necessary' + multiLine: 'consistent' + CanBeNonNullable: + active: false + CascadingCallWrapping: + active: false + includeElvis: true + ClassOrdering: + active: false + CollapsibleIfStatements: + active: false + DataClassContainsFunctions: + active: false + conversionFunctionPrefix: + - 'to' + allowOperators: false + DataClassShouldBeImmutable: + active: false + DestructuringDeclarationWithTooManyEntries: + active: true + maxDestructuringEntries: 3 + DoubleNegativeLambda: + active: false + negativeFunctions: + - reason: 'Use `takeIf` instead.' + value: 'takeUnless' + - reason: 'Use `all` instead.' + value: 'none' + negativeFunctionNameParts: + - 'not' + - 'non' + EqualsNullCall: + active: true + EqualsOnSignatureLine: + active: false + ExplicitCollectionElementAccessMethod: + active: false + ExplicitItLambdaParameter: + active: true + ExpressionBodySyntax: + active: false + includeLineWrapping: false + ForbiddenAnnotation: + active: false + annotations: + - reason: 'it is a java annotation. Use `Suppress` instead.' + value: 'java.lang.SuppressWarnings' + - reason: 'it is a java annotation. Use `kotlin.Deprecated` instead.' + value: 'java.lang.Deprecated' + - reason: 'it is a java annotation. Use `kotlin.annotation.MustBeDocumented` instead.' + value: 'java.lang.annotation.Documented' + - reason: 'it is a java annotation. Use `kotlin.annotation.Target` instead.' + value: 'java.lang.annotation.Target' + - reason: 'it is a java annotation. Use `kotlin.annotation.Retention` instead.' + value: 'java.lang.annotation.Retention' + - reason: 'it is a java annotation. Use `kotlin.annotation.Repeatable` instead.' + value: 'java.lang.annotation.Repeatable' + - reason: 'Kotlin does not support @Inherited annotation, see https://youtrack.jetbrains.com/issue/KT-22265' + value: 'java.lang.annotation.Inherited' + ForbiddenComment: + active: false + comments: + - reason: 'Forbidden FIXME todo marker in comment, please fix the problem.' + value: 'FIXME:' + - reason: 'Forbidden STOPSHIP todo marker in comment, please address the problem before shipping the code.' + value: 'STOPSHIP:' + allowedPatterns: '' + ForbiddenImport: + active: false + imports: [] + forbiddenPatterns: '' + ForbiddenMethodCall: + active: false + methods: + - reason: 'print does not allow you to configure the output stream. Use a logger instead.' + value: 'kotlin.io.print' + - reason: 'println does not allow you to configure the output stream. Use a logger instead.' + value: 'kotlin.io.println' + ForbiddenSuppress: + active: false + rules: [] + ForbiddenVoid: + active: true + ignoreOverridden: false + ignoreUsageInGenerics: false + FunctionOnlyReturningConstant: + active: true + ignoreOverridableFunction: true + ignoreActualFunction: true + excludedFunctions: [] + LoopWithTooManyJumpStatements: + active: true + maxJumpCount: 1 + MagicNumber: + active: true + excludes: ['**/test/**', '**/commonTest/**', '**/jvmTest/**', '**/*.kts'] + 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 + MandatoryBracesLoops: + active: false + MaxChainedCallsOnSameLine: + active: false + maxChainedCalls: 5 + MaxLineLength: + active: true + maxLineLength: 120 + excludePackageStatements: true + excludeImportStatements: true + excludeCommentStatements: false + excludeRawStrings: true + MayBeConst: + active: true + ModifierOrder: + active: true + MultilineLambdaItParameter: + active: false + MultilineRawStringIndentation: + active: false + indentSize: 4 + trimmingMethods: + - 'trimIndent' + - 'trimMargin' + NestedClassesVisibility: + active: true + NewLineAtEndOfFile: + active: true + NoTabs: + active: false + NullableBooleanCheck: + active: false + ObjectLiteralToLambda: + active: true + OptionalAbstractKeyword: + active: true + OptionalUnit: + active: false + PreferToOverPairSyntax: + active: false + ProtectedMemberInFinalClass: + active: true + RedundantExplicitType: + active: false + RedundantHigherOrderMapUsage: + active: true + 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 + StringShouldBeRawString: + active: false + maxEscapedCharacterCount: 2 + ignoredCharacters: [] + ThrowsCount: + active: true + max: 2 + excludeGuardClauses: false + TrailingWhitespace: + active: false + TrimMultilineRawString: + active: false + trimmingMethods: + - 'trimIndent' + - 'trimMargin' + UnderscoresInNumericLiterals: + active: false + acceptableLength: 4 + allowNonStandardGrouping: false + UnnecessaryAbstractClass: + active: true + UnnecessaryAnnotationUseSiteTarget: + active: false + UnnecessaryApply: + active: true + UnnecessaryBackticks: + active: false + UnnecessaryBracesAroundTrailingLambda: + active: false + UnnecessaryFilter: + active: true + UnnecessaryInheritance: + active: true + UnnecessaryInnerClass: + active: false + UnnecessaryLet: + active: false + UnnecessaryParentheses: + active: false + allowForUnclearPrecedence: false + UntilInsteadOfRangeTo: + active: false + UnusedImports: + active: false + UnusedParameter: + active: true + allowedNames: 'ignored|expected' + UnusedPrivateClass: + active: true + UnusedPrivateMember: + active: true + allowedNames: '' + UnusedPrivateProperty: + active: true + allowedNames: '_|ignored|expected|serialVersionUID' + UseAnyOrNoneInsteadOfFind: + active: true + UseArrayLiteralsInAnnotations: + active: true + UseCheckNotNull: + active: true + UseCheckOrError: + active: true + UseDataClass: + active: false + allowVars: false + UseEmptyCounterpart: + active: false + UseIfEmptyOrIfBlank: + active: false + UseIfInsteadOfWhen: + active: false + ignoreWhenContainingVariableDeclaration: false + UseIsNullOrEmpty: + active: true + UseLet: + active: false + UseOrEmpty: + active: true + UseRequire: + active: true + UseRequireNotNull: + active: true + UseSumOfInsteadOfFlatMapSize: + active: false + UselessCallOnNotNull: + active: true + UtilityClassWithPublicConstructor: + active: true + VarCouldBeVal: + active: true + ignoreLateinitVar: false + WildcardImport: + active: true + excludeImports: + - 'java.util.*' diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e708b1c..7454180 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index ffed3a2..d6e308a 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 4f906e0..1b6c787 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,67 +17,101 @@ # ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` +APP_BASE_NAME=${0##*/} # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar @@ -87,9 +121,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -98,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" + JAVACMD=java which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the @@ -106,80 +140,95 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=`expr $i + 1` + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/settings.gradle.kts b/settings.gradle.kts index a3ce49f..7e45544 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,2 +1 @@ rootProject.name = "polls" - diff --git a/src/main/kotlin/com/wire/bots/polls/PollBot.kt b/src/main/kotlin/com/wire/bots/polls/PollBot.kt index cf1f9fe..1d3185a 100644 --- a/src/main/kotlin/com/wire/bots/polls/PollBot.kt +++ b/src/main/kotlin/com/wire/bots/polls/PollBot.kt @@ -1,10 +1,10 @@ package com.wire.bots.polls import com.wire.bots.polls.setup.init -import io.ktor.application.* -import io.ktor.server.engine.* -import io.ktor.server.netty.* +import io.ktor.application.Application +import io.ktor.server.engine.embeddedServer +import io.ktor.server.netty.Netty fun main() { - embeddedServer(Netty, 8080, module = Application::init).start() + embeddedServer(Netty, port = 8080, module = Application::init).start() } diff --git a/src/main/kotlin/com/wire/bots/polls/dao/DaoConstants.kt b/src/main/kotlin/com/wire/bots/polls/dao/DaoConstants.kt new file mode 100644 index 0000000..7ebca41 --- /dev/null +++ b/src/main/kotlin/com/wire/bots/polls/dao/DaoConstants.kt @@ -0,0 +1,5 @@ +package com.wire.bots.polls.dao + +const val UUID_LENGTH = 36 + +const val OPTION_LENGTH = 256 diff --git a/src/main/kotlin/com/wire/bots/polls/dao/DatabaseSetup.kt b/src/main/kotlin/com/wire/bots/polls/dao/DatabaseSetup.kt index 89c99aa..4ad7026 100644 --- a/src/main/kotlin/com/wire/bots/polls/dao/DatabaseSetup.kt +++ b/src/main/kotlin/com/wire/bots/polls/dao/DatabaseSetup.kt @@ -8,7 +8,6 @@ import org.jetbrains.exposed.sql.transactions.transaction * Object with methods for managing the database. */ object DatabaseSetup { - /** * Connect bot to the database via provided credentials. * @@ -25,11 +24,12 @@ object DatabaseSetup { /** * Returns true if the bot is connected to database */ - fun isConnected() = runCatching { - // execute simple query to verify whether the db is connected - // if the transaction throws exception, database is not connected - transaction { - this.connection.isClosed - } - }.isSuccess + fun isConnected() = + runCatching { + // execute simple query to verify whether the db is connected + // if the transaction throws exception, database is not connected + transaction { + this.connection.isClosed + } + }.isSuccess } diff --git a/src/main/kotlin/com/wire/bots/polls/dao/Mentions.kt b/src/main/kotlin/com/wire/bots/polls/dao/Mentions.kt index b970f9a..8f8adcb 100644 --- a/src/main/kotlin/com/wire/bots/polls/dao/Mentions.kt +++ b/src/main/kotlin/com/wire/bots/polls/dao/Mentions.kt @@ -10,12 +10,12 @@ object Mentions : IntIdTable("mentions") { /** * Id of the poll. */ - val pollId: Column = varchar("poll_id", 36) references Polls.id + val pollId: Column = varchar("poll_id", UUID_LENGTH) references Polls.id /** * If of user that is mentioned. */ - val userId: Column = varchar("user_id", 36) + val userId: Column = varchar("user_id", UUID_LENGTH) /** * Where mention begins. diff --git a/src/main/kotlin/com/wire/bots/polls/dao/PollOptions.kt b/src/main/kotlin/com/wire/bots/polls/dao/PollOptions.kt index d68db3f..ff1380d 100644 --- a/src/main/kotlin/com/wire/bots/polls/dao/PollOptions.kt +++ b/src/main/kotlin/com/wire/bots/polls/dao/PollOptions.kt @@ -7,11 +7,10 @@ import org.jetbrains.exposed.sql.Table * Poll options. */ object PollOptions : Table("poll_option") { - /** * Id of the poll this option is for. UUID. */ - val pollId: Column = varchar("poll_id", 36) references Polls.id + val pollId: Column = varchar("poll_id", UUID_LENGTH) references Polls.id /** * Option order or option id. @@ -21,7 +20,7 @@ object PollOptions : Table("poll_option") { /** * Option content, the text inside the button/choice. */ - val optionContent: Column = varchar("option_content", 256) + val optionContent: Column = varchar("option_content", OPTION_LENGTH) override val primaryKey: PrimaryKey get() = PrimaryKey(pollId, optionOrder) diff --git a/src/main/kotlin/com/wire/bots/polls/dao/PollRepository.kt b/src/main/kotlin/com/wire/bots/polls/dao/PollRepository.kt index 0df80d7..74fe043 100644 --- a/src/main/kotlin/com/wire/bots/polls/dao/PollRepository.kt +++ b/src/main/kotlin/com/wire/bots/polls/dao/PollRepository.kt @@ -19,14 +19,18 @@ import pw.forst.katlib.mapToSet * Simple repository for handling database transactions on one place. */ class PollRepository { - private companion object : KLogging() /** * Saves given poll to database and returns its id (same as the [pollId] parameter, * but this design supports fluent style in the services. */ - suspend fun savePoll(poll: PollDto, pollId: String, userId: String, botSelfId: String) = newSuspendedTransaction { + suspend fun savePoll( + poll: PollDto, + pollId: String, + userId: String, + botSelfId: String + ) = newSuspendedTransaction { Polls.insert { it[id] = pollId it[ownerId] = userId @@ -56,78 +60,90 @@ class PollRepository { /** * Returns question for given poll Id. If the poll does not exist, null is returned. */ - suspend fun getPollQuestion(pollId: String) = newSuspendedTransaction { - (Polls leftJoin Mentions) - .select { Polls.id eq pollId } - .groupBy( - { it[Polls.body] }, - { - if (it.getOrNull(Mentions.userId) != null) { - Mention( - userId = it[Mentions.userId], - offset = it[Mentions.offset], - length = it[Mentions.length] - ) - } else { - null + suspend fun getPollQuestion(pollId: String) = + newSuspendedTransaction { + (Polls leftJoin Mentions) + .select { Polls.id eq pollId } + .groupBy( + { it[Polls.body] }, + { + if (it.getOrNull(Mentions.userId) != null) { + Mention( + userId = it[Mentions.userId], + offset = it[Mentions.offset], + length = it[Mentions.length] + ) + } else { + null + } } - } - ).map { (pollBody, mentions) -> - Question(body = pollBody, mentions = mentions.filterNotNull()) - }.singleOrNull() - } + ).map { (pollBody, mentions) -> + Question(body = pollBody, mentions = mentions.filterNotNull()) + }.singleOrNull() + } /** * Register new vote to the poll. If the poll with provided pollId does not exist, * database contains foreign key to an option and poll so the SQL exception is thrown. */ - suspend fun vote(pollAction: PollAction) = newSuspendedTransaction { - Votes.insertOrUpdate(Votes.pollId, Votes.userId) { - it[pollId] = pollAction.pollId - it[pollOption] = pollAction.optionId - it[userId] = pollAction.userId + suspend fun vote(pollAction: PollAction) = + newSuspendedTransaction { + Votes.insertOrUpdate(Votes.pollId, Votes.userId) { + it[pollId] = pollAction.pollId + it[pollOption] = pollAction.optionId + it[userId] = pollAction.userId + } } - } /** * Retrieves stats for given pollId. * * Offset/option/button content as keys and count of the votes as values. */ - suspend fun stats(pollId: String) = newSuspendedTransaction { - PollOptions.join(Votes, JoinType.LEFT, - additionalConstraint = { - (Votes.pollId eq PollOptions.pollId) and (Votes.pollOption eq PollOptions.optionOrder) - } - ).slice(PollOptions.optionOrder, PollOptions.optionContent, Votes.userId) - .select { PollOptions.pollId eq pollId } - // left join so userId can be null - .groupBy({ it[PollOptions.optionOrder] to it[PollOptions.optionContent] }, { it.getOrNull(Votes.userId) }) - .mapValues { (_, votingUsers) -> votingUsers.count { !it.isNullOrBlank() } } - } + suspend fun stats(pollId: String) = + newSuspendedTransaction { + PollOptions + .join( + Votes, + JoinType.LEFT, + additionalConstraint = { + (Votes.pollId eq PollOptions.pollId) and + (Votes.pollOption eq PollOptions.optionOrder) + } + ).slice(PollOptions.optionOrder, PollOptions.optionContent, Votes.userId) + .select { PollOptions.pollId eq pollId } + // left join so userId can be null + .groupBy({ + it[PollOptions.optionOrder] to it[PollOptions.optionContent] + }, { it.getOrNull(Votes.userId) }) + .mapValues { (_, votingUsers) -> votingUsers.count { !it.isNullOrBlank() } } + } /** * Returns set of user ids that voted in the poll with given pollId. */ - suspend fun votingUsers(pollId: String) = newSuspendedTransaction { - Votes - .slice(Votes.userId) - .select { Votes.pollId eq pollId } - .mapToSet { it[Votes.userId] } - } + suspend fun votingUsers(pollId: String) = + newSuspendedTransaction { + Votes + .slice(Votes.userId) + .select { Votes.pollId eq pollId } + .mapToSet { it[Votes.userId] } + } /** * Returns set of user ids that voted in the poll with given pollId. */ - suspend fun getLatestForBot(botId: String) = newSuspendedTransaction { - Polls.slice(Polls.id) - // it must be for single bot - .select { Polls.botId eq botId } - // such as latest is on top - .orderBy(Polls.created to SortOrder.DESC) - // select just one - .limit(1) - .singleOrNull() - ?.get(Polls.id) - } + suspend fun getLatestForBot(botId: String) = + newSuspendedTransaction { + Polls + .slice(Polls.id) + // it must be for single bot + .select { Polls.botId eq botId } + // such as latest is on top + .orderBy(Polls.created to SortOrder.DESC) + // select just one + .limit(1) + .singleOrNull() + ?.get(Polls.id) + } } diff --git a/src/main/kotlin/com/wire/bots/polls/dao/Polls.kt b/src/main/kotlin/com/wire/bots/polls/dao/Polls.kt index 049e23c..5617aea 100644 --- a/src/main/kotlin/com/wire/bots/polls/dao/Polls.kt +++ b/src/main/kotlin/com/wire/bots/polls/dao/Polls.kt @@ -12,19 +12,17 @@ object Polls : Table("polls") { /** * Id of the poll. UUID. */ - val id: Column = varchar("id", 36).uniqueIndex() + val id: Column = varchar("id", UUID_LENGTH).uniqueIndex() /** * Id of the user who created this poll. UUID. */ - val ownerId: Column = varchar("owner_id", 36) - + val ownerId: Column = varchar("owner_id", UUID_LENGTH) /** * Id of the bot that created this poll. UUID. */ - val botId: Column = varchar("bot_id", 36) - + val botId: Column = varchar("bot_id", UUID_LENGTH) /** * Determines whether is the pool active and whether new votes should be accepted. diff --git a/src/main/kotlin/com/wire/bots/polls/dao/Votes.kt b/src/main/kotlin/com/wire/bots/polls/dao/Votes.kt index 71e9323..efd74f9 100644 --- a/src/main/kotlin/com/wire/bots/polls/dao/Votes.kt +++ b/src/main/kotlin/com/wire/bots/polls/dao/Votes.kt @@ -10,7 +10,7 @@ object Votes : Table("votes") { /** * Id of the poll. */ - val pollId: Column = varchar("poll_id", 36) + val pollId: Column = varchar("poll_id", UUID_LENGTH) /** * Id of the option. @@ -20,7 +20,7 @@ object Votes : Table("votes") { /** * User who voted for this option. */ - val userId: Column = varchar("user_id", 36) + val userId: Column = varchar("user_id", UUID_LENGTH) override val primaryKey: PrimaryKey get() = PrimaryKey(pollId, userId) diff --git a/src/main/kotlin/com/wire/bots/polls/dto/PollAction.kt b/src/main/kotlin/com/wire/bots/polls/dto/PollAction.kt index 5e0695a..dad595b 100644 --- a/src/main/kotlin/com/wire/bots/polls/dto/PollAction.kt +++ b/src/main/kotlin/com/wire/bots/polls/dto/PollAction.kt @@ -3,4 +3,8 @@ package com.wire.bots.polls.dto /** * Represents poll vote from the user. */ -data class PollAction(val pollId: String, val optionId: Int, val userId: String) +data class PollAction( + val pollId: String, + val optionId: Int, + val userId: String +) diff --git a/src/main/kotlin/com/wire/bots/polls/dto/UsersInput.kt b/src/main/kotlin/com/wire/bots/polls/dto/UsersInput.kt index cd91fde..2939d20 100644 --- a/src/main/kotlin/com/wire/bots/polls/dto/UsersInput.kt +++ b/src/main/kotlin/com/wire/bots/polls/dto/UsersInput.kt @@ -21,6 +21,6 @@ data class UsersInput( */ val mentions: List ) { - //TODO modify this in the future - because we do not want to print decrypted users text to the log + // TODO modify this in the future - because we do not want to print decrypted users text to the log override fun toString(): String = "User: $userId wrote $input" } diff --git a/src/main/kotlin/com/wire/bots/polls/dto/bot/BotMessage.kt b/src/main/kotlin/com/wire/bots/polls/dto/bot/BotMessage.kt index 9ca6c09..cdd08d3 100644 --- a/src/main/kotlin/com/wire/bots/polls/dto/bot/BotMessage.kt +++ b/src/main/kotlin/com/wire/bots/polls/dto/bot/BotMessage.kt @@ -9,4 +9,3 @@ interface BotMessage { */ val type: String } - diff --git a/src/main/kotlin/com/wire/bots/polls/dto/bot/Factories.kt b/src/main/kotlin/com/wire/bots/polls/dto/bot/Factories.kt index 23233d1..6af14ea 100644 --- a/src/main/kotlin/com/wire/bots/polls/dto/bot/Factories.kt +++ b/src/main/kotlin/com/wire/bots/polls/dto/bot/Factories.kt @@ -3,67 +3,97 @@ package com.wire.bots.polls.dto.bot import com.wire.bots.polls.dto.common.Mention import com.wire.bots.polls.dto.common.Text - /** * Creates message for poll. */ -fun newPoll(id: String, body: String, buttons: List, mentions: List = emptyList()): BotMessage = NewPoll( - text = Text(body, mentions), - poll = NewPoll.Poll( - id = id, - buttons = buttons +fun newPoll( + id: String, + body: String, + buttons: List, + mentions: List = emptyList() +): BotMessage = + NewPoll( + text = Text(body, mentions), + poll = NewPoll.Poll( + id = id, + buttons = buttons + ) ) -) /** * Creates message for vote confirmation. */ -fun confirmVote(pollId: String, userId: String, offset: Int): BotMessage = PollVote( - poll = PollVote.Poll( - id = pollId, - userId = userId, - offset = offset +fun confirmVote( + pollId: String, + userId: String, + offset: Int +): BotMessage = + PollVote( + poll = PollVote.Poll( + id = pollId, + userId = userId, + offset = offset + ) ) -) - /** * Creates message which greets the users in the conversation. */ -fun greeting(text: String, mentions: List = emptyList()): BotMessage = text(text, mentions) - +fun greeting( + text: String, + mentions: List = emptyList() +): BotMessage = text(text, mentions) /** * Creates stats (result of the poll) message. */ -fun statsMessage(text: String, mentions: List = emptyList()): BotMessage = text(text, mentions) +fun statsMessage( + text: String, + mentions: List = emptyList() +): BotMessage = text(text, mentions) /** * Creates message notifying user about wrongly used command. */ -fun fallBackMessage(text: String, mentions: List = emptyList()): BotMessage = text(text, mentions) +fun fallBackMessage( + text: String, + mentions: List = emptyList() +): BotMessage = text(text, mentions) /** * Creates good bot message. */ -fun goodBotMessage(text: String, mentions: List = emptyList()): BotMessage = text(text, mentions) +fun goodBotMessage( + text: String, + mentions: List = emptyList() +): BotMessage = text(text, mentions) /** * Creates version message. */ -fun versionMessage(text: String, mentions: List = emptyList()): BotMessage = text(text, mentions) +fun versionMessage( + text: String, + mentions: List = emptyList() +): BotMessage = text(text, mentions) /** * Creates message with help. */ -fun helpMessage(text: String, mentions: List = emptyList()): BotMessage = text(text, mentions) +fun helpMessage( + text: String, + mentions: List = emptyList() +): BotMessage = text(text, mentions) /** * Creates text message. */ -private fun text(text: String, mentions: List): BotMessage = TextMessage( - text = Text( - data = text, - mentions = mentions +private fun text( + text: String, + mentions: List +): BotMessage = + TextMessage( + text = Text( + data = text, + mentions = mentions + ) ) -) diff --git a/src/main/kotlin/com/wire/bots/polls/dto/bot/NewPoll.kt b/src/main/kotlin/com/wire/bots/polls/dto/bot/NewPoll.kt index 275832d..5f16f18 100644 --- a/src/main/kotlin/com/wire/bots/polls/dto/bot/NewPoll.kt +++ b/src/main/kotlin/com/wire/bots/polls/dto/bot/NewPoll.kt @@ -7,7 +7,6 @@ internal data class NewPoll( val poll: Poll, override val type: String = "poll" ) : BotMessage { - internal data class Poll( val id: String, val buttons: List, diff --git a/src/main/kotlin/com/wire/bots/polls/dto/bot/PollVote.kt b/src/main/kotlin/com/wire/bots/polls/dto/bot/PollVote.kt index 767dfd0..f906abb 100644 --- a/src/main/kotlin/com/wire/bots/polls/dto/bot/PollVote.kt +++ b/src/main/kotlin/com/wire/bots/polls/dto/bot/PollVote.kt @@ -4,7 +4,6 @@ internal data class PollVote( val poll: Poll, override val type: String = "poll" ) : BotMessage { - internal data class Poll( val id: String, val offset: Int, diff --git a/src/main/kotlin/com/wire/bots/polls/dto/roman/Message.kt b/src/main/kotlin/com/wire/bots/polls/dto/roman/Message.kt index b93b0e7..a93039e 100644 --- a/src/main/kotlin/com/wire/bots/polls/dto/roman/Message.kt +++ b/src/main/kotlin/com/wire/bots/polls/dto/roman/Message.kt @@ -18,12 +18,10 @@ data class Message( * User who sent a message. */ val userId: String?, - /** * Id of the conversation. */ val conversationId: String?, - /** * Type of the message. */ @@ -64,21 +62,16 @@ data class Message( * Poll object. */ val poll: PollObjectMessage?, - /** * Type of the file */ - val mimeType: String?, - + val mimeType: String? ) { data class Text( val data: String, val mentions: List? - ) { - override fun toString(): String { - return "Text(mentions=$mentions)" - } + override fun toString(): String = "Text(mentions=$mentions)" } /** @@ -93,28 +86,26 @@ data class Message( * Body of the poll - the question. */ val body: String?, - /** * Ordered list of buttons. Position in the list is the ID / offset. */ val buttons: List?, - /** * Id of the button when it was clicked on. */ val offset: Int? ) { - override fun toString(): String { - return "PollObjectMessage(id='$id', buttons=$buttons, offset=$offset)" - } + override fun toString(): String = + "PollObjectMessage(id='$id', buttons=$buttons, offset=$offset)" } /** * Avoid printing out the token by mistake if object is printed. */ - override fun toString(): String { - return "Message(botId='$botId', userId=$userId, conversationId=$conversationId, type='$type', messageId=$messageId, text=$text, refMessageId=$refMessageId, reaction=$reaction, image=$image, handle=$handle, locale=$locale, poll=$poll, mimeType=$mimeType)" - } + override fun toString(): String = + "Message(botId='$botId', userId=$userId, conversationId=$conversationId, type='$type', " + + "messageId=$messageId, text=$text, refMessageId=$refMessageId, reaction=$reaction, " + + "image=$image, handle=$handle, locale=$locale, poll=$poll, mimeType=$mimeType)" } /* JSON from the swagger diff --git a/src/main/kotlin/com/wire/bots/polls/parser/InputParser.kt b/src/main/kotlin/com/wire/bots/polls/parser/InputParser.kt index c3a4771..7f1a737 100644 --- a/src/main/kotlin/com/wire/bots/polls/parser/InputParser.kt +++ b/src/main/kotlin/com/wire/bots/polls/parser/InputParser.kt @@ -7,7 +7,6 @@ import com.wire.bots.polls.dto.common.Mention import mu.KLogging class InputParser { - private companion object : KLogging() { val delimiters = charArrayOf('\"', '“') @@ -15,7 +14,7 @@ class InputParser { } fun parsePoll(userInput: UsersInput): PollDto? { - //TODO currently not supporting char " in the strings + // TODO currently not supporting char " in the strings val inputs = userInput.input .substringAfter("/poll", "") .substringBeforeLast("\"") @@ -37,10 +36,10 @@ class InputParser { ) } - private fun shiftMentions(usersInput: UsersInput): List { val delimiterIndex = usersInput.input.indexOfFirst { delimitersSet.contains(it) } - val emptyCharsInQuestion = usersInput.input.substringAfter(usersInput.input[delimiterIndex]) + val emptyCharsInQuestion = usersInput.input + .substringAfter(usersInput.input[delimiterIndex]) .takeWhile { it == ' ' } .count() diff --git a/src/main/kotlin/com/wire/bots/polls/parser/PollFactory.kt b/src/main/kotlin/com/wire/bots/polls/parser/PollFactory.kt index 6320c09..8c24c2e 100644 --- a/src/main/kotlin/com/wire/bots/polls/parser/PollFactory.kt +++ b/src/main/kotlin/com/wire/bots/polls/parser/PollFactory.kt @@ -9,8 +9,10 @@ import pw.forst.katlib.whenNull /** * Class used for creating the polls from the text. Parsing and creating the poll objects. */ -class PollFactory(private val inputParser: InputParser, private val pollValidation: PollValidation) { - +class PollFactory( + private val inputParser: InputParser, + private val pollValidation: PollValidation +) { private companion object : KLogging() /** @@ -28,8 +30,9 @@ class PollFactory(private val inputParser: InputParser, private val pollValidati poll } else { logger.warn { - "It was not possible to create poll for user input: $usersInput due to errors listed bellow:" + - "$newLine${errors.joinToString(newLine)}" + "It was not possible to create poll for user input: " + + "$usersInput due to errors listed bellow:" + + "$newLine${errors.joinToString(newLine)}" } null } diff --git a/src/main/kotlin/com/wire/bots/polls/parser/PollValidation.kt b/src/main/kotlin/com/wire/bots/polls/parser/PollValidation.kt index 87e027b..33da111 100644 --- a/src/main/kotlin/com/wire/bots/polls/parser/PollValidation.kt +++ b/src/main/kotlin/com/wire/bots/polls/parser/PollValidation.kt @@ -13,16 +13,26 @@ private typealias PollRule = (PollDto) -> String? * Class validating the polls. */ class PollValidation { - private companion object : KLogging() private val questionRules = - listOf { question -> if (question.body.isNotBlank()) null else "The question must not be empty!" } + listOf { question -> + if (question.body.isNotBlank()) null else "The question must not be empty!" + } - private val optionRules = listOf { option -> if (option.isNotBlank()) null else "The option must not be empty!" } + private val optionRules = + listOf { option -> + if (option.isNotBlank()) null else "The option must not be empty!" + } private val pollRules = - listOf { poll -> if (poll.options.isNotEmpty()) null else "There must be at least one option for answering the poll." } + listOf { poll -> + if (poll.options.isNotEmpty()) { + null + } else { + "There must be at least one option for answering the poll." + } + } /** * Validates given poll, returns pair when the boolean signalizes whether the poll is valid or not. @@ -34,6 +44,11 @@ class PollValidation { val questionValidation = questionRules.mapNotNull { it(poll.question) } val optionsValidation = optionRules.flatMap { poll.options.mapNotNull(it) } - return (pollValidation.isEmpty() && questionValidation.isEmpty() && optionsValidation.isEmpty()) to pollValidation + questionValidation + optionsValidation + return ( + pollValidation.isEmpty() && + questionValidation.isEmpty() && + optionsValidation.isEmpty() + ) to + pollValidation + questionValidation + optionsValidation } } diff --git a/src/main/kotlin/com/wire/bots/polls/routing/MessagesRoute.kt b/src/main/kotlin/com/wire/bots/polls/routing/MessagesRoute.kt index 52db64d..b5d5ed2 100644 --- a/src/main/kotlin/com/wire/bots/polls/routing/MessagesRoute.kt +++ b/src/main/kotlin/com/wire/bots/polls/routing/MessagesRoute.kt @@ -5,11 +5,12 @@ import com.wire.bots.polls.services.AuthService import com.wire.bots.polls.services.MessagesHandlingService import com.wire.bots.polls.setup.logging.USER_ID import com.wire.bots.polls.utils.mdc -import io.ktor.application.* -import io.ktor.http.* -import io.ktor.request.* -import io.ktor.response.* -import io.ktor.routing.* +import io.ktor.application.call +import io.ktor.http.HttpStatusCode +import io.ktor.request.receive +import io.ktor.response.respond +import io.ktor.routing.Routing +import io.ktor.routing.post import org.kodein.di.instance import org.kodein.di.ktor.closestDI diff --git a/src/main/kotlin/com/wire/bots/polls/routing/Routing.kt b/src/main/kotlin/com/wire/bots/polls/routing/Routing.kt index f2bcde8..2ff9f08 100644 --- a/src/main/kotlin/com/wire/bots/polls/routing/Routing.kt +++ b/src/main/kotlin/com/wire/bots/polls/routing/Routing.kt @@ -1,7 +1,7 @@ package com.wire.bots.polls.routing import com.wire.bots.polls.utils.createLogger -import io.ktor.routing.* +import io.ktor.routing.Routing internal val routingLogger by lazy { createLogger("RoutingLogger") } diff --git a/src/main/kotlin/com/wire/bots/polls/routing/ServiceRoutes.kt b/src/main/kotlin/com/wire/bots/polls/routing/ServiceRoutes.kt index 17c8268..2d5dfc2 100644 --- a/src/main/kotlin/com/wire/bots/polls/routing/ServiceRoutes.kt +++ b/src/main/kotlin/com/wire/bots/polls/routing/ServiceRoutes.kt @@ -1,10 +1,12 @@ package com.wire.bots.polls.routing import com.wire.bots.polls.dao.DatabaseSetup -import io.ktor.application.* -import io.ktor.http.* -import io.ktor.response.* -import io.ktor.routing.* +import io.ktor.application.call +import io.ktor.http.HttpStatusCode +import io.ktor.response.respond +import io.ktor.routing.Routing +import io.ktor.routing.get +import io.ktor.response.respondTextWriter import io.micrometer.prometheus.PrometheusMeterRegistry import org.kodein.di.instance import org.kodein.di.ktor.closestDI diff --git a/src/main/kotlin/com/wire/bots/polls/services/AuthService.kt b/src/main/kotlin/com/wire/bots/polls/services/AuthService.kt index 4a364c0..c301946 100644 --- a/src/main/kotlin/com/wire/bots/polls/services/AuthService.kt +++ b/src/main/kotlin/com/wire/bots/polls/services/AuthService.kt @@ -1,31 +1,35 @@ package com.wire.bots.polls.services -import io.ktor.http.* +import io.ktor.http.Headers import mu.KLogging import pw.forst.katlib.whenNull /** * Authentication service. */ -class AuthService(private val proxyToken: String) { - +class AuthService( + private val proxyToken: String +) { private companion object : KLogging() { - const val authHeader = "Authorization" - const val bearerPrefix = "Bearer " + const val AUTH_HEADER = "Authorization" + const val BEARER_HEADER = "Bearer " } /** * Validates token. */ - fun isTokenValid(headersGet: () -> Headers) = runCatching { isTokenValid(headersGet()) }.getOrNull() ?: false + fun isTokenValid(headersGet: () -> Headers) = + runCatching { isTokenValid(headersGet()) }.getOrNull() ?: false private fun isTokenValid(headers: Headers): Boolean { - val header = headers[authHeader].whenNull { + val header = headers[AUTH_HEADER].whenNull { logger.info { "Request did not have authorization header." } } ?: return false - return if (!header.startsWith(bearerPrefix)) { + return if (!header.startsWith(BEARER_HEADER)) { false - } else header.substringAfter(bearerPrefix) == proxyToken + } else { + header.substringAfter(BEARER_HEADER) == proxyToken + } } } diff --git a/src/main/kotlin/com/wire/bots/polls/services/ConversationService.kt b/src/main/kotlin/com/wire/bots/polls/services/ConversationService.kt index 43076ff..5b50d07 100644 --- a/src/main/kotlin/com/wire/bots/polls/services/ConversationService.kt +++ b/src/main/kotlin/com/wire/bots/polls/services/ConversationService.kt @@ -11,13 +11,15 @@ import mu.KLogging /** * Provides possibility to check the conversation details. */ -class ConversationService(private val client: HttpClient, config: ProxyConfiguration) { - +class ConversationService( + private val client: HttpClient, + config: ProxyConfiguration +) { private companion object : KLogging() { - const val conversationPath = "/conversation" + const val CONVERSATION_PATH = "/conversation" } - private val endpoint = config.baseUrl appendPath conversationPath + private val endpoint = config.baseUrl appendPath CONVERSATION_PATH /** * Returns the number of members of conversation. diff --git a/src/main/kotlin/com/wire/bots/polls/services/MessagesHandlingService.kt b/src/main/kotlin/com/wire/bots/polls/services/MessagesHandlingService.kt index b821ed1..3147fd3 100644 --- a/src/main/kotlin/com/wire/bots/polls/services/MessagesHandlingService.kt +++ b/src/main/kotlin/com/wire/bots/polls/services/MessagesHandlingService.kt @@ -3,14 +3,13 @@ package com.wire.bots.polls.services import com.wire.bots.polls.dto.PollAction import com.wire.bots.polls.dto.UsersInput import com.wire.bots.polls.dto.roman.Message -import io.ktor.features.* +import io.ktor.features.BadRequestException import mu.KLogging class MessagesHandlingService( private val pollService: PollService, private val userCommunicationService: UserCommunicationService ) { - private companion object : KLogging() suspend fun handle(message: Message) { @@ -18,22 +17,36 @@ class MessagesHandlingService( logger.trace { "Message: $message" } val handled = when (message.type) { - "conversation.bot_request" -> false.also { logger.debug { "Bot was added to conversation." } } - "conversation.bot_removed" -> false.also { logger.debug { "Bot was removed from the conversation." } } + "conversation.bot_request" -> false.also { + logger.debug { "Bot was added to conversation." } + } + "conversation.bot_removed" -> false.also { + logger.debug { "Bot was removed from the conversation." } + } else -> { logger.debug { "Handling type: ${message.type}" } - when { - message.token != null -> tokenAwareHandle(message.token, message) - else -> false.also { logger.warn { "Proxy didn't send token along side the message with type ${message.type}. Message:$message" } } + if (message.token != null) { + tokenAwareHandle(message.token, message) + } else { + logger.warn { + "Proxy didn't send token along side the message " + + "with type ${message.type}. Message:$message" + } + false } } } - logger.debug { if (handled) "Bot reacted to the message" else "Bot didn't react to the message." } + logger.debug { + if (handled) "Bot reacted to the message" else "Bot didn't react to the message." + } logger.debug { "Message handled." } } - private suspend fun tokenAwareHandle(token: String, message: Message): Boolean { + private suspend fun tokenAwareHandle( + token: String, + message: Message + ): Boolean { logger.debug { "Message contains token." } return runCatching { when (message.type) { @@ -46,35 +59,53 @@ class MessagesHandlingService( logger.debug { "New text message received." } handleText(token, message) } - "conversation.new_image" -> true.also { logger.debug { "New image posted to conversation, ignoring." } } + "conversation.new_image" -> true.also { + logger.debug { "New image posted to conversation, ignoring." } + } "conversation.reaction" -> { logger.debug { "Reaction message" } pollService.sendStats( token = token, - pollId = requireNotNull(message.refMessageId) { "Reaction must contain refMessageId" } + pollId = requireNotNull( + message.refMessageId + ) { "Reaction must contain refMessageId" } ) true } "conversation.poll.action" -> { - val poll = requireNotNull(message.poll) { "Reaction to a poll, poll object must be set!" } + val poll = + requireNotNull( + message.poll + ) { "Reaction to a poll, poll object must be set!" } pollService.pollAction( token, PollAction( pollId = poll.id, - optionId = requireNotNull(poll.offset) { "Offset/Option id must be set!" }, - userId = requireNotNull(message.userId) { "UserId of user who sent the message must be set." } + optionId = requireNotNull( + poll.offset + ) { "Offset/Option id must be set!" }, + userId = requireNotNull( + message.userId + ) { "UserId of user who sent the message must be set." } ) ) true } - else -> false.also { logger.warn { "Unknown message type of ${message.type}. Ignoring." } } + else -> false.also { + logger.warn { "Unknown message type of ${message.type}. Ignoring." } + } } }.onFailure { - logger.error(it) { "Exception during handling the message: $message with token $token." } + logger.error( + it + ) { "Exception during handling the message: $message with token $token." } }.getOrThrow() } - private suspend fun handleText(token: String, message: Message): Boolean { + private suspend fun handleText( + token: String, + message: Message + ): Boolean { var handled = true fun ignore(reason: () -> String) { @@ -88,9 +119,16 @@ class MessagesHandlingService( // it is a reply on something refMessageId != null && text != null -> when { // request for stats - text.data.trim().startsWith("/stats") -> pollService.sendStats(token, refMessageId) + text.data.trim().startsWith( + "/stats" + ) -> pollService.sendStats(token, refMessageId) // integer vote where the text contains offset - text.data.trim().toIntOrNull() != null -> vote(token, userId, refMessageId, text.data) + text.data.trim().toIntOrNull() != null -> vote( + token, + userId, + refMessageId, + text.data + ) else -> ignore { "Ignoring the message as it is reply unrelated to the bot" } } // text message with just text @@ -99,14 +137,24 @@ class MessagesHandlingService( when { // poll request trimmed.startsWith("/poll") -> - pollService.createPoll(token, UsersInput(userId, trimmed, text.mentions ?: emptyList()), botId) + pollService.createPoll( + token, + UsersInput( + userId, + trimmed, + text.mentions ?: emptyList() + ), + botId + ) // stats request trimmed.startsWith("/stats") -> pollService.sendStatsForLatest(token, botId) // send version when asked - trimmed.startsWith("/version") -> userCommunicationService.sendVersion(token) + trimmed.startsWith( + "/version" + ) -> userCommunicationService.sendVersion(token) // send version when asked trimmed.startsWith("/help") -> userCommunicationService.sendHelp(token) - // easter egg, good bot is good + // Easter egg, good bot is good trimmed == "good bot" -> userCommunicationService.goodBot(token) else -> ignore { "Ignoring the message, unrecognized command." } } @@ -117,11 +165,18 @@ class MessagesHandlingService( return handled } - private suspend fun vote(token: String, userId: String, refMessageId: String, text: String) = pollService.pollAction( + private suspend fun vote( + token: String, + userId: String, + refMessageId: String, + text: String + ) = pollService.pollAction( token, PollAction( pollId = refMessageId, - optionId = requireNotNull(text.toIntOrNull()) { "Text message must be a valid integer." }, + optionId = requireNotNull( + text.toIntOrNull() + ) { "Text message must be a valid integer." }, userId = userId ) ) diff --git a/src/main/kotlin/com/wire/bots/polls/services/PollService.kt b/src/main/kotlin/com/wire/bots/polls/services/PollService.kt index b2b3109..47bdbdc 100644 --- a/src/main/kotlin/com/wire/bots/polls/services/PollService.kt +++ b/src/main/kotlin/com/wire/bots/polls/services/PollService.kt @@ -9,7 +9,7 @@ import com.wire.bots.polls.parser.PollFactory import mu.KLogging import pw.forst.katlib.whenNull import pw.forst.katlib.whenTrue -import java.util.* +import java.util.UUID /** * Service handling the polls. It communicates with the proxy via [proxySenderService]. @@ -22,74 +22,96 @@ class PollService( private val userCommunicationService: UserCommunicationService, private val statsFormattingService: StatsFormattingService ) { - private companion object : KLogging() /** * Create poll. */ - suspend fun createPoll(token: String, usersInput: UsersInput, botId: String): String? { - val poll = factory.forUserInput(usersInput) + suspend fun createPoll( + token: String, + usersInput: UsersInput, + botId: String + ): String? { + val poll = factory + .forUserInput(usersInput) .whenNull { logger.warn { "It was not possible to create poll." } pollNotParsedFallback(token, usersInput) } ?: return null - val pollId = repository.savePoll(poll, pollId = UUID.randomUUID().toString(), userId = usersInput.userId, botSelfId = botId) + val pollId = repository.savePoll( + poll, + pollId = UUID.randomUUID().toString(), + userId = usersInput.userId, + botSelfId = botId + ) logger.info { "Poll successfully created with id: $pollId" } - proxySenderService.send( - token, - message = newPoll( - id = pollId, - body = poll.question.body, - buttons = poll.options, - mentions = poll.question.mentions - ) - ).whenNull { - logger.error { "It was not possible to send the poll to the Roman!" } - }?.also { (messageId) -> - logger.info { "Poll successfully created with id: $messageId" } - } + proxySenderService + .send( + token, + message = newPoll( + id = pollId, + body = poll.question.body, + buttons = poll.options, + mentions = poll.question.mentions + ) + ).whenNull { + logger.error { "It was not possible to send the poll to the Roman!" } + }?.also { (messageId) -> + logger.info { "Poll successfully created with id: $messageId" } + } return pollId } - - private suspend fun pollNotParsedFallback(token: String, usersInput: UsersInput) { + private suspend fun pollNotParsedFallback( + token: String, + usersInput: UsersInput + ) { usersInput.input.startsWith("/poll").whenTrue { logger.info { "Command started with /poll, sending usage to user." } userCommunicationService.reactionToWrongCommand(token) } - } /** * Record that the user voted. */ - suspend fun pollAction(token: String, pollAction: PollAction) { + suspend fun pollAction( + token: String, + pollAction: PollAction + ) { logger.info { "User voted" } repository.vote(pollAction) logger.info { "Vote registered." } - proxySenderService.send( - token = token, - message = confirmVote( - pollId = pollAction.pollId, - offset = pollAction.optionId, - userId = pollAction.userId - ) - ).whenNull { - logger.error { "It was not possible to send response to vote." } - }?.also { (messageId) -> - logger.info { "Proxy received confirmation for vote under id: $messageId" } - sendStatsIfAllVoted(token, pollAction.pollId) - } + proxySenderService + .send( + token = token, + message = confirmVote( + pollId = pollAction.pollId, + offset = pollAction.optionId, + userId = pollAction.userId + ) + ).whenNull { + logger.error { "It was not possible to send response to vote." } + }?.also { (messageId) -> + logger.info { "Proxy received confirmation for vote under id: $messageId" } + sendStatsIfAllVoted(token, pollAction.pollId) + } } - private suspend fun sendStatsIfAllVoted(token: String, pollId: String) { - val conversationMembersCount = conversationService.getNumberOfConversationMembers(token) - .whenNull { logger.warn { "It was not possible to determine number of conversation members!" } } ?: return + private suspend fun sendStatsIfAllVoted( + token: String, + pollId: String + ) { + val conversationMembersCount = conversationService + .getNumberOfConversationMembers(token) + .whenNull { + logger.warn { "It was not possible to determine number of conversation members!" } + } + ?: return val votedSize = repository.votingUsers(pollId).size @@ -97,21 +119,35 @@ class PollService( logger.info { "All users voted, sending statistics to the conversation." } sendStats(token, pollId, conversationMembersCount) } else { - logger.info { "Users voted: $votedSize, members of conversation: $conversationMembersCount" } + logger.info { + "Users voted: $votedSize, members of conversation: $conversationMembersCount" + } } } /** * Sends statistics about the poll to the proxy. */ - suspend fun sendStats(token: String, pollId: String, conversationMembers: Int? = null) { + suspend fun sendStats( + token: String, + pollId: String, + conversationMembers: Int? = null + ) { logger.debug { "Sending stats for poll $pollId" } - val conversationMembersCount = conversationMembers ?: conversationService.getNumberOfConversationMembers(token) - .whenNull { logger.warn { "It was not possible to determine number of conversation members!" } } + val conversationMembersCount = + conversationMembers ?: conversationService + .getNumberOfConversationMembers(token) + .whenNull { + logger.warn { + "It was not possible to determine number of conversation members!" + } + } logger.debug { "Conversation members: $conversationMembersCount" } - val stats = statsFormattingService.formatStats(pollId, conversationMembersCount) - .whenNull { logger.warn { "It was not possible to format stats for poll $pollId" } } ?: return + val stats = statsFormattingService + .formatStats(pollId, conversationMembersCount) + .whenNull { logger.warn { "It was not possible to format stats for poll $pollId" } } + ?: return proxySenderService.send(token, stats) } @@ -119,7 +155,10 @@ class PollService( /** * Sends stats for latest poll. */ - suspend fun sendStatsForLatest(token: String, botId: String) { + suspend fun sendStatsForLatest( + token: String, + botId: String + ) { logger.debug { "Sending latest stats for bot $botId" } val latest = repository.getLatestForBot(botId).whenNull { diff --git a/src/main/kotlin/com/wire/bots/polls/services/ProxySenderService.kt b/src/main/kotlin/com/wire/bots/polls/services/ProxySenderService.kt index a500b75..8cb3b81 100644 --- a/src/main/kotlin/com/wire/bots/polls/services/ProxySenderService.kt +++ b/src/main/kotlin/com/wire/bots/polls/services/ProxySenderService.kt @@ -10,8 +10,8 @@ import io.ktor.client.request.post import io.ktor.client.request.url import io.ktor.client.statement.HttpStatement import io.ktor.client.statement.readText -import io.ktor.http.* import io.ktor.http.contentType +import io.ktor.http.ContentType import io.ktor.http.isSuccess import mu.KLogging import pw.forst.katlib.createJson @@ -20,43 +20,53 @@ import java.nio.charset.Charset /** * Service responsible for sending requests to the proxy service Roman. */ -class ProxySenderService(private val client: HttpClient, config: ProxyConfiguration) { - +class ProxySenderService( + private val client: HttpClient, + config: ProxyConfiguration +) { private companion object : KLogging() { - const val conversationPath = "/conversation" + const val CONVERSATION_PATH = "/conversation" } - private val conversationEndpoint = config.baseUrl appendPath conversationPath + private val conversationEndpoint = config.baseUrl appendPath CONVERSATION_PATH /** * Send given message with provided token. */ - suspend fun send(token: String, message: BotMessage): Response? { + suspend fun send( + token: String, + message: BotMessage + ): Response? { logger.debug { "Sending: ${createJson(message)}" } - return client.post(body = message) { - url(conversationEndpoint) - contentType(ContentType.Application.Json) - header("Authorization", "Bearer $token") - }.execute { - logger.debug { "Message sent." } - when { - it.status.isSuccess() -> { - it.receive().also { - logger.info { "Message sent successfully: message id: ${it.messageId}" } + return client + .post(body = message) { + url(conversationEndpoint) + contentType(ContentType.Application.Json) + header("Authorization", "Bearer $token") + }.execute { + logger.debug { "Message sent." } + when { + it.status.isSuccess() -> { + it.receive().also { + logger.info { "Message sent successfully: message id: ${it.messageId}" } + } + } + else -> { + val body = it.readText(Charset.defaultCharset()) + logger.error { + "Error in communication with proxy. Status: ${it.status}, body: $body." + } + null } - } - else -> { - val body = it.readText(Charset.defaultCharset()) - logger.error { "Error in communication with proxy. Status: ${it.status}, body: $body." } - null } } - } } } /** * Configuration used to connect to the proxy. */ -data class ProxyConfiguration(val baseUrl: String) +data class ProxyConfiguration( + val baseUrl: String +) diff --git a/src/main/kotlin/com/wire/bots/polls/services/StatsFormattingService.kt b/src/main/kotlin/com/wire/bots/polls/services/StatsFormattingService.kt index 2f65ac9..ca6d64c 100644 --- a/src/main/kotlin/com/wire/bots/polls/services/StatsFormattingService.kt +++ b/src/main/kotlin/com/wire/bots/polls/services/StatsFormattingService.kt @@ -12,7 +12,7 @@ class StatsFormattingService( private val repository: PollRepository ) { private companion object : KLogging() { - const val titlePrefix = "**Results** for poll *\"" + const val TITLE_PREFIX = "**Results** for poll *\"" /** * Maximum number of trailing vote slots to be displayed, considered the most voted option. @@ -24,14 +24,17 @@ class StatsFormattingService( * Prepares message with statistics about the poll to the proxy. * When conversationMembers is null, stats are formatted according to the max votes per option. */ - suspend fun formatStats(pollId: String, conversationMembers: Int?): BotMessage? { + suspend fun formatStats( + pollId: String, + conversationMembers: Int? + ): BotMessage? { val pollQuestion = repository.getPollQuestion(pollId).whenNull { logger.warn { "No poll $pollId exists." } - } ?: return null + } val stats = repository.stats(pollId) - if (stats.isEmpty()) { - logger.info { "There are no data for given pollId." } + stats.ifEmpty { logger.info { "There are no data for given pollId." } } + if (pollQuestion == null || stats.isEmpty()) { return null } @@ -39,7 +42,11 @@ class StatsFormattingService( val options = formatVotes(stats, conversationMembers) return statsMessage( text = "$title$newLine$options", - mentions = pollQuestion.mentions.map { it.copy(offset = it.offset + titlePrefix.length) } + mentions = pollQuestion.mentions.map { + it.copy( + offset = it.offset + TITLE_PREFIX.length + ) + } ) } @@ -63,9 +70,13 @@ class StatsFormattingService( * - ⬛⬛⬛ A (3) * - ⬜⬜⬜ B (1) */ - private fun formatVotes(stats: Map, Int>, conversationMembers: Int?): String { + private fun formatVotes( + stats: Map, Int>, + conversationMembers: Int? + ): String { // we can use assert as the result size is checked - val mostPopularOptionVoteCount = requireNotNull(stats.values.maxOrNull()) { "There were no stats!" } + val mostPopularOptionVoteCount = + requireNotNull(stats.values.maxOrNull()) { "There were no stats!" } val maximumSize = min( conversationMembers ?: Integer.MAX_VALUE, @@ -74,30 +85,41 @@ class StatsFormattingService( return stats .map { (option, votingUsers) -> - VotingOption(if (votingUsers == mostPopularOptionVoteCount) "**" else "*", option.second, votingUsers) + VotingOption( + if (votingUsers == + mostPopularOptionVoteCount + ) { + "**" + } else { + "*" + }, + option.second, + votingUsers + ) }.let { votes -> votes.joinToString(newLine) { it.toString(maximumSize) } } } - private fun prepareTitle(body: String) = "$titlePrefix${body}\"*" - + private fun prepareTitle(body: String) = "$TITLE_PREFIX${body}\"*" } /** * Class used for formatting voting objects. */ -private data class VotingOption(val style: String, val option: String, val votingUsers: Int) { - +private data class VotingOption( + val style: String, + val option: String, + val votingUsers: Int +) { private companion object { - const val notVote = "⚪" - const val vote = "🟢" + const val NOT_VOTE = "⚪" + const val VOTE = "🟢" } fun toString(max: Int): String { - val missingVotes = (0 until max - votingUsers).joinToString("") { notVote } - val votes = (0 until votingUsers).joinToString("") { vote } + val missingVotes = (0 until max - votingUsers).joinToString("") { NOT_VOTE } + val votes = (0 until votingUsers).joinToString("") { VOTE } return "$votes$missingVotes $style$option$style ($votingUsers)" } } - diff --git a/src/main/kotlin/com/wire/bots/polls/services/UserCommunicationService.kt b/src/main/kotlin/com/wire/bots/polls/services/UserCommunicationService.kt index b9dfe2f..a733b58 100644 --- a/src/main/kotlin/com/wire/bots/polls/services/UserCommunicationService.kt +++ b/src/main/kotlin/com/wire/bots/polls/services/UserCommunicationService.kt @@ -15,9 +15,9 @@ class UserCommunicationService( private val proxySenderService: ProxySenderService, private val version: String ) { - private companion object : KLogging() { - const val usage = "To create poll please text: `/poll \"Question\" \"Option 1\" \"Option 2\"`. To display usage write `/help`" + const val USAGE = "To create poll please text: " + + "`/poll \"Question\" \"Option 1\" \"Option 2\"`. To display usage write `/help`" val commands = """ Following commands are available: `/poll "Question" "Option 1" "Option 2"` will create poll @@ -29,12 +29,13 @@ class UserCommunicationService( /** * Sends hello message with instructions to the conversation. */ - suspend fun sayHello(token: String) = greeting("Hello, I'm Poll Bot. $usage").send(token) + suspend fun sayHello(token: String) = greeting("Hello, I'm Poll Bot. $USAGE").send(token) /** * Sends message with help. */ - suspend fun reactionToWrongCommand(token: String) = fallBackMessage("I couldn't recognize your command. $usage").send(token) + suspend fun reactionToWrongCommand(token: String) = + fallBackMessage("I couldn't recognize your command. $USAGE").send(token) /** * Sends message containing help diff --git a/src/main/kotlin/com/wire/bots/polls/setup/ConfigurationDependencyInjection.kt b/src/main/kotlin/com/wire/bots/polls/setup/ConfigurationDependencyInjection.kt index dd61764..2b3f81d 100644 --- a/src/main/kotlin/com/wire/bots/polls/setup/ConfigurationDependencyInjection.kt +++ b/src/main/kotlin/com/wire/bots/polls/setup/ConfigurationDependencyInjection.kt @@ -17,11 +17,13 @@ import java.io.File private val logger = createLogger("EnvironmentLoaderLogger") -private fun getEnvOrLogDefault(env: String, defaultValue: String) = getEnv(env).whenNull { +private fun getEnvOrLogDefault( + env: String, + defaultValue: String +) = getEnv(env).whenNull { logger.warn { "Env variable $env not set! Using default value - $defaultValue" } } ?: defaultValue - @Suppress("SameParameterValue") // we don't care... private fun loadVersion(defaultVersion: String): String = runCatching { getEnv("RELEASE_FILE_PATH") @@ -29,12 +31,12 @@ private fun loadVersion(defaultVersion: String): String = runCatching { ?: defaultVersion }.getOrNull() ?: defaultVersion +// TODO load all config from the file and then allow the replacement with env variables + /** * Loads the DI container with configuration from the system environment. */ -// TODO load all config from the file and then allow the replacement with env variables fun DI.MainBuilder.bindConfiguration() { - // The default values used in this configuration are for the local development. bind() with singleton { diff --git a/src/main/kotlin/com/wire/bots/polls/setup/DependencyInjection.kt b/src/main/kotlin/com/wire/bots/polls/setup/DependencyInjection.kt index 62b3e1a..b1a7d86 100644 --- a/src/main/kotlin/com/wire/bots/polls/setup/DependencyInjection.kt +++ b/src/main/kotlin/com/wire/bots/polls/setup/DependencyInjection.kt @@ -22,7 +22,6 @@ import org.kodein.di.instance import org.kodein.di.singleton fun DI.MainBuilder.configureContainer() { - bind() with singleton { PollValidation() } bind() with singleton { createHttpClient(instance()) } @@ -48,13 +47,25 @@ fun DI.MainBuilder.configureContainer() { bind() with singleton { PollRepository() } - bind() with singleton { PollService(instance(), instance(), instance(), instance(), instance(), instance()) } + bind() with + singleton { + PollService( + instance(), + instance(), + instance(), + instance(), + instance(), + instance() + ) + } - bind() with singleton { UserCommunicationService(instance(), instance("version")) } + bind() with + singleton { UserCommunicationService(instance(), instance("version")) } bind() with singleton { ConversationService(instance(), instance()) } - bind() with singleton { MessagesHandlingService(instance(), instance()) } + bind() with + singleton { MessagesHandlingService(instance(), instance()) } bind() with singleton { AuthService(proxyToken = instance("proxy-auth")) diff --git a/src/main/kotlin/com/wire/bots/polls/setup/HttpClient.kt b/src/main/kotlin/com/wire/bots/polls/setup/HttpClient.kt index 958df2b..8714b5a 100644 --- a/src/main/kotlin/com/wire/bots/polls/setup/HttpClient.kt +++ b/src/main/kotlin/com/wire/bots/polls/setup/HttpClient.kt @@ -3,10 +3,13 @@ package com.wire.bots.polls.setup import com.wire.bots.polls.utils.ClientRequestMetric import com.wire.bots.polls.utils.createLogger import com.wire.bots.polls.utils.httpCall -import io.ktor.client.* -import io.ktor.client.engine.apache.* -import io.ktor.client.features.json.* -import io.ktor.client.features.logging.* +import io.ktor.client.HttpClient +import io.ktor.client.engine.apache.Apache +import io.ktor.client.features.json.JsonFeature +import io.ktor.client.features.json.JacksonSerializer +import io.ktor.client.features.logging.Logger +import io.ktor.client.features.logging.Logging +import io.ktor.client.features.logging.LogLevel import io.micrometer.core.instrument.MeterRegistry fun createHttpClient(meterRegistry: MeterRegistry) = diff --git a/src/main/kotlin/com/wire/bots/polls/setup/KodeinSetup.kt b/src/main/kotlin/com/wire/bots/polls/setup/KodeinSetup.kt index 5975bbc..91896cb 100644 --- a/src/main/kotlin/com/wire/bots/polls/setup/KodeinSetup.kt +++ b/src/main/kotlin/com/wire/bots/polls/setup/KodeinSetup.kt @@ -1,7 +1,7 @@ package com.wire.bots.polls.setup -import io.ktor.application.* import org.kodein.di.ktor.di +import io.ktor.application.Application /** * Inits and sets up DI container. diff --git a/src/main/kotlin/com/wire/bots/polls/setup/KtorInstallation.kt b/src/main/kotlin/com/wire/bots/polls/setup/KtorInstallation.kt index ae91a62..195cef4 100644 --- a/src/main/kotlin/com/wire/bots/polls/setup/KtorInstallation.kt +++ b/src/main/kotlin/com/wire/bots/polls/setup/KtorInstallation.kt @@ -8,12 +8,18 @@ import com.wire.bots.polls.setup.errors.registerExceptionHandlers import com.wire.bots.polls.setup.logging.APP_REQUEST import com.wire.bots.polls.setup.logging.INFRA_REQUEST import com.wire.bots.polls.utils.createLogger -import io.ktor.application.* -import io.ktor.features.* -import io.ktor.jackson.* -import io.ktor.metrics.micrometer.* -import io.ktor.request.* -import io.ktor.routing.* +import io.ktor.application.Application +import io.ktor.application.install +import io.ktor.features.ContentNegotiation +import io.ktor.features.DefaultHeaders +import io.ktor.features.CallLogging +import io.ktor.features.CallId +import io.ktor.features.callId +import io.ktor.jackson.jackson +import io.ktor.metrics.micrometer.MicrometerMetrics +import io.ktor.request.header +import io.ktor.request.uri +import io.ktor.routing.routing import io.micrometer.core.instrument.distribution.DistributionStatisticConfig import io.micrometer.prometheus.PrometheusMeterRegistry import org.flywaydb.core.Flyway @@ -21,8 +27,7 @@ import org.kodein.di.instance import org.kodein.di.ktor.closestDI import org.slf4j.event.Level import java.text.DateFormat -import java.util.* - +import java.util.UUID private val installationLogger = createLogger("ApplicationSetup") @@ -59,7 +64,10 @@ fun Application.connectDatabase() { migrateDatabase(dbConfig) } else { // TODO verify handling, maybe exit the App? - installationLogger.error { "It was not possible to connect to db database! The application will start but it won't work." } + installationLogger.error { + "It was not possible to connect to db database! " + + "The application will start but it won't work." + } } } @@ -75,8 +83,11 @@ fun migrateDatabase(dbConfig: DatabaseConfiguration) { .migrate() installationLogger.info { - if (migrateResult.migrationsExecuted == 0) "No migrations necessary." - else "Applied ${migrateResult.migrationsExecuted} migrations." + if (migrateResult.migrationsExecuted == 0) { + "No migrations necessary." + } else { + "Applied ${migrateResult.migrationsExecuted} migrations." + } } } @@ -125,7 +136,8 @@ fun Application.installFrameworks() { val prometheusRegistry by closestDI().instance() install(MicrometerMetrics) { registry = prometheusRegistry - distributionStatisticConfig = DistributionStatisticConfig.Builder() + distributionStatisticConfig = DistributionStatisticConfig + .Builder() .percentilesHistogram(true) .build() } diff --git a/src/main/kotlin/com/wire/bots/polls/setup/errors/ExceptionHandling.kt b/src/main/kotlin/com/wire/bots/polls/setup/errors/ExceptionHandling.kt index a34bba9..7e95a9a 100644 --- a/src/main/kotlin/com/wire/bots/polls/setup/errors/ExceptionHandling.kt +++ b/src/main/kotlin/com/wire/bots/polls/setup/errors/ExceptionHandling.kt @@ -2,10 +2,13 @@ package com.wire.bots.polls.setup.errors import com.wire.bots.polls.utils.countException import com.wire.bots.polls.utils.createLogger -import io.ktor.application.* -import io.ktor.features.* -import io.ktor.http.* -import io.ktor.response.* +import io.ktor.application.Application +import io.ktor.application.install +import io.ktor.application.call +import io.ktor.application.ApplicationCall +import io.ktor.features.StatusPages +import io.ktor.http.HttpStatusCode +import io.ktor.response.respond import io.micrometer.prometheus.PrometheusMeterRegistry import org.kodein.di.instance import org.kodein.di.ktor.closestDI @@ -26,13 +29,18 @@ fun Application.registerExceptionHandlers() { } exception { cause -> - logger.error(cause) { "Error in communication with Roman. Status: ${cause.status}, body: ${cause.body}." } + logger.error(cause) { + "Error in communication with Roman. Status: ${cause.status}, body: ${cause.body}." + } call.errorResponse(HttpStatusCode.ServiceUnavailable, cause.message) registry.countException(cause) } } } -suspend inline fun ApplicationCall.errorResponse(statusCode: HttpStatusCode, message: String?) { +suspend inline fun ApplicationCall.errorResponse( + statusCode: HttpStatusCode, + message: String? +) { respond(status = statusCode, message = mapOf("message" to (message ?: "No details specified"))) } diff --git a/src/main/kotlin/com/wire/bots/polls/setup/errors/Exceptions.kt b/src/main/kotlin/com/wire/bots/polls/setup/errors/RomanUnavailableException.kt similarity index 86% rename from src/main/kotlin/com/wire/bots/polls/setup/errors/Exceptions.kt rename to src/main/kotlin/com/wire/bots/polls/setup/errors/RomanUnavailableException.kt index 8caa646..ec3d261 100644 --- a/src/main/kotlin/com/wire/bots/polls/setup/errors/Exceptions.kt +++ b/src/main/kotlin/com/wire/bots/polls/setup/errors/RomanUnavailableException.kt @@ -1,6 +1,6 @@ package com.wire.bots.polls.setup.errors -import io.ktor.http.* +import io.ktor.http.HttpStatusCode data class RomanUnavailableException( val status: HttpStatusCode, diff --git a/src/main/kotlin/com/wire/bots/polls/setup/logging/JsonLoggingLayout.kt b/src/main/kotlin/com/wire/bots/polls/setup/logging/JsonLoggingLayout.kt index 2f476ae..e74efbb 100644 --- a/src/main/kotlin/com/wire/bots/polls/setup/logging/JsonLoggingLayout.kt +++ b/src/main/kotlin/com/wire/bots/polls/setup/logging/JsonLoggingLayout.kt @@ -1,6 +1,5 @@ package com.wire.bots.polls.setup.logging - import ch.qos.logback.classic.spi.ILoggingEvent import ch.qos.logback.classic.spi.IThrowableProxy import ch.qos.logback.classic.spi.ThrowableProxyUtil @@ -11,12 +10,10 @@ import java.time.Instant import java.time.ZoneOffset import java.time.format.DateTimeFormatter - /** * Layout logging into jsons. */ class JsonLoggingLayout : LayoutBase() { - private companion object { val dateTimeFormatter: DateTimeFormatter = DateTimeFormatter.ISO_DATE_TIME @@ -44,15 +41,20 @@ class JsonLoggingLayout : LayoutBase() { return createJson(finalMap) + CoreConstants.LINE_SEPARATOR } - private fun MutableMap.includeMdc(event: ILoggingEvent, mdcKey: String, mapKey: String = mdcKey) { + private fun MutableMap.includeMdc( + event: ILoggingEvent, + mdcKey: String, + mapKey: String = mdcKey + ) { event.mdcPropertyMap[mdcKey]?.also { mdcValue -> this[mapKey] = mdcValue } } - private fun exception(proxy: IThrowableProxy) = mapOf( - "message" to proxy.message, - "class" to proxy.className, - "stacktrace" to ThrowableProxyUtil.asString(proxy) - ) + private fun exception(proxy: IThrowableProxy) = + mapOf( + "message" to proxy.message, + "class" to proxy.className, + "stacktrace" to ThrowableProxyUtil.asString(proxy) + ) private fun formatTime(event: ILoggingEvent): String = dateTimeFormatter.format(Instant.ofEpochMilli(event.timeStamp)) diff --git a/src/main/kotlin/com/wire/bots/polls/utils/ClientRequestMetric.kt b/src/main/kotlin/com/wire/bots/polls/utils/ClientRequestMetric.kt index 0bd22f0..3a7aa4c 100644 --- a/src/main/kotlin/com/wire/bots/polls/utils/ClientRequestMetric.kt +++ b/src/main/kotlin/com/wire/bots/polls/utils/ClientRequestMetric.kt @@ -5,7 +5,7 @@ import io.ktor.client.features.HttpClientFeature import io.ktor.client.statement.HttpReceivePipeline import io.ktor.client.statement.HttpResponse import io.ktor.client.statement.request -import io.ktor.util.* +import io.ktor.util.AttributeKey import mu.KLogging /** @@ -13,12 +13,12 @@ import mu.KLogging */ typealias RequestMetricHandler = suspend (RequestMetric) -> Unit - /** * Enables callback after HttpClient sends a request with [RequestMetric]. */ -class ClientRequestMetric(private val metricHandler: RequestMetricHandler) { - +class ClientRequestMetric( + private val metricHandler: RequestMetricHandler +) { class Config { internal var metricHandler: RequestMetricHandler = {} @@ -31,14 +31,16 @@ class ClientRequestMetric(private val metricHandler: RequestMetricHandler) { } companion object Feature : HttpClientFeature, KLogging() { - override val key: AttributeKey = AttributeKey("ClientRequestMetric") override fun prepare(block: Config.() -> Unit) = ClientRequestMetric(Config().apply(block).metricHandler) - override fun install(feature: ClientRequestMetric, scope: HttpClient) { + override fun install( + feature: ClientRequestMetric, + scope: HttpClient + ) { // synchronous response pipeline hook // instead of ResponseObserver - which spawns a new coroutine scope.receivePipeline.intercept(HttpReceivePipeline.After) { response -> @@ -50,17 +52,17 @@ class ClientRequestMetric(private val metricHandler: RequestMetricHandler) { } // does not touch the content - private fun HttpResponse.toRequestMetric() = RequestMetric( - requestTime = requestTime.timestamp, - responseTime = responseTime.timestamp, - method = request.method.value, - url = request.url.toString(), - responseCode = status.value - ) + private fun HttpResponse.toRequestMetric() = + RequestMetric( + requestTime = requestTime.timestamp, + responseTime = responseTime.timestamp, + method = request.method.value, + url = request.url.toString(), + responseCode = status.value + ) } } - data class RequestMetric( // number of epoch milliseconds val requestTime: Long, @@ -69,4 +71,3 @@ data class RequestMetric( val url: String, val responseCode: Int ) - diff --git a/src/main/kotlin/com/wire/bots/polls/utils/Extensions.kt b/src/main/kotlin/com/wire/bots/polls/utils/Extensions.kt index 727a721..f5043b2 100644 --- a/src/main/kotlin/com/wire/bots/polls/utils/Extensions.kt +++ b/src/main/kotlin/com/wire/bots/polls/utils/Extensions.kt @@ -6,23 +6,29 @@ import org.slf4j.MDC /** * Creates URL from [this] as base and [path] as path */ -infix fun String.appendPath(path: String) = "${dropLastWhile { it == '/' }}/${path.dropWhile { it == '/' }}" +infix fun String.appendPath(path: String) = + "${dropLastWhile { it == '/' }}/${path.dropWhile { it == '/' }}" /** * Creates logger with given name. */ fun createLogger(name: String) = KLogging().logger("com.wire.$name") - /** * Includes value to current MDC under the key. */ -inline fun mdc(key: String, value: () -> String?) = mdc(key, value()) +inline fun mdc( + key: String, + value: () -> String? +) = mdc(key, value()) /** * Includes value to current MDC under the key if the key is not null. */ -fun mdc(key: String, value: String?) { +fun mdc( + key: String, + value: String? +) { if (value != null) { MDC.put(key, value) } diff --git a/src/main/kotlin/com/wire/bots/polls/utils/PrometheusExtensions.kt b/src/main/kotlin/com/wire/bots/polls/utils/PrometheusExtensions.kt index 95cc3b7..f62925d 100644 --- a/src/main/kotlin/com/wire/bots/polls/utils/PrometheusExtensions.kt +++ b/src/main/kotlin/com/wire/bots/polls/utils/PrometheusExtensions.kt @@ -7,7 +7,10 @@ import java.util.concurrent.TimeUnit /** * Registers exception in the prometheus metrics. */ -fun MeterRegistry.countException(exception: Throwable, additionalTags: Map = emptyMap()) { +fun MeterRegistry.countException( + exception: Throwable, + additionalTags: Map = emptyMap() +) { val baseTags = mapOf( "type" to exception.javaClass.name, "message" to (exception.message ?: "No message.") @@ -16,7 +19,6 @@ fun MeterRegistry.countException(exception: Throwable, additionalTags: Map.toTags() = - map { (key, value) -> Tag(key, value) } +private fun Map.toTags() = map { (key, value) -> Tag(key, value) } /** * Because original implementation is not handy. */ -private data class Tag(private val k: String, private val v: String) : Tag { +private data class Tag( + private val k: String, + private val v: String +) : Tag { override fun getKey(): String = k + override fun getValue(): String = v }