Merge pull request #8238 from vector-im/feature/bma/postHogOff

Create Posthog instance only when user consent is given
This commit is contained in:
Benoit Marty 2023-03-17 16:13:30 +01:00 committed by GitHub
commit f08f3c1b02
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 7 deletions

View File

@ -41,19 +41,23 @@ private val IGNORED_OPTIONS: Options? = null
@Singleton
class DefaultVectorAnalytics @Inject constructor(
postHogFactory: PostHogFactory,
private val postHogFactory: PostHogFactory,
private val sentryAnalytics: SentryAnalytics,
analyticsConfig: AnalyticsConfig,
private val analyticsConfig: AnalyticsConfig,
private val analyticsStore: AnalyticsStore,
private val lateInitUserPropertiesFactory: LateInitUserPropertiesFactory,
@NamedGlobalScope private val globalScope: CoroutineScope
) : VectorAnalytics {
private val posthog: PostHog? = when {
analyticsConfig.isEnabled -> postHogFactory.createPosthog()
else -> {
Timber.tag(analyticsTag.value).w("Analytics is disabled")
null
private var posthog: PostHog? = null
private fun createPosthog(): PostHog? {
return when {
analyticsConfig.isEnabled -> postHogFactory.createPosthog()
else -> {
Timber.tag(analyticsTag.value).w("Analytics is disabled")
null
}
}
}
@ -150,6 +154,7 @@ class DefaultVectorAnalytics @Inject constructor(
userConsent?.let { _userConsent ->
when (_userConsent) {
true -> {
posthog = createPosthog()
posthog?.optOut(false)
identifyPostHog()
pendingUserProperties?.let { doUpdateUserProperties(it) }
@ -159,6 +164,7 @@ class DefaultVectorAnalytics @Inject constructor(
// When opting out, ensure that the queue is flushed first, or it will be flushed later (after user has revoked consent)
posthog?.flush()
posthog?.optOut(true)
posthog = null
}
}
}

View File

@ -80,6 +80,12 @@ class DefaultVectorAnalyticsTest {
@Test
fun `when revoking consent to analytics then updates posthog opt out to true and closes Sentry`() = runTest {
// For opt-out to have effect on Posthog, it has to be used first, so it has to be opt-in first
fakeAnalyticsStore.givenUserContent(consent = true)
fakePostHog.verifyOptOutStatus(optedOut = false)
fakeSentryAnalytics.verifySentryInit()
// Then test opt-out
fakeAnalyticsStore.givenUserContent(consent = false)
fakePostHog.verifyOptOutStatus(optedOut = true)