From 55c7270ef2af923a4c4b672c3863f1f245ee81d3 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Wed, 24 Nov 2021 17:05:19 +0100 Subject: [PATCH] Analytics: Create PostHog client only when user has given their consent --- .../analytics/impl/DefaultVectorAnalytics.kt | 57 ++++++++++--------- 1 file changed, 31 insertions(+), 26 deletions(-) diff --git a/vector/src/main/java/im/vector/app/features/analytics/impl/DefaultVectorAnalytics.kt b/vector/src/main/java/im/vector/app/features/analytics/impl/DefaultVectorAnalytics.kt index 069e2ba8d5..a4f2ce2ca3 100644 --- a/vector/src/main/java/im/vector/app/features/analytics/impl/DefaultVectorAnalytics.kt +++ b/vector/src/main/java/im/vector/app/features/analytics/impl/DefaultVectorAnalytics.kt @@ -70,6 +70,37 @@ class DefaultVectorAnalytics @Inject constructor( } override fun init() { + observeUserConsent() + observeAnalyticsId() + } + + @Suppress("EXPERIMENTAL_API_USAGE") + private fun observeAnalyticsId() { + getAnalyticsId() + .onEach { id -> + if (id.isEmpty()) { + posthog?.reset() + } else { + posthog?.identify(id) + } + } + .launchIn(GlobalScope) + } + + @Suppress("EXPERIMENTAL_API_USAGE") + private fun observeUserConsent() { + getUserConsent() + .onEach { consent -> + userConsent = consent + if (consent) { + createAnalyticsClient() + } + posthog?.optOut(!consent) + } + .launchIn(GlobalScope) + } + + private fun createAnalyticsClient() { val config: AnalyticsConfig = AnalyticsConfig.getConfig() ?: return Unit.also { Timber.w("Analytics is disabled") } @@ -93,9 +124,6 @@ class DefaultVectorAnalytics @Inject constructor( .collectDeviceId(false) .logLevel(getLogLevel()) .build() - - observeUserConsent() - observeAnalyticsId() } private fun getLogLevel(): PostHog.LogLevel { @@ -106,29 +134,6 @@ class DefaultVectorAnalytics @Inject constructor( } } - @Suppress("EXPERIMENTAL_API_USAGE") - private fun observeAnalyticsId() { - getAnalyticsId() - .onEach { id -> - if (id.isEmpty()) { - posthog?.reset() - } else { - posthog?.identify(id) - } - } - .launchIn(GlobalScope) - } - - @Suppress("EXPERIMENTAL_API_USAGE") - private fun observeUserConsent() { - getUserConsent() - .onEach { consent -> - userConsent = consent - posthog?.optOut(!consent) - } - .launchIn(GlobalScope) - } - override fun capture(event: String, properties: Map?) { posthog ?.takeIf { userConsent }