// ContextSDK Unity binding for the core SDK: iOS, and on Android com.contextsdk:contextsdk, set up // with SetupWithAPIBackend and your license key. Use it as it is. // For the AdTech SDK (com.contextsdk:contextsdk-adtech) import unity/adtech/ContextSDKBinding.cs // instead: both declare the same class, so a game imports exactly one of them. // ============================================================================ // Platform Configuration // ============================================================================ // Comment out these defines to disable iOS or Android support #if UNITY_IOS && !UNITY_EDITOR #define CONTEXTSDK_IOS #endif #if UNITY_ANDROID && !UNITY_EDITOR #define CONTEXTSDK_ANDROID #endif // ============================================================================ using System.Collections.Generic; using System.Runtime.InteropServices; using AOT; using UnityEngine; using System; #if UNITY_ANDROID using UnityEngine.Android; #endif #nullable enable public static class ContextSDKBinding { #region Configuration /// /// Enable this to see debug logs from ContextSDK binding /// public static bool EnableDebugLogs = false; #if CONTEXTSDK_ANDROID // The package of the Android distribution this file pairs with (see the top of the file). It // decides the setup method: the other one logs an error and sets nothing up. private const string ANDROID_PACKAGE_NAME = "com.contextsdk"; private const string ANDROID_CORE_PACKAGE_NAME = "com.contextsdk"; private const string ANDROID_ADTECH_PACKAGE_NAME = "com.contextsdk.adtech"; #endif #endregion #region Debug Logging private static void DebugLog(string message) { if (EnableDebugLogs) { Debug.Log($"[ContextSDK] {message}"); } } #endregion #region Android Helpers #if CONTEXTSDK_ANDROID private static bool SafeAndroidCall(System.Action action, string errorMessage) { try { action(); return true; } catch (Exception e) { Debug.LogError($"ContextSDK: {errorMessage} - {e.Message}"); return false; } } private static T SafeAndroidCall(System.Func func, string errorMessage, T defaultValue) { try { return func(); } catch (Exception e) { Debug.LogError($"ContextSDK: {errorMessage} - {e.Message}"); return defaultValue; } } #endif #endregion #region iOS P/Invoke Declarations #if CONTEXTSDK_IOS [DllImport("__Internal")] private static extern void contextSDK_setupContextManagerWithAPIBackend(string licenseKey); [DllImport("__Internal")] private static extern void contextSDK_setControlMode(bool enabled); [DllImport("__Internal")] private static extern bool contextSDK_setGlobalCustomSignalInt(string id, int value); [DllImport("__Internal")] private static extern bool contextSDK_setGlobalCustomSignalBool(string id, bool value); [DllImport("__Internal")] private static extern bool contextSDK_setGlobalCustomSignalFloat(string id, float value); [DllImport("__Internal")] private static extern bool contextSDK_setGlobalCustomSignalString(string id, string? value); [DllImport("__Internal")] private static extern int contextSDK_getNextContextID(); #endif #if CONTEXTSDK_ANDROID private static AndroidJavaClass? contextSDKClass; private static AndroidJavaClass ContextSDKClass { get { if (contextSDKClass == null) { contextSDKClass = new AndroidJavaClass($"{ANDROID_PACKAGE_NAME}.ContextSDK"); } return contextSDKClass; } } #endif private static Dictionary pendingContextDelegates = new Dictionary(); private delegate void InternalContextDelegate(int contextID); public delegate void ContextDelegate(Context context); #if CONTEXTSDK_ANDROID private class ContextCallback : AndroidJavaProxy { private readonly ContextDelegate callback; public ContextCallback(ContextDelegate callback) : base("kotlin.jvm.functions.Function1") { this.callback = callback; } public AndroidJavaObject? invoke(AndroidJavaObject contextObj) { Context context = new Context(-1, contextObj); // Marshal the callback to Unity's main thread UnityMainThreadDispatcher.Enqueue(() => callback(context)); return null; } } private class UnityMainThreadDispatcher : MonoBehaviour { private static readonly System.Collections.Queue actions = new System.Collections.Queue(); private static UnityMainThreadDispatcher? instance = null; public static void Initialize() { if (instance == null) { var go = new GameObject("ContextSDKMainThreadDispatcher"); instance = go.AddComponent(); DontDestroyOnLoad(go); } } public static void Enqueue(System.Action action) { lock (actions) { actions.Enqueue(action); } } void Update() { lock (actions) { while (actions.Count > 0) { var action = (System.Action)actions.Dequeue(); action?.Invoke(); } } } } #endif #if UNITY_IOS [DllImport("__Internal")] private static extern int contextSDK_instantContext(string flowName, int customSignalsID, int duration); [DllImport("__Internal")] private static extern int contextSDK_instantContext_flowDuration(string flowName, int customSignalsID); [DllImport("__Internal")] private static extern void contextSDK_fetchContext_string(int contextID, int customSignalsID, string flowName, int duration, InternalContextDelegate callback); [DllImport("__Internal")] private static extern void contextSDK_fetchContext_string_flowDuration(int contextID, int customSignalsID, string flowName, InternalContextDelegate callback); [DllImport("__Internal")] private static extern int contextSDK_recentContext(string flowName); [DllImport("__Internal")] private static extern int contextSDK_trackEvent(string eventName, int customSignalsID); [DllImport("__Internal")] private static extern int contextSDK_trackPageView(string pageName, int customSignalsID); [DllImport("__Internal")] private static extern int contextSDK_trackUserAction(string userActionName, int customSignalsID); [DllImport("__Internal")] private static extern bool contextSDK_context_shouldUpsell(int contextID); [DllImport("__Internal")] private static extern string contextSDK_context_validate(int contextID); [DllImport("__Internal")] private static extern int contextSDK_context_modelOutputsCount(int contextID); [DllImport("__Internal")] private static extern string? contextSDK_context_modelOutputKey(int contextID, int index); [DllImport("__Internal")] private static extern double contextSDK_context_modelOutputValue(int contextID, int index); [DllImport("__Internal")] private static extern int contextSDK_context_sensorDataStatus(int contextID); [DllImport("__Internal")] private static extern bool contextSDK_context_log(int contextID, int outcome); [DllImport("__Internal")] private static extern bool contextSDK_context_logIfNotLoggedYet(int contextID, int outcome); [DllImport("__Internal")] private static extern bool contextSDK_context_appendOutcomeMetadataInt(int contextID, string id, int value); [DllImport("__Internal")] private static extern bool contextSDK_context_appendOutcomeMetadataBool(int contextID, string id, bool value); [DllImport("__Internal")] private static extern bool contextSDK_context_appendOutcomeMetadataFloat(int contextID, string id, float value); [DllImport("__Internal")] private static extern bool contextSDK_context_appendOutcomeMetadataString(int contextID, string id, string value); [DllImport("__Internal")] private static extern bool contextSDK_releaseContext(int contextID); [DllImport("__Internal")] private static extern bool contextSDK_context_addCustomSignalInt(int contextID, string id, int value); [DllImport("__Internal")] private static extern bool contextSDK_context_addCustomSignalBool(int contextID, string id, bool value); [DllImport("__Internal")] private static extern bool contextSDK_context_addCustomSignalFloat(int contextID, string id, float value); [DllImport("__Internal")] private static extern bool contextSDK_context_addCustomSignalString(int contextID, string id, string value); [DllImport("__Internal")] private static extern bool contextSDK_releaseCustomSignals(int contextID); #endif #endregion #region Setup Methods /// /// Sets ContextSDK up with your license key. On Android this needs the core SDK /// (com.contextsdk:contextsdk) and the core binding, unity/ContextSDKBinding.cs. /// public static void SetupWithAPIBackend(string licenseKey) { #if CONTEXTSDK_IOS contextSDK_setupContextManagerWithAPIBackend(licenseKey); #elif CONTEXTSDK_ANDROID if (ANDROID_PACKAGE_NAME == ANDROID_ADTECH_PACKAGE_NAME) { Debug.LogError("ContextSDK: SetupWithAPIBackend takes a license key and needs the core Android SDK " + "and its binding, unity/ContextSDKBinding.cs. This is the AdTech binding: call SetupWithAPIKey " + "with your API key instead. ContextSDK is not set up."); return; } DebugLog($"Setting up with license key"); SetupFromUnity(licenseKey); #endif } /// /// Sets ContextSDK up with your AdTech API key. Android only, and it needs the AdTech SDK /// (com.contextsdk:contextsdk-adtech) and the AdTech binding, unity/adtech/ContextSDKBinding.cs. /// public static void SetupWithAPIKey(string apiKey) { #if CONTEXTSDK_ANDROID if (ANDROID_PACKAGE_NAME == ANDROID_CORE_PACKAGE_NAME) { Debug.LogError("ContextSDK: SetupWithAPIKey takes an AdTech API key and needs the AdTech Android SDK " + "and its binding, unity/adtech/ContextSDKBinding.cs. This is the core binding: call " + "SetupWithAPIBackend with your license key instead. ContextSDK is not set up."); return; } DebugLog($"Setting up with API key"); SetupFromUnity(apiKey); #endif } #if CONTEXTSDK_ANDROID // Both distributions name their Unity setup `setupFromUnity`: core takes the license key, AdTech // the API key. private static void SetupFromUnity(string key) { // Initialize the main thread dispatcher first UnityMainThreadDispatcher.Initialize(); SafeAndroidCall(() => { // The activity Unity runs in has already started, so the SDK starts its session with it // and observes every activity from then on by itself. var activity = AndroidApplication.currentActivity; ContextSDKClass.CallStatic("setupFromUnity", activity, key); }, "Failed to setup"); } #endif #endregion #region Control Mode /// /// Enable or disable control mode. When enabled the SDK will always return true for /// and skip all internal decision making. On Android this is the core SDK's setDecisionsEnabled(!enabled); the /// AdTech Android SDK makes no decisions, so there it logs an error and does nothing. /// /// Whether control mode should be enabled. public static void SetControlMode(bool enabled) { #if CONTEXTSDK_IOS contextSDK_setControlMode(enabled); #elif CONTEXTSDK_ANDROID if (ANDROID_PACKAGE_NAME == ANDROID_CORE_PACKAGE_NAME) { DebugLog($"SetControlMode: {enabled}"); SafeAndroidCall(() => ContextSDKClass.CallStatic("setDecisionsEnabled", !enabled), "Failed to set control mode"); } else { Debug.LogError("ContextSDK: SetControlMode needs the core Android SDK and its binding, " + "unity/ContextSDKBinding.cs. The AdTech Android SDK runs no flow models, so it makes no " + "decisions to turn off. Control mode is not set."); } #endif } #endregion #region Global Custom Signals /// /// Set custom signals that will be used for all ContextSDK events on this instance. We recommend using this to provide generic information that's applicable to all calls, like any AB test information, or other data that may be relevant to calculate the likelihood of an event. Please be sure to not include any PII or other potentially sensitive information. You can overwrite values by using the same id again. /// /// The unique id of the custom signal. This id will be used to identify the custom signal in the ContextSDK backend. It must not be empty or consist only of whitespace, should contain only the letters A-Z and a-z, the digits 0-9 and underscores, and should be at most 128 user-perceived characters (grapheme clusters) long. Every other character is replaced with an underscore when the id is used as a model feature, so two ids such as "cart-value" and "cart.value" risk colliding with each other. The id must not start with "s_"; that prefix is reserved for ContextSDK. Each rule a signal breaks is logged as an error once, since it is an integration mistake; the signal is still set. /// The value of the custom signal public static void SetGlobalCustomSignal(string id, int value) { #if CONTEXTSDK_IOS contextSDK_setGlobalCustomSignalInt(id, value); #elif CONTEXTSDK_ANDROID DebugLog($"SetGlobalCustomSignal: {id} = {value}"); SafeAndroidCall(() => { AndroidJavaObject globalSignals = ContextSDKClass.CallStatic("getGlobalCustomSignals"); globalSignals.Call("set", id, value); }, "Failed to set global custom signal"); #endif } /// /// Set custom signals that will be used for all ContextSDK events on this instance. We recommend using this to provide generic information that's applicable to all calls, like any AB test information, or other data that may be relevant to calculate the likelihood of an event. Please be sure to not include any PII or other potentially sensitive information. You can overwrite values by using the same id again. /// /// The unique id of the custom signal. This id will be used to identify the custom signal in the ContextSDK backend. It must not be empty or consist only of whitespace, should contain only the letters A-Z and a-z, the digits 0-9 and underscores, and should be at most 128 user-perceived characters (grapheme clusters) long. Every other character is replaced with an underscore when the id is used as a model feature, so two ids such as "cart-value" and "cart.value" risk colliding with each other. The id must not start with "s_"; that prefix is reserved for ContextSDK. Each rule a signal breaks is logged as an error once, since it is an integration mistake; the signal is still set. /// The value of the custom signal. It must be finite: NaN or an infinite value cannot be used as a model feature. public static void SetGlobalCustomSignal(string id, float value) { #if CONTEXTSDK_IOS contextSDK_setGlobalCustomSignalFloat(id, value); #elif CONTEXTSDK_ANDROID DebugLog($"SetGlobalCustomSignal: {id} = {value}"); SafeAndroidCall(() => { AndroidJavaObject globalSignals = ContextSDKClass.CallStatic("getGlobalCustomSignals"); globalSignals.Call("set", id, value); }, "Failed to set global custom signal"); #endif } /// /// Set custom signals that will be used for all ContextSDK events on this instance. We recommend using this to provide generic information that's applicable to all calls, like any AB test information, or other data that may be relevant to calculate the likelihood of an event. Please be sure to not include any PII or other potentially sensitive information. You can overwrite values by using the same id again. /// /// The unique id of the custom signal. This id will be used to identify the custom signal in the ContextSDK backend. It must not be empty or consist only of whitespace, should contain only the letters A-Z and a-z, the digits 0-9 and underscores, and should be at most 128 user-perceived characters (grapheme clusters) long. Every other character is replaced with an underscore when the id is used as a model feature, so two ids such as "cart-value" and "cart.value" risk colliding with each other. The id must not start with "s_"; that prefix is reserved for ContextSDK. Each rule a signal breaks is logged as an error once, since it is an integration mistake; the signal is still set. /// The value of the custom signal public static void SetGlobalCustomSignal(string id, bool value) { #if CONTEXTSDK_IOS contextSDK_setGlobalCustomSignalBool(id, value); #elif CONTEXTSDK_ANDROID DebugLog($"SetGlobalCustomSignal: {id} = {value}"); SafeAndroidCall(() => { AndroidJavaObject globalSignals = ContextSDKClass.CallStatic("getGlobalCustomSignals"); globalSignals.Call("set", id, value); }, "Failed to set global custom signal"); #endif } /// /// Set custom signals that will be used for all ContextSDK events on this instance. We recommend using this to provide generic information that's applicable to all calls, like any AB test information, or other data that may be relevant to calculate the likelihood of an event. Please be sure to not include any PII or other potentially sensitive information. You can overwrite values by using the same id again. /// /// The unique id of the custom signal. This id will be used to identify the custom signal in the ContextSDK backend. It must not be empty or consist only of whitespace, should contain only the letters A-Z and a-z, the digits 0-9 and underscores, and should be at most 128 user-perceived characters (grapheme clusters) long. Every other character is replaced with an underscore when the id is used as a model feature, so two ids such as "cart-value" and "cart.value" risk colliding with each other. The id must not start with "s_"; that prefix is reserved for ContextSDK. Each rule a signal breaks is logged as an error once, since it is an integration mistake; the signal is still set. /// The value of the custom signal, or null to remove the signal with this id. public static void SetGlobalCustomSignal(string id, string? value) { #if CONTEXTSDK_IOS contextSDK_setGlobalCustomSignalString(id, value); #elif CONTEXTSDK_ANDROID DebugLog($"SetGlobalCustomSignal: {id} = {value ?? "null (remove)"}"); SafeAndroidCall(() => { AndroidJavaObject globalSignals = ContextSDKClass.CallStatic("getGlobalCustomSignals"); if (value != null) { globalSignals.Call("set", id, value); } else { RemoveAndroidCustomSignal(globalSignals, id); } }, "Failed to set global custom signal"); #endif } #if CONTEXTSDK_ANDROID // Unity signs a null argument as java.lang.Object, so `Call("set", id, null)` looks up // set(String, Object), which does not exist, and fails. This calls set(String, String?) by its // explicit signature instead, which removes the signal. private static void RemoveAndroidCustomSignal(AndroidJavaObject customSignals, string id) { IntPtr setString = AndroidJNI.GetMethodID(customSignals.GetRawClass(), "set", "(Ljava/lang/String;Ljava/lang/String;)V"); ThrowPendingJavaException("CustomSignals.set(String, String) not found"); jvalue[] args = new jvalue[2]; args[0].l = AndroidJNI.NewStringUTF(id); args[1].l = IntPtr.Zero; try { AndroidJNI.CallVoidMethod(customSignals.GetRawObject(), setString, args); ThrowPendingJavaException("CustomSignals.set(String, null) threw"); } finally { AndroidJNI.DeleteLocalRef(args[0].l); } } // A raw AndroidJNI call leaves a Java exception pending instead of throwing it, and the next JNI // call would abort the app, so clear it and throw for SafeAndroidCall to log. private static void ThrowPendingJavaException(string message) { IntPtr thrown = AndroidJNI.ExceptionOccurred(); if (thrown == IntPtr.Zero) { return; } AndroidJNI.ExceptionClear(); AndroidJNI.DeleteLocalRef(thrown); throw new Exception(message); } #endif #endregion #region Context Methods /// /// Get the current context synchronously. The signal may not include all the information, if the duration wasn't reached. /// Be sure that the majority of the times when calling this method, the SDK has already had enough time to reach the duration. /// /// /// Seconds of motion data the context is built from, 2 to 7. Leave it out (null) to use the duration the flow's model was /// trained for, or 3 seconds while the flow has no model. A duration other than the model's means the context runs /// without the model. The AdTech SDK runs no flow models, so on Android it uses 3 seconds when you leave it out. /// public static Context InstantContext(string flowName, CustomSignals? customSignals = null, int? duration = null) { #if CONTEXTSDK_IOS int customSignalsID = customSignals?.contextID ?? -1; int contextID = duration.HasValue ? contextSDK_instantContext(flowName, customSignalsID, duration.Value) : contextSDK_instantContext_flowDuration(flowName, customSignalsID); return new Context(contextID); #elif CONTEXTSDK_ANDROID DebugLog($"InstantContext: {flowName}, duration: {duration?.ToString() ?? "the flow model's"}"); return SafeAndroidCall(() => { AndroidJavaObject customSignalsObj = customSignals?.ToAndroidCustomSignals() ?? new AndroidJavaObject($"{ANDROID_PACKAGE_NAME}.signals.CustomSignals"); AndroidJavaObject contextObj = duration.HasValue ? ContextSDKClass.CallStatic("instantContext", flowName, duration.Value, customSignalsObj) : ContextSDKClass.CallStatic("instantContext", flowName, customSignalsObj); return new Context(-1, contextObj); }, "Failed to get InstantContext", new Context(-1)); #else return new Context(-1); #endif } /// /// Get the current context asynchronously: the callback runs once ContextSDK has collected motion data for the duration, /// right away if it already has. /// /// /// Seconds of motion data the context is built from, 2 to 7. Leave it out (null) to use the duration the flow's model was /// trained for, or 3 seconds while the flow has no model. A duration other than the model's means the context runs /// without the model. The AdTech SDK runs no flow models, so on Android it uses 3 seconds when you leave it out. /// public static void FetchContext(string flowName, ContextDelegate callback, CustomSignals? customSignals = null, int? duration = null) { #if CONTEXTSDK_IOS int customSignalsID = customSignals?.contextID ?? -1; int currentContextID = contextSDK_getNextContextID(); pendingContextDelegates[currentContextID] = callback; if (duration.HasValue) { contextSDK_fetchContext_string(currentContextID, customSignalsID, flowName, duration.Value, HandleContext); } else { contextSDK_fetchContext_string_flowDuration(currentContextID, customSignalsID, flowName, HandleContext); } #elif CONTEXTSDK_ANDROID DebugLog($"FetchContext: {flowName}, duration: {duration?.ToString() ?? "the flow model's"}"); bool success = SafeAndroidCall(() => { AndroidJavaObject customSignalsObj = customSignals?.ToAndroidCustomSignals() ?? new AndroidJavaObject($"{ANDROID_PACKAGE_NAME}.signals.CustomSignals"); ContextCallback contextCallback = new ContextCallback(callback); if (duration.HasValue) { ContextSDKClass.CallStatic("fetchContext", flowName, duration.Value, customSignalsObj, contextCallback); } else { ContextSDKClass.CallStatic("fetchContext", flowName, customSignalsObj, contextCallback); } }, "Failed to fetch context"); if (!success) { callback(new Context(-1)); } #else // On non iOS always instantly callback. callback(new Context(-1)); #endif } [MonoPInvokeCallback(typeof(InternalContextDelegate))] private static void HandleContext(int contextID) { ContextDelegate callback = pendingContextDelegates[contextID]; callback.Invoke(new Context(contextID)); pendingContextDelegates.Remove(contextID); } /// /// Fetch the most recently generated Context for a given flowName /// public static Context? RecentContext(string flowName) { #if CONTEXTSDK_IOS int contextID = contextSDK_recentContext(flowName); if (contextID == -1) { return null; } return new Context(contextID); #elif CONTEXTSDK_ANDROID DebugLog($"RecentContext: {flowName}"); return SafeAndroidCall(() => { AndroidJavaObject contextObj = ContextSDKClass.CallStatic("recentContext", flowName); if (contextObj == null) { return null; } return new Context(-1, contextObj); }, "Failed to get recent context", null); #else return null; #endif } #endregion #region Tracking Methods /// /// Call this method to track a generic event. Using this allows us to provide you with insights on how your app behaves in the real-world context /// public static void TrackEvent(string eventName, CustomSignals? customSignals = null) { #if CONTEXTSDK_IOS int customSignalsID = customSignals?.contextID ?? -1; contextSDK_trackEvent(eventName, customSignalsID); #elif CONTEXTSDK_ANDROID DebugLog($"TrackEvent: {eventName}"); SafeAndroidCall(() => { AndroidJavaObject customSignalsObj = customSignals?.ToAndroidCustomSignals() ?? new AndroidJavaObject($"{ANDROID_PACKAGE_NAME}.signals.CustomSignals"); ContextSDKClass.CallStatic("trackEvent", eventName, customSignalsObj); }, "Failed to track event"); #endif } /// /// Call this method to track a generic page view. Using this allows us to provide you with insights on how your app behaves in the real-world context /// public static void TrackPageView(string pageName, CustomSignals? customSignals = null) { #if CONTEXTSDK_IOS int customSignalsID = customSignals?.contextID ?? -1; contextSDK_trackPageView(pageName, customSignalsID); #elif CONTEXTSDK_ANDROID DebugLog($"TrackPageView: {pageName}"); SafeAndroidCall(() => { AndroidJavaObject customSignalsObj = customSignals?.ToAndroidCustomSignals() ?? new AndroidJavaObject($"{ANDROID_PACKAGE_NAME}.signals.CustomSignals"); ContextSDKClass.CallStatic("trackPageView", pageName, customSignalsObj); }, "Failed to track page view"); #endif } /// /// Call this method to track a generic user action. Using this allows us to provide you with insights on how your app behaves in the real-world context /// public static void TrackUserAction(string userActionName, CustomSignals? customSignals = null) { #if CONTEXTSDK_IOS int customSignalsID = customSignals?.contextID ?? -1; contextSDK_trackUserAction(userActionName, customSignalsID); #elif CONTEXTSDK_ANDROID DebugLog($"TrackUserAction: {userActionName}"); SafeAndroidCall(() => { AndroidJavaObject customSignalsObj = customSignals?.ToAndroidCustomSignals() ?? new AndroidJavaObject($"{ANDROID_PACKAGE_NAME}.signals.CustomSignals"); ContextSDKClass.CallStatic("trackUserAction", userActionName, customSignalsObj); }, "Failed to track user action"); #endif } #endregion #region Helper Classes public class CustomSignals { internal int contextID; #if CONTEXTSDK_ANDROID private Dictionary signalValues = new Dictionary(); #endif public CustomSignals() { #if CONTEXTSDK_IOS this.contextID = contextSDK_getNextContextID(); #else this.contextID = -1; #endif } public void AppendCustomSignal(string id, int value) { #if CONTEXTSDK_IOS contextSDK_context_addCustomSignalInt(contextID, id, value); #elif CONTEXTSDK_ANDROID signalValues[id] = value; #endif } public void AppendCustomSignal(string id, float value) { #if CONTEXTSDK_IOS contextSDK_context_addCustomSignalFloat(contextID, id, value); #elif CONTEXTSDK_ANDROID signalValues[id] = value; #endif } public void AppendCustomSignal(string id, bool value) { #if CONTEXTSDK_IOS contextSDK_context_addCustomSignalBool(contextID, id, value); #elif CONTEXTSDK_ANDROID signalValues[id] = value; #endif } public void AppendCustomSignal(string id, string value) { #if CONTEXTSDK_IOS contextSDK_context_addCustomSignalString(contextID, id, value); #elif CONTEXTSDK_ANDROID signalValues[id] = value; #endif } #if CONTEXTSDK_ANDROID internal AndroidJavaObject ToAndroidCustomSignals() { AndroidJavaObject customSignalsObj = new AndroidJavaObject($"{ANDROID_PACKAGE_NAME}.signals.CustomSignals"); foreach (var kvp in signalValues) { if (kvp.Value is int intValue) { customSignalsObj.Call("set", kvp.Key, intValue); } else if (kvp.Value is float floatValue) { customSignalsObj.Call("set", kvp.Key, floatValue); } else if (kvp.Value is bool boolValue) { customSignalsObj.Call("set", kvp.Key, boolValue); } else if (kvp.Value is string stringValue) { customSignalsObj.Call("set", kvp.Key, stringValue); } } return customSignalsObj; } #endif ~CustomSignals() { #if CONTEXTSDK_IOS contextSDK_releaseCustomSignals(contextID); #endif } } public class RevenueEvent { public readonly float revenue; public readonly Currency currency; public readonly RevenueSource source; public RevenueEvent(RevenueSource source, float revenue, Currency currency) { this.source = source; this.revenue = revenue; this.currency = currency; } } public class Context { internal int contextID; internal AndroidJavaObject? androidContextObj; /// /// Check if you now is a good time to show an upsell prompt. During calibration phase, this will always be `true`. /// public readonly bool shouldUpsell = true; /// /// Every score output the flow's model produced, keyed by the output's name, or null when no model ran for this context: /// the flow has no model, this installation is in its control group, decisions are turned off, the model failed, or the /// AdTech SDK, which runs no flow models. A score is in whatever range its output defines. /// A value can be NaN or infinite when the model produced one: check double.IsFinite before acting on it. /// public readonly IReadOnlyDictionary? modelOutputs; /// /// The state of the motion window this context, and any model that ran on it, was built from. /// Null when the binding has no native context behind this one, or could not read it. /// public readonly SensorDataStatus? sensorDataStatus; #if CONTEXTSDK_ANDROID private AndroidJavaObject? OutcomeMetadata { get { if (androidContextObj != null) { return androidContextObj.Call("getOutcomeMetadata"); } return null; } } #endif internal Context(int contextID, AndroidJavaObject? androidContextObj = null) { this.contextID = contextID; this.androidContextObj = androidContextObj; #if CONTEXTSDK_IOS this.shouldUpsell = contextSDK_context_shouldUpsell(contextID); this.modelOutputs = ReadModelOutputs(contextID); this.sensorDataStatus = ReadSensorDataStatus(contextID); #elif CONTEXTSDK_ANDROID if (androidContextObj != null) { this.shouldUpsell = androidContextObj.Call("getShouldUpsell"); this.modelOutputs = SafeAndroidCall(() => ReadModelOutputs(androidContextObj), "Failed to read model outputs", null); this.sensorDataStatus = SafeAndroidCall( () => ReadSensorDataStatus(androidContextObj), "Failed to read sensor data status", null); } #endif } #if CONTEXTSDK_IOS // The bridge hands the outputs over one at a time, by an index into their keys in sorted order; // a count of -1 is a context without model outputs. private static IReadOnlyDictionary? ReadModelOutputs(int contextID) { int count = contextSDK_context_modelOutputsCount(contextID); if (count < 0) { return null; } var outputs = new Dictionary(count); for (int index = 0; index < count; index++) { string? key = contextSDK_context_modelOutputKey(contextID, index); if (key != null) { outputs[key] = contextSDK_context_modelOutputValue(contextID, index); } } return outputs; } // The bridge's numbers are this enum's values; -1 is a context the bridge does not hold. private static SensorDataStatus? ReadSensorDataStatus(int contextID) { return contextSDK_context_sensorDataStatus(contextID) switch { 0 => SensorDataStatus.Complete, 1 => SensorDataStatus.Incomplete, 2 => SensorDataStatus.Unavailable, _ => null, }; } #endif #if CONTEXTSDK_ANDROID // RealWorldContext.modelOutputs is a java.util.Map, or null when no model ran. private static IReadOnlyDictionary? ReadModelOutputs(AndroidJavaObject androidContextObj) { using AndroidJavaObject? javaOutputs = androidContextObj.Call("getModelOutputs"); if (javaOutputs == null) { return null; } var outputs = new Dictionary(); using AndroidJavaObject javaKeys = javaOutputs.Call("keySet"); using AndroidJavaObject javaKeyIterator = javaKeys.Call("iterator"); while (javaKeyIterator.Call("hasNext")) { using AndroidJavaObject javaKey = javaKeyIterator.Call("next"); using AndroidJavaObject javaValue = javaOutputs.Call("get", javaKey); outputs[javaKey.Call("toString")] = javaValue.Call("doubleValue"); } return outputs; } private static SensorDataStatus ReadSensorDataStatus(AndroidJavaObject androidContextObj) { using AndroidJavaObject javaSensorDataStatus = androidContextObj.Call("getSensorDataStatus"); return javaSensorDataStatus.Call("name") switch { "COMPLETE" => SensorDataStatus.Complete, "INCOMPLETE" => SensorDataStatus.Incomplete, "UNAVAILABLE" => SensorDataStatus.Unavailable, var unknown => UnknownSensorDataStatus(unknown), }; } // A constant this binding does not know yet: logged, so it does not pass silently as Unavailable. private static SensorDataStatus UnknownSensorDataStatus(string name) { Debug.LogWarning($"ContextSDK: unknown sensor data status {name}, read as Unavailable."); return SensorDataStatus.Unavailable; } #endif /// /// Use this method to log an outcome and send the context event to the backend /// public void Log(Outcome outcome) { #if CONTEXTSDK_IOS contextSDK_context_log(contextID, ((int)outcome)); #elif CONTEXTSDK_ANDROID DebugLog($"Log: {outcome}"); if (androidContextObj != null) { SafeAndroidCall(() => { AndroidJavaObject eventOutcome = GetAndroidEventOutcome(outcome); androidContextObj.Call("log", eventOutcome); }, "Failed to log outcome"); } #endif } /// /// Use this function to log an outcome only if this particular context object hasn't been logged yet /// public void LogIfNotLoggedYet(Outcome outcome) { #if CONTEXTSDK_IOS contextSDK_context_logIfNotLoggedYet(contextID, ((int)outcome)); #elif CONTEXTSDK_ANDROID DebugLog($"LogIfNotLoggedYet: {outcome}"); if (androidContextObj != null) { SafeAndroidCall(() => { AndroidJavaObject eventOutcome = GetAndroidEventOutcome(outcome); androidContextObj.Call("logIfNotLoggedYet", eventOutcome); }, "Failed to log if not logged yet"); } #endif } /// /// This method allows you to append custom outcomes to that specific outcome /// We recommend using this method to provide information like the selected price tier / plan, or other relevant info about the type of product or action the user has selected /// public void AppendOutcomeMetadata(string id, int value) { #if CONTEXTSDK_IOS contextSDK_context_appendOutcomeMetadataInt(contextID, id, value); #elif CONTEXTSDK_ANDROID DebugLog($"AppendOutcomeMetadata: {id} = {value}"); if (OutcomeMetadata != null) { SafeAndroidCall(() => { OutcomeMetadata.Call("set", id, value); }, "Failed to append outcome metadata"); } #endif } /// /// This method allows you to append custom outcomes to that specific outcome /// We recommend using this method to provide information like the selected price tier / plan, or other relevant info about the type of product or action the user has selected /// public void AppendOutcomeMetadata(string id, bool value) { #if CONTEXTSDK_IOS contextSDK_context_appendOutcomeMetadataBool(contextID, id, value); #elif CONTEXTSDK_ANDROID DebugLog($"AppendOutcomeMetadata: {id} = {value}"); if (OutcomeMetadata != null) { SafeAndroidCall(() => { OutcomeMetadata.Call("set", id, value); }, "Failed to append outcome metadata"); } #endif } /// /// This method allows you to append custom outcomes to that specific outcome /// We recommend using this method to provide information like the selected price tier / plan, or other relevant info about the type of product or action the user has selected /// public void AppendOutcomeMetadata(string id, float value) { #if CONTEXTSDK_IOS contextSDK_context_appendOutcomeMetadataFloat(contextID, id, value); #elif CONTEXTSDK_ANDROID DebugLog($"AppendOutcomeMetadata: {id} = {value}"); if (OutcomeMetadata != null) { SafeAndroidCall(() => { OutcomeMetadata.Call("set", id, value); }, "Failed to append outcome metadata"); } #endif } /// /// This method allows you to append custom outcomes to that specific outcome /// We recommend using this method to provide information like the selected price tier / plan, or other relevant info about the type of product or action the user has selected /// public void AppendOutcomeMetadata(string id, string value) { #if CONTEXTSDK_IOS contextSDK_context_appendOutcomeMetadataString(contextID, id, value); #elif CONTEXTSDK_ANDROID DebugLog($"AppendOutcomeMetadata: {id} = {value}"); if (OutcomeMetadata != null) { SafeAndroidCall(() => { OutcomeMetadata.Call("set", id, value); }, "Failed to append outcome metadata"); } #endif } /// /// Tracks a revenue event and logs the given outcome. /// /// The revenue event information. /// The outcome to log. Defaults to . public void LogRevenueOutcome(RevenueEvent revenueEvent, Outcome outcome = Outcome.Positive) { AppendOutcomeMetadata("ctx_revenue", revenueEvent.revenue); AppendOutcomeMetadata("ctx_currency", currencyCode(revenueEvent.currency)); AppendOutcomeMetadata("ctx_revenue_source", revenueSourceIdentifier(revenueEvent.source)); Log(outcome); } #if CONTEXTSDK_ANDROID private AndroidJavaObject GetAndroidEventOutcome(Outcome outcome) { string eventOutcomeName = outcome switch { Outcome.PositiveAdTapped => "POSITIVE_AD_TAPPED", Outcome.PositiveConverted => "POSITIVE_CONVERTED", Outcome.PositiveInteracted => "POSITIVE_INTERACTED", Outcome.Positive => "POSITIVE", Outcome.Skipped => "SKIPPED", Outcome.Negative => "NEGATIVE", Outcome.NegativeNotInteracted => "NEGATIVE_NOT_INTERACTED", Outcome.NegativeDismissed => "NEGATIVE_DISMISSED", _ => throw new ArgumentOutOfRangeException(nameof(outcome), outcome, "Unknown outcome value") }; AndroidJavaClass eventOutcomeClass = new AndroidJavaClass($"{ANDROID_PACKAGE_NAME}.enums.EventOutcome"); return eventOutcomeClass.GetStatic(eventOutcomeName); } #endif /// /// Call this method to do a local validation of your ContextSDK setup /// /// A string with diagnostic information. public string Validate() { #if CONTEXTSDK_IOS return contextSDK_context_validate(contextID); #elif CONTEXTSDK_ANDROID DebugLog("Validate called"); if (androidContextObj != null) { return SafeAndroidCall(() => { return androidContextObj.Call("validate"); }, "Failed to validate context", "Validation failed."); } return "No Context object available for validation."; #else return "Calling Validate from outside of iOS is not supported."; #endif } ~Context() { #if CONTEXTSDK_IOS contextSDK_releaseContext(contextID); #endif } } /// /// The state of the motion window a context was built from. /// public enum SensorDataStatus { // The values are the iOS bridge's contextSDK_context_sensorDataStatus numbers: keep them in step. /// /// A full window of valid motion samples, as long as the context asked for. /// Complete = 0, /// /// Fewer valid samples than the window asked for, usually because ContextSDK had not been collecting for long enough. /// A model still runs on it, with the missing samples padded. /// Incomplete = 1, /// /// This device has no usable motion sensors, so no window could be collected. /// Unavailable = 2, } /// /// Describes the outcome of a flow. /// public enum Outcome { /// /// Optional outcome: The user has tapped on the ad, and followed any external link provided. /// PositiveAdTapped = 4, /// /// Optional outcome: The user ended up successfully purchasing the product (all the way through the payment flow) /// PositiveConverted = 3, /// /// Optional outcome: The user has tapped on the banner, and started the purchase flow, or read more about the offer /// PositiveInteracted = 2, /// /// A generic, positive signal. Use this for the basic ContextSDK integration, e.g. when showing an upsell prompt. /// Positive = 1, /// /// Log this when ContextSDK has recommended to skip showing an upsell prompt (`.shouldUpsell` is false). /// Skipped = 0, /// /// A generic, negative signal. Use this for the basic ContextSDK integration, on a user e.g. declining or dismissing an upsell prompt /// Negative = -1, /// /// Optional outcome: Use this as a negative signal of a user not interacting with e.g. a banner. Depending on your app, we may recommend to log this when the app is put into the background, and hasn't interacted with a banner in any way. This can be done using the `LogIfNotLoggedYet` method /// NegativeNotInteracted = -2, /// /// Optional outcome: The user has actively dismissed the banner (e.g. using a close button) /// NegativeDismissed = -3 } public enum RevenueSource { AdImpression, AdClick, AdClickThrough, AdConversion, AdEngagement, PurchaseOutsideAppStore, SubscriptionOutsideAppStore, PurchaseAppStore, SubscriptionAppStore, Affiliate, Tip, Donation, } private static string revenueSourceIdentifier(RevenueSource source) { return source switch { RevenueSource.AdImpression => "ad_impression", RevenueSource.AdClick => "ad_click", RevenueSource.AdClickThrough => "ad_click_through", RevenueSource.AdConversion => "ad_conversion", RevenueSource.AdEngagement => "ad_engagement", RevenueSource.PurchaseOutsideAppStore => "purchase_outside_app_store", RevenueSource.SubscriptionOutsideAppStore => "subscription_outside_app_store", RevenueSource.PurchaseAppStore => "purchase_app_store", RevenueSource.SubscriptionAppStore => "subscription_app_store", RevenueSource.Affiliate => "affiliate", RevenueSource.Tip => "tip", RevenueSource.Donation => "donation", _ => "", }; } public enum Currency { aed, afn, all, amd, ang, aoa, ars, aud, awg, azn, bam, bbd, bdt, bgn, bhd, bif, bmd, bnd, bob, brl, bsd, btn, bwp, byn, bzd, cad, cdf, chf, clp, cny, cop, crc, cup, cve, czk, djf, dkk, dop, dzd, egp, ern, etb, eur, fjd, fkp, fok, gbp, gel, ggp, ghs, gip, gmd, gnf, gtq, gyd, hkd, hnl, hrk, htg, huf, idr, ils, imp, inr, iqd, irr, isk, jep, jmd, jod, jpy, kes, kgs, khr, kid, kmf, krw, kwd, kyd, kzt, lak, lbp, lkr, lrd, lsl, lyd, mad, mdl, mga, mkd, mmk, mnt, mop, mru, mur, mvr, mwk, mxn, myr, mzn, nad, ngn, nio, nok, npr, nzd, omr, pab, pen, pgk, php, pkr, pln, pyg, qar, ron, rsd, rub, rwf, sar, sbd, scr, sdg, sek, sgd, shp, sll, sos, srd, ssp, stn, syp, szl, thb, tjs, tmt, tnd, top, @try, ttd, tvd, twd, tzs, uah, ugx, usd, uyu, uzs, ves, vnd, vuv, wst, xaf, xcd, xof, xpf, yer, zar, zmw, zwl, } private static string currencyCode(Currency currency) { return currency.ToString().ToUpper(); } #endregion }