diff --git a/.gitmodules b/.gitmodules index a132b3d23..9fb7d2421 100644 --- a/.gitmodules +++ b/.gitmodules @@ -34,9 +34,6 @@ [submodule "kits/revealmobile-kit"] path = kits/revealmobile-kit url = git@github.com:mparticle-integrations/mparticle-android-integration-revealmobile.git -[submodule "kits/singular-kit"] - path = kits/singular-kit - url = git@github.com:mparticle-integrations/mparticle-android-integration-singular.git [submodule "kits/skyhook-kit"] path = kits/skyhook-kit url = git@github.com:mparticle-integrations/mparticle-android-integration-skyhook.git diff --git a/.trunk/trunk.yaml b/.trunk/trunk.yaml index ec773bef2..110ec1474 100644 --- a/.trunk/trunk.yaml +++ b/.trunk/trunk.yaml @@ -75,15 +75,15 @@ lint: - kits/apptimize/apptimize-3/** - kits/braze/braze-38/** - kits/clevertap/clevertap-7/** + - kits/comscore/comscore-6/** - kits/iterable/iterable-3/** - kits/ga/ga-23/** - kits/ga4/ga4-23/** - kits/kochava/kochava-5/** - kits/leanplum/leanplum-7/** - - kits/rokt/rokt/** - kits/localytics/localytics-6/** - kits/rokt/rokt/** - - kits/comscore/comscore-6/** + - kits/singular/singular-12/** actions: enabled: - trunk-announce diff --git a/kits/singular-kit b/kits/singular-kit deleted file mode 160000 index 64b3434b1..000000000 --- a/kits/singular-kit +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 64b3434b173692283e6ac5616b1e4584deeff19e diff --git a/kits/singular/singular-12/README.md b/kits/singular/singular-12/README.md new file mode 100644 index 000000000..18649d6a8 --- /dev/null +++ b/kits/singular/singular-12/README.md @@ -0,0 +1,32 @@ +## Singular Kit Integration + +This repository contains the [Singular](https://www.singular.net/) integration for the [mParticle Android SDK](https://github.com/mParticle/mparticle-android-sdk). + +### Adding the integration + +1. The singular Kit requires that you add singular's Maven server to your buildscript: + + ``` + repositories { + maven { url "https://maven.singular.net"} + ... + } + ``` + +1. Add the kit dependency to your app's build.gradle: + + ```groovy + dependencies { + implementation 'com.mparticle:android-singular-kit: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 `"Singular detected"` in the output of `adb logcat`. +3. Reference mParticle's integration docs below to enable the integration. + +### Documentation + +[Singular integration](https://docs.mparticle.com/integrations/singular/event/) + +### License + +[Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0) diff --git a/kits/singular/singular-12/build.gradle b/kits/singular/singular-12/build.gradle new file mode 100644 index 000000000..d9431f556 --- /dev/null +++ b/kits/singular/singular-12/build.gradle @@ -0,0 +1,77 @@ +buildscript { + ext.kotlin_version = '2.0.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-singular" + 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' + +repositories { + maven { + url 'https://maven.singular.net' + } + mavenCentral() +} + +android { + namespace 'com.mparticle.kits.singular' + buildFeatures { + buildConfig = true + } + defaultConfig { + minSdkVersion 16 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + kotlinOptions { + jvmTarget = '17' + } + testOptions { + unitTests.all { + jvmArgs += ['--add-opens', 'java.base/java.lang=ALL-UNNAMED'] + } + } +} + +dependencies { + api 'com.singular.sdk:singular_sdk:12.5.4' + + androidTestImplementation 'androidx.test:runner:1.5.2' + testImplementation 'org.powermock:powermock-core:2.0.9' + testImplementation 'org.powermock:powermock-api-mockito2:2.0.2' + testImplementation 'org.powermock:powermock-module-junit4-rule:2.0.9' + testImplementation 'org.powermock:powermock-module-junit4:2.0.9' + testImplementation 'org.powermock:powermock-classloading-xstream:2.0.2' + testImplementation "org.robolectric:robolectric:4.3.1" + testImplementation 'org.json:json:20220320' +} diff --git a/kits/singular/singular-12/consumer-proguard.pro b/kits/singular/singular-12/consumer-proguard.pro new file mode 100644 index 000000000..2a90e0f4c --- /dev/null +++ b/kits/singular/singular-12/consumer-proguard.pro @@ -0,0 +1 @@ +# TODO: Add rules to exclude your SDK classes from proguard in implementing apps \ No newline at end of file diff --git a/kits/singular/singular-12/gradle.properties b/kits/singular/singular-12/gradle.properties new file mode 100644 index 000000000..edb1202c3 --- /dev/null +++ b/kits/singular/singular-12/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/singular/singular-12/gradle/wrapper/gradle-wrapper.jar b/kits/singular/singular-12/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..41d9927a4 Binary files /dev/null and b/kits/singular/singular-12/gradle/wrapper/gradle-wrapper.jar differ diff --git a/kits/singular/singular-12/gradle/wrapper/gradle-wrapper.properties b/kits/singular/singular-12/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..e1bef7e87 --- /dev/null +++ b/kits/singular/singular-12/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/singular/singular-12/gradlew b/kits/singular/singular-12/gradlew new file mode 100755 index 000000000..1b6c78733 --- /dev/null +++ b/kits/singular/singular-12/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/singular/singular-12/gradlew.bat b/kits/singular/singular-12/gradlew.bat new file mode 100644 index 000000000..107acd32c --- /dev/null +++ b/kits/singular/singular-12/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/singular/singular-12/libs/java-json.jar b/kits/singular/singular-12/libs/java-json.jar new file mode 100755 index 000000000..2f211e366 Binary files /dev/null and b/kits/singular/singular-12/libs/java-json.jar differ diff --git a/kits/singular/singular-12/libs/testutils.aar b/kits/singular/singular-12/libs/testutils.aar new file mode 100644 index 000000000..cf49b4189 Binary files /dev/null and b/kits/singular/singular-12/libs/testutils.aar differ diff --git a/kits/singular/singular-12/settings.gradle.kts b/kits/singular/singular-12/settings.gradle.kts new file mode 100644 index 000000000..bfecd119f --- /dev/null +++ b/kits/singular/singular-12/settings.gradle.kts @@ -0,0 +1,2 @@ +rootProject.name = "android-singular-kit" +include(":") diff --git a/kits/singular/singular-12/src/main/AndroidManifest.xml b/kits/singular/singular-12/src/main/AndroidManifest.xml new file mode 100644 index 000000000..c4e6c98d7 --- /dev/null +++ b/kits/singular/singular-12/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/kits/singular/singular-12/src/main/kotlin/com/mparticle/kits/SingularKit.kt b/kits/singular/singular-12/src/main/kotlin/com/mparticle/kits/SingularKit.kt new file mode 100644 index 000000000..280fd6aa3 --- /dev/null +++ b/kits/singular/singular-12/src/main/kotlin/com/mparticle/kits/SingularKit.kt @@ -0,0 +1,507 @@ +package com.mparticle.kits + +import android.app.Activity +import android.content.Context +import android.content.Intent +import android.os.Bundle +import android.util.Log +import com.mparticle.AttributionResult +import com.mparticle.MPEvent +import com.mparticle.MParticle +import com.mparticle.MParticle.IdentityType +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.ActivityListener +import com.mparticle.kits.KitIntegration.ApplicationStateListener +import com.mparticle.kits.KitIntegration.AttributeListener +import com.mparticle.kits.KitIntegration.CommerceListener +import com.mparticle.kits.KitIntegration.EventListener +import com.mparticle.kits.KitIntegration.PushListener +import com.mparticle.kits.KitIntegration.UserAttributeListener +import com.singular.sdk.SDIDAccessorHandler +import com.singular.sdk.Singular +import com.singular.sdk.SingularConfig +import com.singular.sdk.SingularDeviceAttributionHandler +import com.singular.sdk.internal.SingularLog +import org.json.JSONException +import org.json.JSONObject +import java.math.BigDecimal + +open class SingularKit : + KitIntegration(), + ActivityListener, + EventListener, + PushListener, + CommerceListener, + ApplicationStateListener, + UserAttributeListener, + AttributeListener { + interface DeviceAttributionCallback : SingularDeviceAttributionHandler + + interface SdidAccessorHandler : SDIDAccessorHandler + + private val logger = SingularLog.getLogger(Singular::class.java.simpleName) + private var isInitialized = false + private var deviceToken: String? = null + + //endregion + //region Kit Integration Implementation + override fun onKitCreate( + settings: Map, + context: Context, + ): List { + // Returning the reporting message to state that the method was successful and + // Preventing from the mParticle Kit to retry to activate to method. + val messages: MutableList = ArrayList() + messages.add( + ReportingMessage( + this, + ReportingMessage.MessageType.APP_STATE_TRANSITION, + System.currentTimeMillis(), + null, + ), + ) + return messages + } + + fun buildSingularConfig(settings: Map?): SingularConfig? = + try { + val singularKey = settings?.get(API_KEY) + val singularSecret = settings?.get(API_SECRET) + + // Getting the DDL timeout from the settings. If does not exist, use 60(S) as default. + val ddlTimeout = settings?.get(DDL_TIMEOUT) + var ddlHandlerTimeoutSec = 60L + if (!KitUtils.isEmpty(ddlTimeout)) { + try { + if (ddlTimeout != null) { + ddlHandlerTimeoutSec = ddlTimeout.toLong() + } + } catch (unableToGetDDLTimeout: Exception) { + } + } + val config = SingularConfig(singularKey, singularSecret) + config.withDDLTimeoutInSec(ddlHandlerTimeoutSec) + val activity = currentActivity.get() + if (activity != null) { + val intent = activity.intent + config.withSingularLink(intent) { singularLinkParams -> + val attributionResult = AttributionResult() + attributionResult.serviceProviderId = MParticle.ServiceProviders.SINGULAR + attributionResult.link = singularLinkParams.deeplink + try { + val linkParams = JSONObject() + linkParams.put(PASSTHROUGH, singularLinkParams.passthrough) + linkParams.put(IS_DEFERRED, singularLinkParams.isDeferred) + if (singularLinkParams.urlParameters != null) { + linkParams.put( + QUERY_PARAMS, + (singularLinkParams.urlParameters as Map<*, *>?)?.let { + JSONObject( + it, + ) + }, + ) + } + attributionResult.parameters = linkParams + } catch (e: JSONException) { + e.printStackTrace() + } + kitManager.onResult(attributionResult) + } + } + + // If the environment is in development mode, enable logging. + if (MPUtility.isDevEnv()) { + config.withLoggingEnabled() + config.withLogLevel(Log.DEBUG) + } + + config.deviceAttributionHandler = deviceAttributionCallback + + config.withCustomSdid(customSdid, sdidAccessorHandler) + + Singular.setWrapperNameAndVersion(MPARTICLE_WRAPPER_NAME, MPARTICLE_WRAPPER_VERSION) + config + } catch (ex: Exception) { + logger.error(CANT_BUILD_SINGULAR_CONFIG_MESSAGE, ex) + null + } + + override fun setOptOut(b: Boolean): List = emptyList() + + override fun getName(): String = KIT_NAME + + override fun setInstallReferrer(intent: Intent) {} + + //endregion + //region Activity Listener Implementation + override fun onActivityResumed(activity: Activity): List { + Singular.onActivityResumed() + return emptyList() + } + + override fun onActivityPaused(activity: Activity): List { + Singular.onActivityPaused() + return emptyList() + } + + //region Unimplemented (Empty Methods) + override fun onActivityCreated( + activity: Activity, + bundle: Bundle?, + ): List { + initializeSingular() + return emptyList() + } + + override fun onActivityStarted(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() + + //endregion + //endregion + //region Event Listener Implementation + override fun logEvent(mpEvent: MPEvent): List? { + val messages: MutableList = ArrayList() + executeIfSingularInitialized({ + val eventName = mpEvent.eventName + val eventInfo = mpEvent.customAttributes + + // Logging the event with the Singular API + val eventStatus: Boolean = + if (!eventInfo.isNullOrEmpty()) { + Singular.eventJSON(eventName, JSONObject(eventInfo)) + } else { + Singular.event(eventName) + } + + // If the Singular event logging was successful, return the message to the mParticle Kit + // So it won't retry the event + if (eventStatus) { + messages.add(ReportingMessage.fromEvent(this, mpEvent)) + } + }, forceInitSingular = true, "logEvent") + return messages + } + + //region Unimplemented (Empty Methods) + override fun leaveBreadcrumb(s: String): List = emptyList() + + override fun logError( + s: String, + map: Map, + ): List = emptyList() + + override fun logException( + e: Exception, + map: Map, + s: String, + ): List = emptyList() + + override fun logScreen( + s: String, + map: Map, + ): List = emptyList() + + //endregion + //endregion + //region Push Listener Implementation + override fun onPushRegistration( + deviceToken: String, + senderId: String, + ): Boolean { + // Saving the registration token to determine when the user uninstalls the app. + this.deviceToken = deviceToken + executeIfSingularInitialized({ + if (MPUtility.isFirebaseAvailable()) { + Singular.setFCMDeviceToken(deviceToken) + } + }, forceInitSingular = false, "onPushRegistration") + return true + } + + private fun executeIfSingularInitialized( + operation: () -> Unit, + forceInitSingular: Boolean = false, + operationName: String, + ) { + if (isInitialized) { + operation.invoke() + Logger.debug("$operationName executed") + } else { + if (forceInitSingular) { + initializeSingular() + executeIfSingularInitialized(operation, false, operationName) + } else { + Logger.debug("$operationName can't be executed, Singular not initialized") + } + } + } + + private fun initializeSingular() { + if (!isInitialized) { + if (Singular.init(context, buildSingularConfig(settings))) { + currentUser?.id?.toString()?.let { Singular.setCustomUserId(it) } + isInitialized = true + singularSettings = settings + deviceToken?.let { deviceToken -> + if (MPUtility.isFirebaseAvailable()) { + Singular.setFCMDeviceToken(deviceToken) + } + } + } + } + } + + //region Unimplemented (Empty Methods) + override fun willHandlePushMessage(intent: Intent): Boolean = false + + override fun onPushMessageReceived( + context: Context, + intent: Intent, + ) {} + + //endregion + //endregion + //region Commerce Listener Implementation + override fun logEvent(commerceEvent: CommerceEvent): List { + var list = emptyList() + executeIfSingularInitialized(operation = { + if (commerceEvent.productAction == Product.PURCHASE) { + list = handlePurchaseEvents(commerceEvent) + } else { + list = handleNonPurchaseEvents(commerceEvent) + } + }, forceInitSingular = true, "logEvent") + return list + } + + private fun handlePurchaseEvents(commerceEvent: CommerceEvent): List { + val messages: MutableList = ArrayList() + commerceEvent.products?.let { + for (product in it) { + Singular.revenue( + commerceEvent.currency, + product.totalAmount, + product.sku, + product.name, + product.category, + product.quantity.toInt(), + product.unitPrice, + ) + } + } + messages.add(ReportingMessage.fromEvent(this, commerceEvent)) + return messages + } + + private fun handleNonPurchaseEvents(commerceEvent: CommerceEvent): List { + val messages: MutableList = ArrayList() + + // Getting the mParticle events from the commerce event + val eventList = CommerceEventUtils.expand(commerceEvent) + if (eventList != null) { + for (event in eventList) { + try { + logEvent(event)?.let { + for (message in it) { + messages.add(message) + } + } + } catch (e: Exception) { + Logger.warning("Failed to call logCustomEvent to Singular kit: $e") + } + } + } + return messages + } + + //region Unimplemented (Empty Methods) + override fun logLtvIncrease( + bigDecimal: BigDecimal, + bigDecimal1: BigDecimal, + s: String, + map: Map, + ): List = emptyList() + + //endregion + //endregion + //region Deprecated Attribute Listener + override fun setUserAttribute( + key: String, + value: String, + ) { + // TODO: Debug these lines to understand the code + val map = HashMap() + if (MParticle.UserAttributes.AGE == key) { + map[USER_AGE_KEY] = value + } else if (MParticle.UserAttributes.GENDER == key) { + if (value.contains("fe")) { + map[USER_GENDER_KEY] = "f" + } else { + map[USER_GENDER_KEY] = "m" + } + } + if (map.isNotEmpty()) { + executeIfSingularInitialized( + { + Singular.eventJSON("UserAttribute", (map as Map<*, *>?)?.let { JSONObject(it) }) + }, + forceInitSingular = false, + "setUserAttribute", + ) + } + } + + override fun setUserAttributeList( + s: String, + list: List, + ) {} + + override fun onIncrementUserAttribute( + key: String?, + incrementedBy: Number?, + value: String?, + user: FilteredMParticleUser?, + ) { + } + + override fun onRemoveUserAttribute( + s: String, + filteredMParticleUser: FilteredMParticleUser, + ) {} + + override fun onSetUserAttribute( + s: String, + o: Any, + filteredMParticleUser: FilteredMParticleUser, + ) { + } + + override fun onSetUserTag( + s: String, + filteredMParticleUser: FilteredMParticleUser, + ) {} + + override fun onSetUserAttributeList( + s: String, + list: List, + filteredMParticleUser: FilteredMParticleUser, + ) { + } + + override fun onSetAllUserAttributes( + map: Map, + map1: Map>, + filteredMParticleUser: FilteredMParticleUser, + ) { + } + + override fun supportsAttributeLists(): Boolean = false + + override fun onConsentStateUpdated( + consentState: ConsentState, + consentState1: ConsentState, + filteredMParticleUser: FilteredMParticleUser, + ) { + executeIfSingularInitialized({ + consentState.ccpaConsentState?.let { Singular.limitDataSharing(it.isConsented) } + }, forceInitSingular = false, "onConsentStateUpdated") + } + + override fun setAllUserAttributes( + map: Map, + map1: Map>, + ) {} + + override fun removeUserAttribute(s: String) {} + + override fun setUserIdentity( + identityType: IdentityType, + s: String, + ) { + if (identityType == IdentityType.CustomerId) { + executeIfSingularInitialized({ + Singular.setCustomUserId(s) + }, forceInitSingular = false, "setUserIdentity") + } + } + + override fun removeUserIdentity(identityType: IdentityType) { + if (identityType == IdentityType.CustomerId) { + executeIfSingularInitialized({ + Singular.unsetCustomUserId() + isInitialized = false + }, forceInitSingular = false, "removeUserIdentity") + } + } + + override fun logout(): List { + val messageList: MutableList = ArrayList() + executeIfSingularInitialized({ + Singular.unsetCustomUserId() + isInitialized = false + messageList.add(ReportingMessage.logoutMessage(this)) + }, forceInitSingular = false, "logout") + return messageList + } + + override fun onApplicationForeground() { + // Handling deeplinks when the application resumes from background + initializeSingular() + } + + override fun onApplicationBackground() {} //endregion + + companion object { + //region Members + // Config Consts + private const val API_KEY = "apiKey" + private const val API_SECRET = "secret" + private const val DDL_TIMEOUT = "ddlTimeout" + private const val KIT_NAME = "Singular" + + // User Attribute Consts + private const val USER_AGE_KEY = "age" + private const val USER_GENDER_KEY = "gender" + + // Singular Link Consts + private const val PASSTHROUGH = "passthrough" + private const val IS_DEFERRED = "is_deferred" + private const val QUERY_PARAMS = "query_params" + + // Wrapper Consts + private const val MPARTICLE_WRAPPER_NAME = "mParticle" + private const val MPARTICLE_WRAPPER_VERSION = "1.0.1" + private const val CANT_BUILD_SINGULAR_CONFIG_MESSAGE = + "Can't build Singular Config in the mParticle Kit" + private var singularSettings: Map? = null + + private var deviceAttributionCallback: DeviceAttributionCallback? = null + private var customSdid: String? = null + private var sdidAccessorHandler: SdidAccessorHandler? = null + + @JvmStatic fun setDeviceAttributionCallback(deviceAttributionCallback: DeviceAttributionCallback?) { + this.deviceAttributionCallback = deviceAttributionCallback + } + + @JvmStatic fun setCustomSDID( + customSDID: String?, + sdidAccessorHandler: SdidAccessorHandler?, + ) { + this.customSdid = customSDID + this.sdidAccessorHandler = sdidAccessorHandler + } + } +} diff --git a/kits/singular/singular-12/src/test/kotlin/com/mparticle/kits/KitTests.kt b/kits/singular/singular-12/src/test/kotlin/com/mparticle/kits/KitTests.kt new file mode 100644 index 000000000..880425c0c --- /dev/null +++ b/kits/singular/singular-12/src/test/kotlin/com/mparticle/kits/KitTests.kt @@ -0,0 +1,208 @@ +package com.mparticle.kits + +import com.mparticle.MPEvent +import com.mparticle.MParticleOptions +import com.mparticle.commerce.CommerceEvent +import com.mparticle.commerce.Product +import com.singular.sdk.Singular +import com.singular.sdk.SingularConfig +import org.json.JSONObject +import org.junit.Assert +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.ExpectedException +import org.mockito.Mock +import org.mockito.Mockito +import org.powermock.core.classloader.annotations.PowerMockIgnore +import org.powermock.modules.junit4.rule.PowerMockRule + +@PowerMockIgnore("org.mockito.*", "org.robolectric.*", "android.*") +class KitTests { + //region Tests Setup + private var kit: MockSingularKit? = null + private lateinit var settings: HashMap + private val config: SingularConfig? = null + + @get:Rule + var rule = PowerMockRule() + + @get:Rule + var exception: ExpectedException = ExpectedException.none() + + @Mock + private val reportingMessage: ReportingMessage? = null + + @Before + fun setUp() { + // MockitoAnnotations.initMocks(this); + kit = MockSingularKit() + settings = HashMap() + settings[API_KEY] = "Test" + settings[API_SECRET] = "Test" + } + + //endregion + //region Config Tests + @Test + fun buildConfigWithoutSettings() { + val testConfig = kit?.buildSingularConfig(null) + Assert.assertNull(testConfig) + } + + @Test + fun buildConfigWithEmptySettings() { + val testConfig = kit?.buildSingularConfig(HashMap()) + Assert.assertNull(testConfig) + } + + //endregion + //region Log MPEvent Tests + @Test + fun logEventWithInfo() { + var result: List? = null + try { + // Creating the event + val eventJson = JSONObject() + eventJson.put("eventName", "Testing") + eventJson.put("eventType", "Unknown") + val event = MPEvent.Builder.parseString(eventJson.toString())?.build() + + // Mocking the Kit Methods + Singular.acceptEvent = true + result = event?.let { kit?.logEvent(it) } + } catch (e: Exception) { + e.printStackTrace() + Assert.fail( + String.format( + "logEventWithInfo failed with exception message:%s", + e.message, + ), + ) + } finally { + Assert.assertTrue(!result.isNullOrEmpty()) + } + } + + @Test + fun logEventWithoutInfo() { + var result: List? = null + try { + // Creating the event + val eventJson = JSONObject() + eventJson.put("eventName", "Testing") + eventJson.put("eventType", "Unknown") + val event = MPEvent.Builder.parseString(eventJson.toString())?.build() + if (event != null) { + event.customAttributes?.clear() + + // Mocking the kit Methods + Singular.acceptEvent = true + result = kit?.logEvent(event) + } + } catch (e: Exception) { + e.printStackTrace() + Assert.fail( + String.format( + "logEventWithInfo failed with exception message:%s", + e.message, + ), + ) + } finally { + Assert.assertTrue(!result.isNullOrEmpty()) + } + } + + @Test + fun logEventWithInvalidData() { + val event: MPEvent? = null + val result = event?.let { kit?.logEvent(it) } + if (result != null) { + Assert.assertTrue(result.isEmpty()) + } + } + + //endregion + //region Log CommerceEvent Tests + @Test + fun logCommercePurchaseEvents() { + var result: List? = null + try { + val commerceEvent = + CommerceEvent + .Builder( + Product.PURCHASE, + Product + .Builder("Testing", "Unknown", 2.0) + .quantity(1.0) + .category("Category") + .build(), + ).addProduct(Product.Builder("Unknown", "b", 1.0).build()) + .build() + result = kit?.logEvent(commerceEvent) + } catch (e: Exception) { + e.printStackTrace() + Assert.fail( + String.format( + "logCommercePurchaseEvents failed with exception message:%s", + e.message, + ), + ) + } finally { + Assert.assertTrue(!result.isNullOrEmpty()) + } + } + + @Test + fun logCommerceNonPurchaseEvents() { + var result: List? = null + try { + val commerceEvent = + CommerceEvent + .Builder( + Product.DETAIL, + Product + .Builder("Testing", "Unknown", 2.0) + .quantity(1.0) + .category("Category") + .build(), + ).addProduct(Product.Builder("Unknown", "b", 1.0).build()) + .build() + result = kit?.logEvent(commerceEvent) + } catch (e: Exception) { + e.printStackTrace() + Assert.fail( + String.format( + "logCommerceNonPurchaseEvents failed with exception message:%s", + e.message, + ), + ) + } finally { + Assert.assertTrue(!result.isNullOrEmpty()) + } + } + + //endregion + //region MParticle Kit Factory Tests + //endregion + @Throws(Exception::class) + @Test + fun isSingularIntegrationInFactory() { + val options = Mockito.mock(MParticleOptions::class.java) + val factory = KitIntegrationFactory(options) + val integrations = factory.supportedKits.values + val className = kit?.javaClass?.name.orEmpty() + for (integration in integrations) { + if (integration.name.replace("SingularKit", "MockSingularKit") == className) { + return + } + } + Assert.fail("$className not found as a known integration.") + } + + companion object { + private const val API_KEY = "apiKey" + private const val API_SECRET = "secret" + private const val DDL_TIME_OUT = "ddlTimeout" + } +} diff --git a/kits/singular/singular-12/src/test/kotlin/com/mparticle/kits/MockSingularKit.kt b/kits/singular/singular-12/src/test/kotlin/com/mparticle/kits/MockSingularKit.kt new file mode 100644 index 000000000..d96f8d58a --- /dev/null +++ b/kits/singular/singular-12/src/test/kotlin/com/mparticle/kits/MockSingularKit.kt @@ -0,0 +1,43 @@ +package com.mparticle.kits + +import com.mparticle.MPEvent +import com.mparticle.MParticle +import com.mparticle.commerce.CommerceEvent +import org.json.JSONException +import org.json.JSONObject + +class MockSingularKit : SingularKit() { + override fun logEvent(commerceEvent: CommerceEvent): List = + mutableListOf( + ReportingMessage( + this, + commerceEvent.eventName, + System.currentTimeMillis(), + HashMap(), + ), + ) + + override fun logEvent(mpEvent: MPEvent): List = + mutableListOf( + ReportingMessage( + this, + mpEvent.eventType.toString(), + System.currentTimeMillis(), + HashMap(), + ), + ) + + override fun getConfiguration(): KitConfiguration? { + try { + return KitConfiguration.createKitConfiguration( + JSONObject().put( + "id", + MParticle.ServiceProviders.SINGULAR, + ), + ) + } catch (e: JSONException) { + e.printStackTrace() + } + return null + } +} diff --git a/kits/singular/singular-12/src/test/kotlin/com/singular/sdk/Singular.kt b/kits/singular/singular-12/src/test/kotlin/com/singular/sdk/Singular.kt new file mode 100644 index 000000000..ce69bede8 --- /dev/null +++ b/kits/singular/singular-12/src/test/kotlin/com/singular/sdk/Singular.kt @@ -0,0 +1,6 @@ +package com.singular.sdk + +object Singular { + var acceptEventJson = false + var acceptEvent = false +} diff --git a/settings-kits.gradle b/settings-kits.gradle index 55963e9af..313f5bc96 100644 --- a/settings-kits.gradle +++ b/settings-kits.gradle @@ -30,7 +30,7 @@ include ( ':kits:responsys-kit', ':kits:revealmobile-kit', ':kits:rokt:rokt', - ':kits:singular-kit', + ':kits:singular:singular-12', ':kits:skyhook-kit', //Swrve hosts kit ':kits:taplytics-kit',