diff --git a/kits/appsflyer/appsflyer-7/README.md b/kits/appsflyer/appsflyer-7/README.md new file mode 100644 index 000000000..aab314117 --- /dev/null +++ b/kits/appsflyer/appsflyer-7/README.md @@ -0,0 +1,51 @@ +# AppsFlyer Kit Integration + +This repository contains the [AppsFlyer](https://www.appsflyer.com/) integration for the [mParticle Android SDK](https://github.com/mParticle/mparticle-android-sdk). + +This kit targets **AppsFlyer Android SDK 7.x**. For AppsFlyer 6.x, use the `appsflyer-6` kit instead. +AppsFlyer 7.x requires `minSdk 21`. + +## Adding the integration + +1. Add the kit dependency to your app's build.gradle: + + ```groovy + dependencies { + implementation 'com.mparticle:appsflyer-7:5+' + } + ``` + +2. Follow the mParticle Android SDK [quick-start](https://github.com/mParticle/mparticle-android-sdk), then rebuild and launch your app, and verify that you see `"AppsFlyer detected"` in the output of `adb logcat`. +3. Reference mParticle's integration docs below to enable the integration. +4. If you wish to utilize Appsflyers InstallReferrer capabilities, add a dependency for Play Install Referrer library in you app's build.gradle. For more information visit the [Appsflyer SDK's documentation page](https://support.appsflyer.com/hc/en-us/articles/207032066#attribution) on the subject: + + ```groovy + dependencies { + implementation "com.android.installreferrer:installreferrer:2.2" + } + ``` + +## Migrating from the `appsflyer-6` kit + +AppsFlyer 7.0 relocated much of its public API and removed several methods. The kit absorbs most of +this, but two changes are visible to integrating apps: + +- **`minSdk` is now 21** (AppsFlyer 7.x raised its own minimum from 19). +- **Email identities are forwarded via AppsFlyer's `setUserEmail`.** AppsFlyer 7.0 removed + `setUserEmails(EmailsCryptType, ...)` along with the `EmailsCryptType` enum, so the kit can no + longer request SHA256 hashing on AppsFlyer's side. The kit previously passed + `EmailsCryptType.NONE` (plaintext), so the value actually forwarded is unchanged. + +AppsFlyer 7.x also splits its implementation into a companion `com.appsflyer:af-android-sdk-base` +artifact, which resolves transitively. + +If your app calls the AppsFlyer SDK directly in addition to using this kit, see AppsFlyer's own 7.0 +migration notes — the `com.appsflyer.*` -> `com.appsflyer.share.*` package move affects your code too. + +## Documentation + +[AppsFlyer integration](http://docs.mparticle.com/integrations/appsflyer/event/) + +## License + +[Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0) diff --git a/kits/appsflyer/appsflyer-7/build.gradle b/kits/appsflyer/appsflyer-7/build.gradle new file mode 100644 index 000000000..c47d96244 --- /dev/null +++ b/kits/appsflyer/appsflyer-7/build.gradle @@ -0,0 +1,69 @@ +buildscript { + ext.kotlin_version = '2.1.20' + if (!project.hasProperty('version') || project.version.equals('unspecified')) { + project.version = '+' + } + + repositories { + google() + mavenLocal() + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:8.1.4' + classpath 'com.mparticle:android-kit-plugin:' + project.version + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +plugins { + id "org.sonarqube" version "3.5.0.2730" + id "org.jlleitschuh.gradle.ktlint" version "13.0.0" +} + +sonarqube { + properties { + property "sonar.projectKey", "mparticle-android-integration-appsflyer-7" + property "sonar.organization", "mparticle" + property "sonar.host.url", "https://sonarcloud.io" + } +} + +apply plugin: 'org.jlleitschuh.gradle.ktlint' +apply plugin: 'kotlin-android' +apply plugin: 'com.mparticle.kit' + +android { + namespace 'com.mparticle.kits.appsflyer7' + buildFeatures { + buildConfig = true + } + defaultConfig { + minSdkVersion 21 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + kotlinOptions { + jvmTarget = '17' + } + testOptions { + unitTests.all { + jvmArgs += ['--add-opens', 'java.base/java.lang=ALL-UNNAMED'] + } + } +} + +ktlint { + android.set(true) +} + +dependencies { + api 'com.appsflyer:af-android-sdk:[7.0.0,8.0.0)' + testImplementation files('libs/java-json.jar') + testImplementation files('libs/testutils.aar') +} +repositories { + mavenCentral() +} diff --git a/kits/appsflyer/appsflyer-7/consumer-proguard.pro b/kits/appsflyer/appsflyer-7/consumer-proguard.pro new file mode 100644 index 000000000..e69de29bb diff --git a/kits/appsflyer/appsflyer-7/example/example-kotlin/build.gradle b/kits/appsflyer/appsflyer-7/example/example-kotlin/build.gradle new file mode 100644 index 000000000..2fbdc3ff2 --- /dev/null +++ b/kits/appsflyer/appsflyer-7/example/example-kotlin/build.gradle @@ -0,0 +1,40 @@ +plugins { + id 'com.android.application' + id 'org.jetbrains.kotlin.android' +} + +android { + namespace 'com.mparticle.kits.appsflyer.appsflyer7.example.kotlin' + compileSdk 35 + + defaultConfig { + applicationId 'com.mparticle.kits.appsflyer.appsflyer7.example.kotlin' + minSdk 21 + targetSdk 35 + versionCode 1 + versionName '1.0' + multiDexEnabled true + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = '17' + } + + buildTypes { + release { + minifyEnabled false + } + } +} + +dependencies { + implementation project(':kits:appsflyer:appsflyer-7') + implementation 'androidx.appcompat:appcompat:1.6.1' + implementation 'com.google.android.material:material:1.11.0' + implementation 'androidx.multidex:multidex:2.0.1' +} diff --git a/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/AndroidManifest.xml b/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/AndroidManifest.xml new file mode 100644 index 000000000..84b1637c1 --- /dev/null +++ b/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/AndroidManifest.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + diff --git a/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/kotlin/com/mparticle/kits/appsflyer/appsflyer7/example/kotlin/ExampleApplication.kt b/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/kotlin/com/mparticle/kits/appsflyer/appsflyer7/example/kotlin/ExampleApplication.kt new file mode 100644 index 000000000..f8470d24e --- /dev/null +++ b/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/kotlin/com/mparticle/kits/appsflyer/appsflyer7/example/kotlin/ExampleApplication.kt @@ -0,0 +1,24 @@ +package com.mparticle.kits.appsflyer.appsflyer7.example.kotlin + +import androidx.multidex.MultiDexApplication +import com.mparticle.MPEvent +import com.mparticle.MParticle +import com.mparticle.MParticleOptions + +class ExampleApplication : MultiDexApplication() { + override fun onCreate() { + super.onCreate() + val options = + MParticleOptions + .builder(this) + .credentials( + "REPLACE WITH YOUR MPARTICLE API KEY", + "REPLACE WITH YOUR MPARTICLE API SECRET", + ).logLevel(MParticle.LogLevel.VERBOSE) + .build() + MParticle.start(options) + MParticle.getInstance()?.logEvent( + MPEvent.Builder("foo", MParticle.EventType.Other).build(), + ) + } +} diff --git a/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/kotlin/com/mparticle/kits/appsflyer/appsflyer7/example/kotlin/MainActivity.kt b/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/kotlin/com/mparticle/kits/appsflyer/appsflyer7/example/kotlin/MainActivity.kt new file mode 100644 index 000000000..f43119c84 --- /dev/null +++ b/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/kotlin/com/mparticle/kits/appsflyer/appsflyer7/example/kotlin/MainActivity.kt @@ -0,0 +1,11 @@ +package com.mparticle.kits.appsflyer.appsflyer7.example.kotlin + +import android.os.Bundle +import androidx.appcompat.app.AppCompatActivity + +class MainActivity : AppCompatActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + } +} diff --git a/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/res/drawable/ic_launcher_foreground.xml b/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 000000000..046177833 --- /dev/null +++ b/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,14 @@ + + + + diff --git a/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/res/layout/activity_main.xml b/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/res/layout/activity_main.xml new file mode 100644 index 000000000..e2897e3ff --- /dev/null +++ b/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/res/layout/activity_main.xml @@ -0,0 +1,14 @@ + + + + + + diff --git a/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 000000000..a8a8fa551 --- /dev/null +++ b/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 000000000..a8a8fa551 --- /dev/null +++ b/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/res/values/colors.xml b/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/res/values/colors.xml new file mode 100644 index 000000000..f42ada656 --- /dev/null +++ b/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/res/values/colors.xml @@ -0,0 +1,4 @@ + + + #FFFFFF + diff --git a/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/res/values/strings.xml b/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/res/values/strings.xml new file mode 100644 index 000000000..fa734d856 --- /dev/null +++ b/kits/appsflyer/appsflyer-7/example/example-kotlin/src/main/res/values/strings.xml @@ -0,0 +1,4 @@ + + + AppsFlyer Kit Kotlin Example + diff --git a/kits/appsflyer/appsflyer-7/gradle.properties b/kits/appsflyer/appsflyer-7/gradle.properties new file mode 100644 index 000000000..edb1202c3 --- /dev/null +++ b/kits/appsflyer/appsflyer-7/gradle.properties @@ -0,0 +1,4 @@ +android.enableJetifier=true +android.useAndroidX=true +org.gradle.daemon=true +org.gradle.jvmargs=-Xmx2560m \ No newline at end of file diff --git a/kits/appsflyer/appsflyer-7/gradle/wrapper/gradle-wrapper.jar b/kits/appsflyer/appsflyer-7/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..41d9927a4 Binary files /dev/null and b/kits/appsflyer/appsflyer-7/gradle/wrapper/gradle-wrapper.jar differ diff --git a/kits/appsflyer/appsflyer-7/gradle/wrapper/gradle-wrapper.properties b/kits/appsflyer/appsflyer-7/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..e1bef7e87 --- /dev/null +++ b/kits/appsflyer/appsflyer-7/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.2-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/kits/appsflyer/appsflyer-7/gradlew b/kits/appsflyer/appsflyer-7/gradlew new file mode 100755 index 000000000..1b6c78733 --- /dev/null +++ b/kits/appsflyer/appsflyer-7/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# 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. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# 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 +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 + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +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 + +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 ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +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 + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + 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 +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +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 + +# 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" || "$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 + 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 + # 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 +fi + +# 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. +# + +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/kits/appsflyer/appsflyer-7/gradlew.bat b/kits/appsflyer/appsflyer-7/gradlew.bat new file mode 100644 index 000000000..107acd32c --- /dev/null +++ b/kits/appsflyer/appsflyer-7/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/kits/appsflyer/appsflyer-7/libs/java-json.jar b/kits/appsflyer/appsflyer-7/libs/java-json.jar new file mode 100755 index 000000000..2f211e366 Binary files /dev/null and b/kits/appsflyer/appsflyer-7/libs/java-json.jar differ diff --git a/kits/appsflyer/appsflyer-7/libs/testutils.aar b/kits/appsflyer/appsflyer-7/libs/testutils.aar new file mode 100644 index 000000000..cf49b4189 Binary files /dev/null and b/kits/appsflyer/appsflyer-7/libs/testutils.aar differ diff --git a/kits/appsflyer/appsflyer-7/settings.gradle.kts b/kits/appsflyer/appsflyer-7/settings.gradle.kts new file mode 100644 index 000000000..64ca48ba7 --- /dev/null +++ b/kits/appsflyer/appsflyer-7/settings.gradle.kts @@ -0,0 +1,2 @@ +rootProject.name = "android-appsflyer-kit" +include(":") diff --git a/kits/appsflyer/appsflyer-7/src/main/AndroidManifest.xml b/kits/appsflyer/appsflyer-7/src/main/AndroidManifest.xml new file mode 100644 index 000000000..ec4a76765 --- /dev/null +++ b/kits/appsflyer/appsflyer-7/src/main/AndroidManifest.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/kits/appsflyer/appsflyer-7/src/main/kotlin/com/mparticle/kits/AppsFlyerKit.kt b/kits/appsflyer/appsflyer-7/src/main/kotlin/com/mparticle/kits/AppsFlyerKit.kt new file mode 100644 index 000000000..545196b3a --- /dev/null +++ b/kits/appsflyer/appsflyer-7/src/main/kotlin/com/mparticle/kits/AppsFlyerKit.kt @@ -0,0 +1,620 @@ +package com.mparticle.kits + +import android.app.Activity +import android.content.Context +import android.content.Intent +import android.location.Location +import android.os.Bundle +import com.appsflyer.share.AFInAppEventParameterName.CONTENT_ID +import com.appsflyer.share.AFInAppEventParameterName.CONTENT_TYPE +import com.appsflyer.share.AFInAppEventParameterName.CURRENCY +import com.appsflyer.share.AFInAppEventParameterName.PRICE +import com.appsflyer.share.AFInAppEventParameterName.QUANTITY +import com.appsflyer.share.AFInAppEventParameterName.REVENUE +import com.appsflyer.share.AFInAppEventType +import com.appsflyer.share.AFInAppEventType.ADD_TO_CART +import com.appsflyer.share.AFInAppEventType.ADD_TO_WISH_LIST +import com.appsflyer.share.AFInAppEventType.INITIATED_CHECKOUT +import com.appsflyer.share.AFInAppEventType.PURCHASE +import com.appsflyer.share.AppsFlyerConsent +import com.appsflyer.share.AppsFlyerConversionListener +import com.appsflyer.AppsFlyerLib +import com.appsflyer.share.deeplink.DeepLinkListener +import com.appsflyer.share.deeplink.DeepLinkResult +import com.mparticle.AttributionError +import com.mparticle.AttributionResult +import com.mparticle.MPEvent +import com.mparticle.MParticle +import com.mparticle.commerce.CommerceEvent +import com.mparticle.commerce.Product +import com.mparticle.consent.ConsentState +import com.mparticle.internal.Logger +import com.mparticle.internal.MPUtility +import com.mparticle.kits.KitIntegration.LogoutListener +import org.json.JSONArray +import org.json.JSONException +import org.json.JSONObject +import java.math.BigDecimal +import java.util.LinkedList +import com.mparticle.kits.KitIntegration.ModifyIdentityListener + +/** + * mParticle Kit wrapper for the AppsFlyer SDK + */ +class AppsFlyerKit : + KitIntegration(), + KitIntegration.EventListener, + ModifyIdentityListener, + LogoutListener, + KitIntegration.CommerceListener, + AppsFlyerConversionListener, + KitIntegration.ActivityListener, + KitIntegration.UserAttributeListener { + override fun getInstance(): AppsFlyerLib = AppsFlyerLib.getInstance() + + override fun getName() = NAME + + public override fun onKitCreate( + setting: Map?, + context: Context, + ): List { + AppsFlyerLib + .getInstance() + .setDebugLog( + MParticle.getInstance()?.environment == MParticle.Environment.Development, + ) + settings[DEV_KEY]?.let { AppsFlyerLib.getInstance().init(it, this, context) } + setting?.get(SHARING_FILTER_FOR_PARTNERS)?.let { + applySharingFilterForPartners(it) + } + val userConsentState = currentUser?.consentState + setConsent(userConsentState) + AppsFlyerLib.getInstance().start() + AppsFlyerLib.getInstance().setCollectAndroidID(MParticle.isAndroidIdEnabled()) + val integrationAttributes = HashMap(1) + integrationAttributes[APPSFLYERID_INTEGRATION_KEY] = + AppsFlyerLib.getInstance().getAppsFlyerUID(context) + setIntegrationAttributes(integrationAttributes) + AppsFlyerLib.getInstance().subscribeForDeepLink(deepLinkListener()) + + val messages: MutableList = ArrayList() + messages.add( + ReportingMessage( + this, + ReportingMessage.MessageType.APP_STATE_TRANSITION, + System.currentTimeMillis(), + null, + ), + ) + return messages + } + + override fun leaveBreadcrumb(breadcrumb: String): List = emptyList() + + override fun logError( + message: String, + eventData: Map, + ): List = emptyList() + + override fun logException( + exception: Exception, + eventData: Map, + message: String, + ): List = emptyList() + + override fun logLtvIncrease( + valueIncreased: BigDecimal, + valueTotal: BigDecimal, + eventName: String, + contextInfo: Map, + ): List = emptyList() + + override fun logEvent(event: CommerceEvent): List { + val messages: MutableList = LinkedList() + val eventValues: MutableMap = HashMap() + val productList = event.products + + if (isSalesEvent(event)) { + logSalesEvent(event, eventValues, productList, messages) + } else { + logNotSalesEvent(event, messages) + } + return messages + } + + private fun logNotSalesEvent( + event: CommerceEvent, + messages: MutableList, + ) { + val eventList = CommerceEventUtils.expand(event) + if (eventList.isNotEmpty()) { + for (e in eventList) { + try { + logEvent(e) + messages.add(ReportingMessage.fromEvent(this, event)) + } catch (e: Exception) { + Logger.warning("Failed to call logCustomEvent to AppsFlyer kit: $e") + } + } + } + } + + private fun logSalesEvent( + event: CommerceEvent, + eventValues: MutableMap, + productList: MutableList?, + messages: MutableList, + ) { + event.customAttributes?.let { eventValues.putAll(it) } + + if (!KitUtils.isEmpty(event.currency)) { + eventValues[CURRENCY] = event.currency + } + + if (event.productAction == Product.ADD_TO_CART || + event.productAction == Product.ADD_TO_WISHLIST + ) { + val eventName = + if (event.productAction == Product.ADD_TO_CART) { + ADD_TO_CART + } else { + ADD_TO_WISH_LIST + } + + productList?.iterator()?.forEach { product -> + val productEventValues: MutableMap = hashMapOf() + productEventValues.putAll(eventValues) + with(product) { + productEventValues[PRICE] = unitPrice + productEventValues[QUANTITY] = quantity + if (!KitUtils.isEmpty(sku)) { + productEventValues[CONTENT_ID] = sku + } + if (!KitUtils.isEmpty(category)) { + productEventValues[CONTENT_TYPE] = category + } + } + instance.logEvent(context, eventName, productEventValues) + messages.add(ReportingMessage.fromEvent(this, event)) + } + } else { + val eventName = + if (event.productAction == Product.CHECKOUT) { + INITIATED_CHECKOUT + } else { + PURCHASE + } + eventValues[CONTENT_ID] = generateProductIdList(event) + + if (!productList.isNullOrEmpty()) { + var totalQuantity = 0.0 + for (product in productList) { + totalQuantity += product.quantity + } + eventValues[QUANTITY] = totalQuantity + } + + val transactionAttributes = event.transactionAttributes + if ((transactionAttributes != null) && (transactionAttributes.revenue != 0.0)) { + val revenue = transactionAttributes.revenue + if (event.productAction == Product.PURCHASE) { + eventValues[REVENUE] = revenue + if (!MPUtility.isEmpty(transactionAttributes.id)) { + eventValues[AFInAppEventType.ORDER_ID] = transactionAttributes.id + } + } else { + eventValues[PRICE] = revenue + } + } + instance.logEvent(context, eventName, eventValues) + messages.add(ReportingMessage.fromEvent(this, event)) + } + } + + private fun isSalesEvent(event: CommerceEvent) = + event.productAction == Product.ADD_TO_CART || + event.productAction == Product.ADD_TO_WISHLIST || + event.productAction == Product.CHECKOUT || + event.productAction == Product.PURCHASE + + override fun logEvent(event: MPEvent): List { + var hashMap: HashMap? = hashMapOf() + if (event.customAttributes?.isNotEmpty() == true) { + hashMap = event.customAttributes?.let { HashMap(it) } + } + instance.logEvent(context, event.eventName, hashMap) + val messages: MutableList = LinkedList() + messages.add(ReportingMessage.fromEvent(this, event)) + return messages + } + + override fun logScreen( + screenName: String, + eventAttributes: Map, + ): List = emptyList() + + override fun setOptOut(optOutStatus: Boolean): List { + instance.anonymizeUser(optOutStatus) + val messageList: MutableList = LinkedList() + messageList.add( + ReportingMessage( + this, + ReportingMessage.MessageType.OPT_OUT, + System.currentTimeMillis(), + null, + ).setOptOut(optOutStatus), + ) + return messageList + } + + override fun onIncrementUserAttribute( + key: String?, + incrementedBy: Number?, + value: String?, + ) { + } + + override fun onRemoveUserAttribute( + key: String?, + ) { + } + + override fun onSetUserAttribute( + key: String?, + value: Any?, + ) { + // No-op: this kit does not implement this feature. + } + + override fun onSetUserTag( + key: String?, + ) { + } + + override fun onSetUserAttributeList( + attributeKey: String?, + attributeValueList: List?, + ) { + // not supported + } + + override fun onSetAllUserAttributes( + userAttributes: MutableMap?, + userAttributeLists: MutableMap>?, + ) { + // No-op: this kit does not implement this feature. + } + + override fun supportsAttributeLists(): Boolean = true + + override fun removeUserIdentity(identityType: MParticle.IdentityType) { + with(instance) { + if (MParticle.IdentityType.CustomerId == identityType) { + setCustomerUserId("") + } else if (MParticle.IdentityType.Email == identityType) { + setUserEmail("") + } + } + } + + override fun setUserIdentity( + identityType: MParticle.IdentityType, + identity: String, + ) { + with(instance) { + if (MParticle.IdentityType.CustomerId == identityType) { + setCustomerUserId(identity) + } else if (MParticle.IdentityType.Email == identityType) { + setUserEmail(identity) + } + } + } + + override fun logout(): List = emptyList() + + private fun parseToNestedMap(jsonString: String): Map { + val topLevelMap = mutableMapOf() + try { + if (jsonString.isNullOrEmpty()) { + return topLevelMap + } + val jsonObject = JSONObject(jsonString) + + for (key in jsonObject.keys()) { + val value = jsonObject.get(key) + if (value is JSONObject) { + topLevelMap[key] = parseToNestedMap(value.toString()) + } else { + topLevelMap[key] = value + } + } + } catch (e: Exception) { + Logger.error( + e, + "The AppsFlyer kit was unable to parse the user's ConsentState, consent may not be set correctly on the AppsFlyer SDK", + ) + } + return topLevelMap + } + + private fun searchKeyInNestedMap( + map: Map<*, *>, + key: Any, + ): Any? { + if (map.isNullOrEmpty()) { + return null + } + try { + for ((mapKey, mapValue) in map) { + if (mapKey.toString().equals(key.toString(), ignoreCase = true)) { + return mapValue + } + if (mapValue is Map<*, *>) { + val foundValue = searchKeyInNestedMap(mapValue, key) + if (foundValue != null) { + return foundValue + } + } + } + } catch (e: Exception) { + Logger.error( + e, + "The AppsFlyer kit threw an exception while searching for the configured consent purpose mapping in the current user's consent status.", + ) + } + return null + } + + override fun onConsentStateUpdated( + consentState: ConsentState, + consentState1: ConsentState, + ) { + setConsent(consentState1) + } + + private fun setConsent(consentState: ConsentState?) { + if (settings[GDPR_APPLIES].isNullOrEmpty()) { + return + } + val appsFlyerGDPRUser: AppsFlyerConsent + if (!settings[GDPR_APPLIES].toBoolean()) { + appsFlyerGDPRUser = AppsFlyerConsent(false, null, null, null) + } else { + var adStorageConsentValue: Boolean? = null + when (settings[DEFAULT_AD_STORAGE_CONSENT]) { + AppsFlyerConsentValues.GRANTED.consentValue -> adStorageConsentValue = true + AppsFlyerConsentValues.DENIED.consentValue -> adStorageConsentValue = false + } + + var adUserDataConsentValue: Boolean? = null + when (settings[DEFAULT_AD_USER_DATA_CONSENT]) { + AppsFlyerConsentValues.GRANTED.consentValue -> adUserDataConsentValue = true + AppsFlyerConsentValues.DENIED.consentValue -> adUserDataConsentValue = false + } + + var adPersonalizationConsentValue: Boolean? = null + when (settings[DEFAULT_AD_PERSONALIZATION_CONSENT]) { + AppsFlyerConsentValues.GRANTED.consentValue -> adPersonalizationConsentValue = true + AppsFlyerConsentValues.DENIED.consentValue -> adPersonalizationConsentValue = false + } + + val clientConsentSettings = parseToNestedMap(consentState.toString()) + + parseConsentMapping(settings[CONSENT_MAPPING]).iterator().forEach { currentConsent -> + + val isConsentAvailable = + searchKeyInNestedMap(clientConsentSettings, key = currentConsent.key) + + if (isConsentAvailable != null) { + val isConsentGranted: Boolean = + JSONObject(isConsentAvailable.toString()).opt("consented") as Boolean + + when (currentConsent.value) { + "ad_storage" -> adStorageConsentValue = isConsentGranted + + "ad_user_data" -> adUserDataConsentValue = isConsentGranted + + "ad_personalization" -> adPersonalizationConsentValue = isConsentGranted + } + } + } + appsFlyerGDPRUser = AppsFlyerConsent(true, adUserDataConsentValue, adPersonalizationConsentValue, adStorageConsentValue) + } + AppsFlyerLib.getInstance().setConsentData(appsFlyerGDPRUser) + } + + private fun parseConsentMapping(json: String?): Map { + if (json.isNullOrEmpty()) { + return emptyMap() + } + val jsonWithFormat = json.replace("\\", "") + + return try { + JSONArray(jsonWithFormat) + .let { jsonArray -> + (0 until jsonArray.length()) + .associate { + val jsonObject = jsonArray.getJSONObject(it) + val map = jsonObject.getString("map") + val value = jsonObject.getString("value") + map to value + } + } + } catch (jse: JSONException) { + Logger.error( + jse, + "The AppsFlyer kit threw an exception while searching for the configured consent purpose mapping in the current user's consent status.", + ) + emptyMap() + } + } + + override fun onConversionDataSuccess(conversionDataN: MutableMap?) { + var conversionData = conversionDataN + val jsonResult = JSONObject() + + if (conversionData == null) { + conversionData = hashMapOf() + } + + conversionData[INSTALL_CONVERSION_RESULT] = "true" + + for ((key, value) in conversionData) { + try { + jsonResult.put(key, value) + } catch (e: JSONException) { + } + } + + val result = + AttributionResult() + .setParameters(jsonResult) + .setServiceProviderId(configuration.kitId) + kitManager.onResult(result) + } + + override fun onConversionDataFail(conversionFailure: String) { + if (!KitUtils.isEmpty(conversionFailure)) { + val error = + AttributionError() + .setMessage(conversionFailure) + .setServiceProviderId(configuration.kitId) + kitManager.onError(error) + } + } + + fun deepLinkListener() = + DeepLinkListener { deepLinkResult -> + val deepLinkObj = deepLinkResult.deepLink + + when (deepLinkResult.status) { + DeepLinkResult.Status.FOUND -> { + try { + deepLinkObj.clickEvent.put(APP_OPEN_ATTRIBUTION_RESULT, true.toString()) + val result = + AttributionResult() + .setParameters(deepLinkObj.clickEvent) + .setServiceProviderId(configuration.kitId) + kitManager.onResult(result) + } catch (e: Exception) { + return@DeepLinkListener + } + } + DeepLinkResult.Status.NOT_FOUND -> { + return@DeepLinkListener + } + else -> { + val dlError = deepLinkResult.error + if (!KitUtils.isEmpty(dlError.toString())) { + val error = + AttributionError() + .setMessage(dlError.toString()) + .setServiceProviderId(configuration.kitId) + kitManager.onError(error) + } + return@DeepLinkListener + } + } + } + + override fun setInstallReferrer(intent: Intent) { + // do nothing, Appsflyer will fetch the install referrer data internally, + // as long as the proper Play Install Referrer dependency is present. + } + + override fun setLocation(location: Location) { + instance.logLocation(context, location.latitude, location.longitude) + } + + override fun onActivityCreated( + activity: Activity, + bundle: Bundle?, + ): List { + instance.start() + return emptyList() + } + + override fun onActivityStarted(activity: Activity): List = emptyList() + + override fun onActivityResumed(activity: Activity): List = emptyList() + + override fun onActivityPaused(activity: Activity): List = emptyList() + + override fun onActivityStopped(activity: Activity): List = emptyList() + + override fun onActivitySaveInstanceState( + activity: Activity, + bundle: Bundle?, + ): List = emptyList() + + override fun onActivityDestroyed(activity: Activity): List = emptyList() + + override fun onSettingsUpdated(settings: Map) { + settings[SHARING_FILTER_FOR_PARTNERS]?.let { applySharingFilterForPartners(it) } + } + + private fun applySharingFilterForPartners(jsonValue: String) { + val partners = parseSharingFilterForPartners(jsonValue) + if (!partners.isNullOrEmpty()) { + instance.setSharingFilterForPartners(*partners.toTypedArray()) + } + } + + private fun parseSharingFilterForPartners(json: String?): List? { + if (json.isNullOrEmpty()) return null + return try { + val jsonWithFormat = json.replace("\\", "") + val array = JSONArray(jsonWithFormat) + List(array.length()) { i -> array.getString(i) } + } catch (e: JSONException) { + Logger.warning( + "AppsFlyer kit: failed to parse sharingFilterForPartners, " + + "consent filter for partners will not be applied. Error: ${e.message}", + ) + null + } + } + + companion object { + const val DEV_KEY = "devKey" + const val APPSFLYERID_INTEGRATION_KEY = "appsflyer_id_integration_setting" + const val NAME = "AppsFlyer" + const val COMMA = "," + + /** + * This key will be present when returning a result from AppsFlyer's onInstallConversionDataLoaded API + */ + const val INSTALL_CONVERSION_RESULT = "MPARTICLE_APPSFLYER_INSTALL_CONVERSION_RESULT" + + /** + * This key will be present when returning a result from AppsFlyer's onAppOpenAttribution API + */ + const val APP_OPEN_ATTRIBUTION_RESULT = + "MPARTICLE_APPSFLYER_APP_OPEN_ATTRIBUTION_RESULT" + + fun generateProductIdList(event: CommerceEvent?): List? = + event?.products?.filter { !KitUtils.isEmpty(it.sku) }?.let { + if (it.isNotEmpty()) { + it.map { it.sku.replace(COMMA, "%2C") } + } else { + null + } + } + + private const val SHARING_FILTER_FOR_PARTNERS = "sharingFilterForPartners" + private const val CONSENT_MAPPING = "consentMapping" + + @Suppress("ktlint:standard:property-naming") + enum class AppsFlyerConsentValues( + val consentValue: String, + ) { + GRANTED("Granted"), + DENIED("Denied"), + } + + const val GDPR_APPLIES = "gdprApplies" + const val DEFAULT_AD_STORAGE_CONSENT = "defaultAdStorageConsent" + const val DEFAULT_AD_USER_DATA_CONSENT = "defaultAdUserDataConsent" + const val DEFAULT_AD_PERSONALIZATION_CONSENT = "defaultAdPersonalizationConsent" + } +} diff --git a/kits/appsflyer/appsflyer-7/src/test/kotlin/com/appsflyer/AppsFlyerLib.kt b/kits/appsflyer/appsflyer-7/src/test/kotlin/com/appsflyer/AppsFlyerLib.kt new file mode 100644 index 000000000..efbb91b91 --- /dev/null +++ b/kits/appsflyer/appsflyer-7/src/test/kotlin/com/appsflyer/AppsFlyerLib.kt @@ -0,0 +1,48 @@ +package com.appsflyer + +import android.content.Context +import com.appsflyer.share.AppsFlyerConsent + +class AppsFlyerLib { + private var consentData: AppsFlyerConsent? = null + + fun setConsentData(consent: AppsFlyerConsent) { + consentData = consent + } + + fun getConsentData(): AppsFlyerConsent? = consentData + + fun getConsentState(): MutableMap { + val stateMap = mutableMapOf() + consentData?.let { consent -> + // Use property names directly instead of getter methods + consent.isUserSubjectToGDPR?.let { stateMap["isUserSubjectToGDPR"] = it } + consent.hasConsentForDataUsage?.let { stateMap["hasConsentForDataUsage"] = it } + consent.hasConsentForAdsPersonalization?.let { stateMap["hasConsentForAdsPersonalization"] = it } + consent.hasConsentForAdStorage?.let { stateMap["hasConsentForAdStorage"] = it } + } + return stateMap + } + + companion object { + private var _instance: AppsFlyerLib? = null + + @JvmStatic + fun getInstance(): AppsFlyerLib? { + if (_instance == null) { + _instance = AppsFlyerLib() + } + return _instance + } + + @JvmStatic + fun getInstance(context: Context?): AppsFlyerLib? = getInstance() + + /** + * Access Methods + */ + fun clearInstance() { + _instance = null + } + } +} diff --git a/kits/appsflyer/appsflyer-7/src/test/kotlin/com/appsflyer/share/AppsFlyerConsent.kt b/kits/appsflyer/appsflyer-7/src/test/kotlin/com/appsflyer/share/AppsFlyerConsent.kt new file mode 100644 index 000000000..8b5c15dc0 --- /dev/null +++ b/kits/appsflyer/appsflyer-7/src/test/kotlin/com/appsflyer/share/AppsFlyerConsent.kt @@ -0,0 +1,8 @@ +package com.appsflyer.share + +class AppsFlyerConsent( + val isUserSubjectToGDPR: Boolean?, + val hasConsentForDataUsage: Boolean?, + val hasConsentForAdsPersonalization: Boolean?, + val hasConsentForAdStorage: Boolean?, +) diff --git a/kits/appsflyer/appsflyer-7/src/test/kotlin/com/mparticle/kits/AppsflyerKitTests.kt b/kits/appsflyer/appsflyer-7/src/test/kotlin/com/mparticle/kits/AppsflyerKitTests.kt new file mode 100644 index 000000000..a38584815 --- /dev/null +++ b/kits/appsflyer/appsflyer-7/src/test/kotlin/com/mparticle/kits/AppsflyerKitTests.kt @@ -0,0 +1,822 @@ +package com.mparticle.kits + +import android.app.Activity +import android.content.Context +import android.net.Uri +import com.appsflyer.AppsFlyerLib +import com.mparticle.MParticle +import com.mparticle.MParticleOptions +import com.mparticle.commerce.CommerceEvent +import com.mparticle.commerce.Product +import com.mparticle.commerce.TransactionAttributes +import com.mparticle.consent.ConsentState +import com.mparticle.consent.GDPRConsent +import com.mparticle.identity.IdentityApi +import com.mparticle.identity.MParticleUser +import com.mparticle.internal.CoreCallbacks +import com.mparticle.internal.CoreCallbacks.KitListener +import junit.framework.Assert.assertEquals +import junit.framework.TestCase +import org.json.JSONArray +import org.json.JSONException +import org.json.JSONObject +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.Mockito.mock +import org.mockito.MockitoAnnotations +import java.lang.ref.WeakReference +import java.lang.reflect.Method + +class AppsflyerKitTests { + private var kit = AppsFlyerKit() + private var appsflyer = AppsFlyerLib() + + @Mock + lateinit var user: MParticleUser + + @Before + @Throws(JSONException::class) + fun before() { + AppsFlyerLib.clearInstance() + kit = AppsFlyerKit() + MockitoAnnotations.initMocks(this) + MParticle.setInstance(mock(MParticle::class.java)) + Mockito + .`when`(MParticle.getInstance()?.Identity()) + .thenReturn( + mock( + IdentityApi::class.java, + ), + ) + val kitManager = + KitManagerImpl( + mock( + Context::class.java, + ), + null, + emptyCoreCallbacks, + mock(MParticleOptions::class.java), + ) + kit.kitManager = kitManager + kit.configuration = + KitConfiguration.createKitConfiguration(JSONObject().put("id", "-1")) + appsflyer = AppsFlyerLib.getInstance(null)!! + } + + @Test + @Throws(Exception::class) + fun testGetName() { + val name = kit.name + Assert.assertTrue(name.isNotEmpty()) + } + + @Test + @Throws(Exception::class) + fun testParseSharingFilterForPartners_returnsListForValidJson() { + val method = + AppsFlyerKit::class.java.getDeclaredMethod( + "parseSharingFilterForPartners", + String::class.java, + ) + method.isAccessible = true + val result = method.invoke(kit, """["partner_1", "partner_2"]""") + Assert.assertEquals(listOf("partner_1", "partner_2"), result) + } + + @Test + @Throws(Exception::class) + fun testParseSharingFilterForPartners_returnsNullForEmptyInput() { + val method = + AppsFlyerKit::class.java.getDeclaredMethod( + "parseSharingFilterForPartners", + String::class.java, + ) + method.isAccessible = true + Assert.assertNull(method.invoke(kit, "")) + Assert.assertNull(method.invoke(kit, null)) + } + + @Test + @Throws(Exception::class) + fun testParseSharingFilterForPartners_returnsNullForInvalidJson() { + val method = + AppsFlyerKit::class.java.getDeclaredMethod( + "parseSharingFilterForPartners", + String::class.java, + ) + method.isAccessible = true + Assert.assertNull(method.invoke(kit, "not a json array")) + } + + @Test + @Throws(Exception::class) + fun testParseSharingFilterForPartners_stripsBackslashes() { + val method = + AppsFlyerKit::class.java.getDeclaredMethod( + "parseSharingFilterForPartners", + String::class.java, + ) + method.isAccessible = true + val result = method.invoke(kit, """[\"test_1\", \"test_2\"]""") + Assert.assertEquals(listOf("test_1", "test_2"), result) + } + + /** + * Kit *should* throw an exception when they're initialized with the wrong settings. + * + */ + @Test + @Throws(Exception::class) + fun testOnKitCreate() { + var e: Throwable? = null + try { + val settings = HashMap() + settings["fake setting"] = "fake" + kit.onKitCreate(settings as Map, mock(Context::class.java)) + } catch (ex: Throwable) { + e = ex + } + Assert.assertNotNull(e) + } + + @Test + @Throws(Exception::class) + fun testClassName() { + val options = mock(MParticleOptions::class.java) + val factory = KitIntegrationFactory(options) + val integrations = factory.supportedKits.values + val className = kit.javaClass.name + for (integration in integrations) { + if (integration.name == className) { + return + } + } + Assert.fail("$className not found as a known integration.") + } + + @Test + @Throws(Exception::class) + fun testGenerateSkuString() { + MParticle.setInstance(mock(MParticle::class.java)) + Mockito + .`when`(MParticle.getInstance()?.environment) + .thenReturn(MParticle.Environment.Production) + Assert.assertNull(AppsFlyerKit.generateProductIdList(null)) + val product = Product.Builder("foo-name", "foo-sku", 50.0).build() + val event = + CommerceEvent + .Builder(Product.PURCHASE, product) + .transactionAttributes(TransactionAttributes("foo")) + .build() + assertEquals(mutableListOf("foo-sku"), AppsFlyerKit.generateProductIdList(event)) + val product2 = Product.Builder("foo-name-2", "foo-sku-2", 50.0).build() + val event2 = + CommerceEvent + .Builder(Product.PURCHASE, product) + .addProduct(product2) + .transactionAttributes(TransactionAttributes("foo")) + .build() + assertEquals( + mutableListOf("foo-sku", "foo-sku-2"), + AppsFlyerKit.generateProductIdList(event2), + ) + val product3 = Product.Builder("foo-name-3", "foo-sku-,3", 50.0).build() + val event3 = + CommerceEvent + .Builder(Product.PURCHASE, product) + .addProduct(product2) + .addProduct(product3) + .transactionAttributes(TransactionAttributes("foo")) + .build() + assertEquals( + mutableListOf("foo-sku", "foo-sku-2", "foo-sku-%2C3"), + AppsFlyerKit.generateProductIdList(event3), + ) + } + + @Test + @Throws(Exception::class) + fun testConsentWhenGDPRNotApplied() { + val map = HashMap() + map["defaultAdStorageConsent"] = "Granted" + map["gdprApplies"] = "false" + map["consentMapping"] = + "[{\\\"jsmap\\\":null,\\\"map\\\":\\\"Performance\\\",\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"ad_user_data\\\"},{\\\"jsmap\\\":null,\\\"map\\\":\\\"Marketing\\\",\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"ad_personalization\\\"},{\\\"jsmap\\\":null,\\\"map\\\":\\\"testconsent\\\",\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"ad_storage\\\"}]" + map["defaultAdUserDataConsent"] = "Denied" + map["defaultAdPersonalizationConsent"] = "Denied" + + kit.configuration = + KitConfiguration.createKitConfiguration(JSONObject().put("as", JSONObject(map as Map<*, *>))) + + val marketingConsent = + GDPRConsent + .builder(false) + .document("Test consent") + .location("17 Cherry Tree Lane") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + val state = + ConsentState + .builder() + .addGDPRConsentState("Marketing", marketingConsent) + .build() + kit.onConsentStateUpdated(state, state) + + val afConsentResults = appsflyer.getConsentState() + val expectedConsentValue = + afConsentResults + .getValue("isUserSubjectToGDPR") + TestCase.assertEquals(false, expectedConsentValue) + + val notExpectedConsentKey = + afConsentResults.containsKey("hasConsentForDataUsage") + TestCase.assertEquals(false, notExpectedConsentKey) + + val notExpectedConsentKey2 = + afConsentResults.containsKey("hasConsentForAdsPersonalization") + TestCase.assertEquals(false, notExpectedConsentKey2) + + val notExpectedConsentKey3 = + afConsentResults.containsKey("hasConsentForAdStorage") + TestCase.assertEquals(false, notExpectedConsentKey3) + } + + @Test + @Throws(Exception::class) + fun testConsentWhenGDPRAppliedWithoutConsentDefaults() { + val map = HashMap() + map["defaultAdStorageConsent"] = "Unspecified" + map["gdprApplies"] = "true" + map["consentMapping"] = + "[{\\\"jsmap\\\":null,\\\"map\\\":\\\"Performance\\\",\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"ad_user_data\\\"},{\\\"jsmap\\\":null,\\\"map\\\":\\\"Marketing\\\",\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"ad_personalization\\\"},{\\\"jsmap\\\":null,\\\"map\\\":\\\"testconsent\\\",\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"ad_storage\\\"}]" + map["defaultAdUserDataConsent"] = "Unspecified" + map["defaultAdPersonalizationConsent"] = "Unspecified" + + kit.configuration = + KitConfiguration.createKitConfiguration(JSONObject().put("as", JSONObject(map as Map<*, *>))) + + val marketingConsent = + GDPRConsent + .builder(false) + .document("Test consent") + .location("17 Cherry Tree Lane") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + val state = + ConsentState + .builder() + .addGDPRConsentState("test1", marketingConsent) + .build() + kit.onConsentStateUpdated(state, state) + + val afConsentResults = appsflyer.getConsentState() + val expectedConsentValue = + afConsentResults + .getValue("isUserSubjectToGDPR") + TestCase.assertEquals(true, expectedConsentValue) + + val notExpectedConsentKey = + afConsentResults.containsKey("hasConsentForDataUsage") + TestCase.assertEquals(false, notExpectedConsentKey) + + val notExpectedConsentKey2 = + afConsentResults.containsKey("hasConsentForAdsPersonalization") + TestCase.assertEquals(false, notExpectedConsentKey2) + + val notExpectedConsentKey3 = + afConsentResults.containsKey("hasConsentForAdStorage") + TestCase.assertEquals(false, notExpectedConsentKey3) + } + + @Test + @Throws(Exception::class) + fun testConsentWhenGDPRAppliedWithConsentDefaults() { + val map = HashMap() + map["defaultAdStorageConsent"] = "Granted" + map["gdprApplies"] = "true" + map["consentMapping"] = + "[{\\\"jsmap\\\":null,\\\"map\\\":\\\"Performance\\\",\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"ad_user_data\\\"},{\\\"jsmap\\\":null,\\\"map\\\":\\\"Marketing\\\",\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"ad_personalization\\\"},{\\\"jsmap\\\":null,\\\"map\\\":\\\"testconsent\\\",\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"ad_storage\\\"}]" + map["defaultAdUserDataConsent"] = "Denied" + map["defaultAdPersonalizationConsent"] = "Granted" + + kit.configuration = + KitConfiguration.createKitConfiguration(JSONObject().put("as", JSONObject(map as Map<*, *>))) + + val marketingConsent = + GDPRConsent + .builder(false) + .document("Test consent") + .location("17 Cherry Tree Lane") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + val state = + ConsentState + .builder() + .addGDPRConsentState("test1", marketingConsent) + .build() + kit.onConsentStateUpdated(state, state) + + val afConsentResults = appsflyer.getConsentState() + val expectedConsentValue = + afConsentResults + .getValue("isUserSubjectToGDPR") + TestCase.assertEquals(true, expectedConsentValue) + + val expectedConsentValue2 = + afConsentResults + .getValue("hasConsentForDataUsage") + TestCase.assertEquals(false, expectedConsentValue2) + + val expectedConsentValue3 = + afConsentResults + .getValue("hasConsentForAdsPersonalization") + TestCase.assertEquals(true, expectedConsentValue3) + + val expectedConsentValue4 = + afConsentResults + .getValue("hasConsentForAdStorage") + TestCase.assertEquals(true, expectedConsentValue4) + } + + @Test + @Throws(Exception::class) + fun testConsentMapping() { + val map = HashMap() + map["defaultAdStorageConsent"] = "Granted" + map["gdprApplies"] = "true" + map["consentMapping"] = + "[{\\\"jsmap\\\":null,\\\"map\\\":\\\"Performance\\\",\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"ad_user_data\\\"},{\\\"jsmap\\\":null,\\\"map\\\":\\\"Marketing\\\",\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"ad_personalization\\\"},{\\\"jsmap\\\":null,\\\"map\\\":\\\"testconsent\\\",\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"ad_storage\\\"}]" + map["defaultAdUserDataConsent"] = "Denied" + map["defaultAdPersonalizationConsent"] = "Granted" + + kit.configuration = + KitConfiguration.createKitConfiguration(JSONObject().put("as", JSONObject(map as Map<*, *>))) + + val performanceConsent = + GDPRConsent + .builder(true) + .document("Test consent") + .location("17 Cherry Tree Lane") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + val marketingConsent = + GDPRConsent + .builder(false) + .document("Test consent") + .location("17 Cherry Tree Lane") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + val testConsent = + GDPRConsent + .builder(false) + .document("Test consent") + .location("17 Cherry Tree Lane") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + val state = + ConsentState + .builder() + .addGDPRConsentState("Performance", performanceConsent) + .addGDPRConsentState("Marketing", marketingConsent) + .addGDPRConsentState("testconsent", testConsent) + .build() + kit.onConsentStateUpdated(state, state) + + val afConsentResults = appsflyer.getConsentState() + val expectedConsentValue = + afConsentResults + .getValue("isUserSubjectToGDPR") + TestCase.assertEquals(true, expectedConsentValue) + + val expectedConsentValue2 = + afConsentResults + .getValue("hasConsentForDataUsage") + TestCase.assertEquals(true, expectedConsentValue2) + + val expectedConsentValue3 = + afConsentResults + .getValue("hasConsentForAdsPersonalization") + TestCase.assertEquals(false, expectedConsentValue3) + + val expectedConsentValue4 = + afConsentResults + .getValue("hasConsentForAdStorage") + TestCase.assertEquals(false, expectedConsentValue4) + } + + @Test + fun onConsentStateUpdatedTestPerformance_And_Marketing_are_true() { + val map = HashMap() + map["defaultAdStorageConsent"] = "Granted" + map["gdprApplies"] = "true" + map["consentMapping"] = + "[{\\\"jsmap\\\":null,\\\"map\\\":\\\"Performance\\\",\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"ad_user_data\\\"},{\\\"jsmap\\\":null,\\\"map\\\":\\\"Marketing\\\",\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"ad_personalization\\\"},{\\\"jsmap\\\":null,\\\"map\\\":\\\"testconsent\\\",\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"ad_storage\\\"}]" + map["defaultAdUserDataConsent"] = "Denied" + map["defaultAdPersonalizationConsent"] = "Granted" + + kit.configuration = + KitConfiguration.createKitConfiguration(JSONObject().put("as", JSONObject(map as Map<*, *>))) + + val performanceConsent = + GDPRConsent + .builder(true) + .document("Test consent") + .location("17 Cherry Tree Lane") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + + val marketingConsent = + GDPRConsent + .builder(true) + .document("Test consent") + .location("17 Cherry Tree Lane") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + + val state = + ConsentState + .builder() + .addGDPRConsentState("Performance", performanceConsent) + .addGDPRConsentState("Marketing", marketingConsent) + .build() + kit.onConsentStateUpdated(state, state) + + val afConsentResults = appsflyer.getConsentState() + val expectedConsentValue = + afConsentResults + .getValue("isUserSubjectToGDPR") + TestCase.assertEquals(true, expectedConsentValue) + + val expectedConsentValue2 = + afConsentResults + .getValue("hasConsentForDataUsage") + TestCase.assertEquals(true, expectedConsentValue2) + + val expectedConsentValue3 = + afConsentResults + .getValue("hasConsentForAdsPersonalization") + TestCase.assertEquals(true, expectedConsentValue3) + + val expectedConsentValue4 = + afConsentResults + .getValue("hasConsentForAdStorage") + TestCase.assertEquals(true, expectedConsentValue4) + } + + @Test + fun onConsentStateUpdatedTest_When_No_Defaults_Values() { + val map = HashMap() + map["gdprApplies"] = "true" + map["consentMapping"] = + "[{\\\"jsmap\\\":null,\\\"map\\\":\\\"Performance\\\",\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"ad_user_data\\\"},{\\\"jsmap\\\":null,\\\"map\\\":\\\"Marketing\\\",\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"ad_personalization\\\"},{\\\"jsmap\\\":null,\\\"map\\\":\\\"testconsent\\\",\\\"maptype\\\":\\\"ConsentPurposes\\\",\\\"value\\\":\\\"ad_storage\\\"}]" + + kit.configuration = + KitConfiguration.createKitConfiguration(JSONObject().put("as", JSONObject(map as Map<*, *>))) + + val marketingConsent = + GDPRConsent + .builder(true) + .document("Test consent") + .location("17 Cherry Tree Lane") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + + val performanceConsent = + GDPRConsent + .builder(true) + .document("parental_consent_agreement_v2") + .location("17 Cherry Tree Lan 3") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + + val state = + ConsentState + .builder() + .addGDPRConsentState("Marketing", marketingConsent) + .addGDPRConsentState("Performance", performanceConsent) + .build() + kit.onConsentStateUpdated(state, state) + val afConsentResults = appsflyer.getConsentState() + val expectedConsentValue = + afConsentResults + .getValue("isUserSubjectToGDPR") + TestCase.assertEquals(true, expectedConsentValue) + + val expectedConsentValue2 = + afConsentResults + .getValue("hasConsentForDataUsage") + TestCase.assertEquals(true, expectedConsentValue2) + + val expectedConsentValue3 = + afConsentResults + .getValue("hasConsentForAdsPersonalization") + TestCase.assertEquals(true, expectedConsentValue3) + + val notExpectedConsentKey = + afConsentResults.containsKey("hasConsentForAdStorage") + TestCase.assertEquals(false, notExpectedConsentKey) + } + + @Test + fun onConsentStateUpdatedTest_When_No_DATA_From_Server() { + val marketingConsent = + GDPRConsent + .builder(true) + .document("Test consent") + .location("17 Cherry Tree Lane") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + + val performanceConsent = + GDPRConsent + .builder(true) + .document("parental_consent_agreement_v2") + .location("17 Cherry Tree Lan 3") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + + val state = + ConsentState + .builder() + .addGDPRConsentState("Marketing", marketingConsent) + .addGDPRConsentState("Performance", performanceConsent) + .build() + kit.onConsentStateUpdated(state, state) + + TestCase.assertEquals(0, appsflyer.getConsentState().size) + } + + @Test + fun onConsentStateUpdatedTest_No_consentMappingSDK() { + val map = HashMap() + map["gdprApplies"] = "true" + map["defaultAdStorageConsent"] = "Granted" + map["defaultAdUserDataConsent"] = "Denied" + map["defaultAdPersonalizationConsent"] = "Denied" + + kit.configuration = + KitConfiguration.createKitConfiguration(JSONObject().put("as", JSONObject(map as Map<*, *>))) + + val marketingConsent = + GDPRConsent + .builder(true) + .document("Test consent") + .location("17 Cherry Tree Lane") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + + val performanceConsent = + GDPRConsent + .builder(true) + .document("parental_consent_agreement_v2") + .location("17 Cherry Tree Lan 3") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + + val state = + ConsentState + .builder() + .addGDPRConsentState("Marketing", marketingConsent) + .addGDPRConsentState("Performance", performanceConsent) + .build() + kit.onConsentStateUpdated(state, state) + + val afConsentResults = appsflyer.getConsentState() + val expectedConsentValue = + afConsentResults + .getValue("isUserSubjectToGDPR") + TestCase.assertEquals(true, expectedConsentValue) + + val expectedConsentValue2 = + afConsentResults + .getValue("hasConsentForDataUsage") + TestCase.assertEquals(false, expectedConsentValue2) + + val expectedConsentValue3 = + afConsentResults + .getValue("hasConsentForAdsPersonalization") + TestCase.assertEquals(false, expectedConsentValue3) + + val expectedConsentValue4 = + afConsentResults + .getValue("hasConsentForAdStorage") + TestCase.assertEquals(true, expectedConsentValue4) + } + + @Test + fun onConsentStateUpdatedTest_When_default_is_Unspecified_And_No_consentMappingSDK_And_GDPR_Not_Applied() { + val map = HashMap() + map["gdprApplies"] = "false" + map["defaultAdStorageConsent"] = "Unspecified" + map["defaultAdUserDataConsent"] = "Unspecified" + map["defaultAdPersonalizationConsent"] = "Unspecified" + + kit.configuration = + KitConfiguration.createKitConfiguration(JSONObject().put("as", JSONObject(map as Map<*, *>))) + + val marketingConsent = + GDPRConsent + .builder(true) + .document("Test consent") + .location("17 Cherry Tree Lane") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + + val performanceConsent = + GDPRConsent + .builder(true) + .document("parental_consent_agreement_v2") + .location("17 Cherry Tree Lan 3") + .hardwareId("IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702") + .build() + val state = + ConsentState + .builder() + .addGDPRConsentState("Marketing", marketingConsent) + .addGDPRConsentState("Performance", performanceConsent) + .build() + kit.onConsentStateUpdated(state, state) + + TestCase.assertEquals(1, appsflyer.getConsentState().size) + val afConsentResults = appsflyer.getConsentState() + val expectedConsentValue = + afConsentResults + .getValue("isUserSubjectToGDPR") + TestCase.assertEquals(false, expectedConsentValue) + } + + @Test + fun testParseToNestedMap_When_JSON_Is_INVALID() { + var jsonInput = + "{'GDPR':{'marketing':'{:false,'timestamp':1711038269644:'Test consent','location':'17 Cherry Tree Lane','hardware_id':'IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702'}','performance':'{'consented':true,'timestamp':1711038269644,'document':'parental_consent_agreement_v2','location':'17 Cherry Tree Lan 3','hardware_id':'IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702'}'},'CCPA':'{'consented':true,'timestamp':1711038269644,'document':'ccpa_consent_agreement_v3','location':'17 Cherry Tree Lane','hardware_id':'IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702'}'}" + + val method: Method = + AppsFlyerKit::class.java.getDeclaredMethod( + "parseToNestedMap", + String::class.java, + ) + method.isAccessible = true + val result = method.invoke(kit, jsonInput) + Assert.assertEquals(mutableMapOf(), result) + } + + @Test + fun testParseToNestedMap_When_JSON_Is_Empty() { + var jsonInput = "" + + val method: Method = + AppsFlyerKit::class.java.getDeclaredMethod( + "parseToNestedMap", + String::class.java, + ) + method.isAccessible = true + val result = method.invoke(kit, jsonInput) + Assert.assertEquals(mutableMapOf(), result) + } + + @Test + fun testSearchKeyInNestedMap_When_Input_Key_Is_Empty_String() { + val map = + mapOf( + "GDPR" to true, + "marketing" to + mapOf( + "consented" to false, + "document" to + mapOf( + "timestamp" to 1711038269644, + ), + ), + ) + val method: Method = + AppsFlyerKit::class.java.getDeclaredMethod( + "searchKeyInNestedMap", + Map::class.java, + Any::class.java, + ) + method.isAccessible = true + val result = method.invoke(kit, map, "") + Assert.assertEquals(null, result) + } + + @Test + fun testSearchKeyInNestedMap_When_Input_Is_Empty_Map() { + val emptyMap: Map = emptyMap() + val method: Method = + AppsFlyerKit::class.java.getDeclaredMethod( + "searchKeyInNestedMap", + Map::class.java, + Any::class.java, + ) + method.isAccessible = true + val result = method.invoke(kit, emptyMap, "1") + Assert.assertEquals(null, result) + } + + @Test + fun testParseConsentMapping_When_Input_Is_Empty_Json() { + val emptyJson = "" + val method: Method = + AppsFlyerKit::class.java.getDeclaredMethod( + "parseConsentMapping", + String::class.java, + ) + method.isAccessible = true + val result = method.invoke(kit, emptyJson) + Assert.assertEquals(emptyMap(), result) + } + + @Test + fun testParseConsentMapping_When_Input_Is_Invalid_Json() { + var jsonInput = + "{'GDPR':{'marketing':'{:false,'timestamp':1711038269644:'Test consent','location':'17 Cherry Tree Lane','hardware_id':'IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702'}','performance':'{'consented':true,'timestamp':1711038269644,'document':'parental_consent_agreement_v2','location':'17 Cherry Tree Lan 3','hardware_id':'IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702'}'},'CCPA':'{'consented':true,'timestamp':1711038269644,'document':'ccpa_consent_agreement_v3','location':'17 Cherry Tree Lane','hardware_id':'IDFA:a5d934n0-232f-4afc-2e9a-3832d95zc702'}'}" + val method: Method = + AppsFlyerKit::class.java.getDeclaredMethod( + "parseConsentMapping", + String::class.java, + ) + method.isAccessible = true + val result = method.invoke(kit, jsonInput) + Assert.assertEquals(emptyMap(), result) + } + + @Test + fun testParseConsentMapping_When_Input_Is_NULL() { + val method: Method = + AppsFlyerKit::class.java.getDeclaredMethod( + "parseConsentMapping", + String::class.java, + ) + method.isAccessible = true + val result = method.invoke(kit, null) + Assert.assertEquals(emptyMap(), result) + } + + private var emptyCoreCallbacks: CoreCallbacks = + object : CoreCallbacks { + var activity = Activity() + + override fun isBackgrounded(): Boolean = false + + override fun getUserBucket(): Int = 0 + + override fun isEnabled(): Boolean = false + + override fun setIntegrationAttributes( + i: Int, + map: Map, + ) {} + + override fun getIntegrationAttributes(i: Int): Map? = null + + override fun getCurrentActivity(): WeakReference = WeakReference(activity) + + override fun getLatestKitConfiguration(): JSONArray? = null + + override fun getDataplanOptions(): MParticleOptions.DataplanOptions? = null + + override fun isPushEnabled(): Boolean = false + + override fun getPushSenderId(): String? = null + + override fun getPushInstanceId(): String? = null + + override fun getLaunchUri(): Uri? = null + + override fun getLaunchAction(): String? = null + + override fun getKitListener(): KitListener = + object : KitListener { + override fun kitFound(kitId: Int) {} + + override fun kitConfigReceived( + kitId: Int, + configuration: String?, + ) {} + + override fun kitExcluded( + kitId: Int, + reason: String?, + ) {} + + override fun kitStarted(kitId: Int) {} + + override fun onKitApiCalled( + kitId: Int, + used: Boolean?, + vararg objects: Any?, + ) {} + + override fun onKitApiCalled( + methodName: String?, + kitId: Int, + used: Boolean?, + vararg objects: Any?, + ) { + } + } + } +} diff --git a/kits/matrix.json b/kits/matrix.json index 6feaee80f..fd3adff55 100644 --- a/kits/matrix.json +++ b/kits/matrix.json @@ -23,6 +23,12 @@ "kit_project": ":kits:android-appsflyer:appsflyer-6", "example_kotlin_project": ":kits:android-appsflyer:appsflyer-6:example-kotlin" }, + { + "name": "appsflyer-7", + "local_path": "kits/appsflyer/appsflyer-7", + "kit_project": ":kits:android-appsflyer:appsflyer-7", + "example_kotlin_project": ":kits:android-appsflyer:appsflyer-7:example-kotlin" + }, { "name": "apptentive-6", "local_path": "kits/apptentive/apptentive-6", diff --git a/settings-kit-examples.gradle b/settings-kit-examples.gradle index 196e15f87..14ebc29d3 100644 --- a/settings-kit-examples.gradle +++ b/settings-kit-examples.gradle @@ -5,6 +5,7 @@ include ':kits:adjust:adjust-5:example-kotlin', ':kits:adobe:adobe:example-kotlin', ':kits:adobemedia:adobemedia-3:example-kotlin', ':kits:appsflyer:appsflyer-6:example-kotlin', + ':kits:appsflyer:appsflyer-7:example-kotlin', ':kits:apptentive:apptentive-6:example-kotlin', ':kits:apptimize:apptimize-3:example-kotlin', ':kits:braze:braze-38:example-kotlin', @@ -28,6 +29,7 @@ project(':kits:adjust:adjust-5:example-kotlin').projectDir = file('kits/adjust/a project(':kits:adobe:adobe:example-kotlin').projectDir = file('kits/adobe/adobe/example/example-kotlin') project(':kits:adobemedia:adobemedia-3:example-kotlin').projectDir = file('kits/adobemedia/adobemedia-3/example/example-kotlin') project(':kits:appsflyer:appsflyer-6:example-kotlin').projectDir = file('kits/appsflyer/appsflyer-6/example/example-kotlin') +project(':kits:appsflyer:appsflyer-7:example-kotlin').projectDir = file('kits/appsflyer/appsflyer-7/example/example-kotlin') project(':kits:apptentive:apptentive-6:example-kotlin').projectDir = file('kits/apptentive/apptentive-6/example/example-kotlin') project(':kits:apptimize:apptimize-3:example-kotlin').projectDir = file('kits/apptimize/apptimize-3/example/example-kotlin') project(':kits:braze:braze-38:example-kotlin').projectDir = file('kits/braze/braze-38/example/example-kotlin') diff --git a/settings-kits.gradle b/settings-kits.gradle index 9d9143416..9cfb5b691 100644 --- a/settings-kits.gradle +++ b/settings-kits.gradle @@ -5,6 +5,7 @@ include ( ':kits:adobe:adobe', ':kits:adobemedia:adobemedia-3', ':kits:appsflyer:appsflyer-6', + ':kits:appsflyer:appsflyer-7', ':kits:apptentive:apptentive-6', ':kits:apptimize:apptimize-3', //blueshift hosts kit