Bläddra i källkod

Version 6.6.1-1240

Threema 1 vecka sedan
förälder
incheckning
895c101e6d
63 ändrade filer med 773 tillägg och 392 borttagningar
  1. 2 6
      app/build.gradle.kts
  2. 9 7
      app/src/androidTest/java/ch/threema/app/TestTaskManager.kt
  3. 9 7
      app/src/androidTest/java/ch/threema/app/contacts/MarkContactAsDeletedBackgroundTaskTest.kt
  4. 9 7
      app/src/androidTest/java/ch/threema/app/processors/MessageProcessorProvider.kt
  5. 1 1
      app/src/libre/play/release-notes/de/default.txt
  6. 1 1
      app/src/libre/play/release-notes/en-US/default.txt
  7. 2 0
      app/src/main/java/ch/threema/app/activities/wizard/WizardIntroActivity.java
  8. 15 0
      app/src/main/java/ch/threema/app/activities/wizard/WizardIntroHelper.kt
  9. 2 0
      app/src/main/java/ch/threema/app/di/SessionScopeContainer.kt
  10. 1 0
      app/src/main/java/ch/threema/app/errorreporting/ErrorRecord.kt
  11. 2 0
      app/src/main/java/ch/threema/app/errorreporting/ErrorRecordStore.kt
  12. 4 0
      app/src/main/java/ch/threema/app/errorreporting/ErrorRecordStoreImpl.kt
  13. 5 1
      app/src/main/java/ch/threema/app/errorreporting/SendErrorReportWorker.kt
  14. 4 3
      app/src/main/java/ch/threema/app/home/HomeActivity.kt
  15. 1 0
      app/src/main/java/ch/threema/app/notifications/CallNotificationManager.kt
  16. 52 10
      app/src/main/java/ch/threema/app/notifications/CallNotificationManagerImpl.kt
  17. 1 9
      app/src/main/java/ch/threema/app/notifications/ConversationNotificationUpdaterMonitor.kt
  18. 0 4
      app/src/main/java/ch/threema/app/preference/SettingsNotificationsFragment.kt
  19. 2 0
      app/src/main/java/ch/threema/app/preference/service/PreferenceService.kt
  20. 3 0
      app/src/main/java/ch/threema/app/preference/service/PreferenceServiceImpl.kt
  21. 0 4
      app/src/main/java/ch/threema/app/processors/incomingcspmessage/conversation/IncomingContactReactionMessageTask.kt
  22. 0 4
      app/src/main/java/ch/threema/app/processors/incomingcspmessage/conversation/IncomingGroupReactionMessageTask.kt
  23. 0 200
      app/src/main/java/ch/threema/app/services/PollingHelper.java
  24. 217 0
      app/src/main/java/ch/threema/app/services/PollingHelper.kt
  25. 4 2
      app/src/main/java/ch/threema/app/services/notification/BaseNotificationService.kt
  26. 1 1
      app/src/main/java/ch/threema/app/services/notification/ConversationReactionNotification.kt
  27. 16 11
      app/src/main/java/ch/threema/app/services/notification/NotificationServiceImpl.kt
  28. 3 1
      app/src/main/java/ch/threema/app/services/notification/PassphraseNotificationService.kt
  29. 4 0
      app/src/main/java/ch/threema/app/usecases/CheckLicenseUseCase.kt
  30. 1 0
      app/src/main/java/ch/threema/app/usecases/GetDebugMetaDataUseCase.kt
  31. 0 1
      app/src/main/java/ch/threema/app/utils/ContactUtil.java
  32. 62 0
      app/src/main/java/ch/threema/app/voicemessage/SamsungQuirkAudioSink.kt
  33. 3 1
      app/src/main/java/ch/threema/app/voip/services/VoipStateService.java
  34. 1 1
      app/src/main/java/ch/threema/storage/factories/DistributionListMessageModelFactory.java
  35. 50 0
      app/src/main/res/values-sk/strings.xml
  36. 6 0
      app/src/main/res/values-tr/strings.xml
  37. 5 3
      app/src/service_type_specific/google_services_based/java/ch/threema/app/services/VoiceActionService.java
  38. 12 0
      app/src/test/java/ch/threema/app/errorreporting/ErrorRecordStoreImplTest.kt
  39. 2 0
      app/src/test/java/ch/threema/app/errorreporting/ErrorReportDetailsProviderTest.kt
  40. 3 0
      app/src/test/java/ch/threema/app/errorreporting/SentryServiceTest.kt
  41. 4 6
      app/src/test/java/ch/threema/app/notifications/CallNotificationManagerTest.kt
  42. 4 0
      app/src/test/java/ch/threema/app/usecases/GetDebugMetaDataUseCaseTest.kt
  43. 9 7
      app/src/test/java/ch/threema/data/ContactModelTest.kt
  44. 9 7
      app/src/test/java/ch/threema/data/GroupModelTest.kt
  45. 1 1
      app/src/test/resources/error-reporting/fatal-error-record-v2.json
  46. 1 1
      app/src/test/resources/error-reporting/non-fatal-error-record-v2.json
  47. 1 1
      app/src/test/resources/error-reporting/non-fatal-error-record-with-attachment-v2.json
  48. 10 10
      domain/src/main/java/ch/threema/domain/protocol/connection/BaseServerConnection.kt
  49. 4 1
      domain/src/main/java/ch/threema/domain/protocol/connection/layer/EndToEndLayer.kt
  50. 10 3
      domain/src/main/java/ch/threema/domain/protocol/connection/layer/MonitoringLayer.kt
  51. 4 2
      domain/src/main/java/ch/threema/domain/taskmanager/IncomingCspMessageTask.kt
  52. 16 0
      domain/src/main/java/ch/threema/domain/taskmanager/IncomingD2mMessageTask.kt
  53. 7 1
      domain/src/main/java/ch/threema/domain/taskmanager/IncomingMessageTaskQueue.kt
  54. 18 0
      domain/src/main/java/ch/threema/domain/taskmanager/LeaderState.kt
  55. 0 12
      domain/src/main/java/ch/threema/domain/taskmanager/QueueSendCompleteListener.java
  56. 16 0
      domain/src/main/java/ch/threema/domain/taskmanager/QueueSendCompleteState.kt
  57. 18 0
      domain/src/main/java/ch/threema/domain/taskmanager/ReflectionQueueDryState.kt
  58. 69 35
      domain/src/main/java/ch/threema/domain/taskmanager/TaskManager.kt
  59. 10 1
      domain/src/main/java/ch/threema/domain/taskmanager/TaskQueue.kt
  60. 26 2
      domain/src/main/java/ch/threema/domain/taskmanager/TaskRunner.kt
  61. 9 7
      domain/src/test/java/ch/threema/domain/protocol/connection/CspConnectionTest.kt
  62. 9 7
      domain/src/testFixtures/java/ch/threema/domain/helpers/ControlledTaskManager.kt
  63. 3 3
      gradle/libs.versions.toml

+ 2 - 6
app/build.gradle.kts

@@ -35,7 +35,7 @@ if (gradle.startParameter.taskRequests.toString().contains("Hms")) {
 /**
  * Only use the scheme "<major>.<minor>.<patch>" for the appVersion
  */
-val appVersion = "6.6.0"
+val appVersion = "6.6.1"
 
 /**
  * betaSuffix with leading dash (e.g. `-beta1`).
@@ -44,7 +44,7 @@ val appVersion = "6.6.0"
  */
 val betaSuffix = ""
 
-val defaultVersionCode = 1237
+val defaultVersionCode = 1240
 
 /**
  * Map with keystore paths (if found).
@@ -141,7 +141,6 @@ android {
         booleanBuildConfigField("CROSS_PLATFORM_BACKUPS_ENABLED", BuildFeatureFlags["cross_platform_backups"] ?: false)
         booleanBuildConfigField("NEW_CONVERSATION_SCREEN_ENABLED", BuildFeatureFlags["new_conversation_screen"] ?: false)
         booleanBuildConfigField("LOG_TOMBSTONES_FOR_NATIVE_CRASHES", BuildFeatureFlags["log_tombstones"] ?: false)
-        booleanBuildConfigField("EMOJI_REACTION_NOTIFICATIONS_ENABLED", false)
 
         // config fields for action URLs / deep links
         stringBuildConfigField("uriScheme", "threema")
@@ -296,7 +295,6 @@ android {
             stringBuildConfigField("BLOB_MIRROR_SERVER_URL", "https://blob-mirror-{deviceGroupIdPrefix4}.test.threema.ch/{deviceGroupIdPrefix8}")
 
             booleanBuildConfigField("CROSS_PLATFORM_BACKUPS_ENABLED", true)
-            booleanBuildConfigField("EMOJI_REACTION_NOTIFICATIONS_ENABLED", true)
 
             setSentryConfig(SentryConfig.SANDBOX)
         }
@@ -341,7 +339,6 @@ android {
             stringBuildConfigField("actionUrl", "work.test.threema.ch")
 
             booleanBuildConfigField("AVAILABILITY_STATUS_ENABLED", true)
-            booleanBuildConfigField("EMOJI_REACTION_NOTIFICATIONS_ENABLED", true)
 
             stringBuildConfigField("MD_CLIENT_DOWNLOAD_URL", "https://three.ma/mdw")
 
@@ -443,7 +440,6 @@ android {
             stringBuildConfigField("BLOB_MIRROR_SERVER_URL", "https://blob-mirror-{deviceGroupIdPrefix4}.test.threema.ch/{deviceGroupIdPrefix8}")
 
             booleanBuildConfigField("AVAILABILITY_STATUS_ENABLED", true)
-            booleanBuildConfigField("EMOJI_REACTION_NOTIFICATIONS_ENABLED", true)
             booleanBuildConfigField("LOG_TOMBSTONES_FOR_NATIVE_CRASHES", true)
 
             // config fields for action URLs / deep links

+ 9 - 7
app/src/androidTest/java/ch/threema/app/TestTaskManager.kt

@@ -1,6 +1,9 @@
 package ch.threema.app
 
-import ch.threema.domain.taskmanager.QueueSendCompleteListener
+import ch.threema.common.stateFlowOf
+import ch.threema.domain.taskmanager.LeaderState
+import ch.threema.domain.taskmanager.QueueSendCompleteState
+import ch.threema.domain.taskmanager.ReflectionQueueDryState
 import ch.threema.domain.taskmanager.Task
 import ch.threema.domain.taskmanager.TaskCodec
 import ch.threema.domain.taskmanager.TaskManager
@@ -9,6 +12,7 @@ import kotlinx.coroutines.CoroutineScope
 import kotlinx.coroutines.Deferred
 import kotlinx.coroutines.Dispatchers
 import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.flow.StateFlow
 import kotlinx.coroutines.launch
 import kotlinx.coroutines.runBlocking
 
@@ -46,11 +50,9 @@ class TestTaskManager(
 
     override fun hasPendingTasks() = false
 
-    override fun addQueueSendCompleteListener(listener: QueueSendCompleteListener) {
-        // Nothing to do
-    }
+    override fun watchQueueSendComplete(): StateFlow<QueueSendCompleteState> = stateFlowOf(QueueSendCompleteState.PENDING)
 
-    override fun removeQueueSendCompleteListener(listener: QueueSendCompleteListener) {
-        // Nothing to do
-    }
+    override fun watchReflectionQueueDry(): StateFlow<ReflectionQueueDryState> = stateFlowOf(ReflectionQueueDryState.PENDING)
+
+    override fun watchLeaderState(): StateFlow<LeaderState> = stateFlowOf(LeaderState.NOT_LEADER)
 }

+ 9 - 7
app/src/androidTest/java/ch/threema/app/contacts/MarkContactAsDeletedBackgroundTaskTest.kt

@@ -19,6 +19,7 @@ import ch.threema.app.tasks.TaskCreator
 import ch.threema.app.utils.executor.BackgroundExecutor
 import ch.threema.base.crypto.NonceFactory
 import ch.threema.common.DispatcherProvider
+import ch.threema.common.stateFlowOf
 import ch.threema.data.datatypes.AvailabilityStatus
 import ch.threema.data.datatypes.ConversationCategory
 import ch.threema.data.datatypes.ConversationVisibility
@@ -39,7 +40,9 @@ import ch.threema.domain.protocol.connection.data.DeviceId
 import ch.threema.domain.protocol.connection.data.InboundD2mMessage.DevicesInfo
 import ch.threema.domain.protocol.csp.fs.ForwardSecurityMessageProcessor
 import ch.threema.domain.taskmanager.ActiveTaskCodec
-import ch.threema.domain.taskmanager.QueueSendCompleteListener
+import ch.threema.domain.taskmanager.LeaderState
+import ch.threema.domain.taskmanager.QueueSendCompleteState
+import ch.threema.domain.taskmanager.ReflectionQueueDryState
 import ch.threema.domain.taskmanager.Task
 import ch.threema.domain.taskmanager.TaskCodec
 import ch.threema.domain.taskmanager.TaskManager
@@ -61,6 +64,7 @@ import kotlin.test.assertTrue
 import kotlinx.coroutines.CompletableDeferred
 import kotlinx.coroutines.Deferred
 import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.StateFlow
 import kotlinx.coroutines.test.runTest
 
 @DangerousTest
@@ -79,13 +83,11 @@ class MarkContactAsDeletedBackgroundTaskTest {
             return taskQueue.isNotEmpty()
         }
 
-        override fun addQueueSendCompleteListener(listener: QueueSendCompleteListener) {
-            // Nothing to do
-        }
+        override fun watchQueueSendComplete(): StateFlow<QueueSendCompleteState> = stateFlowOf(QueueSendCompleteState.PENDING)
 
-        override fun removeQueueSendCompleteListener(listener: QueueSendCompleteListener) {
-            // Nothing to do
-        }
+        override fun watchReflectionQueueDry(): StateFlow<ReflectionQueueDryState> = stateFlowOf(ReflectionQueueDryState.PENDING)
+
+        override fun watchLeaderState(): StateFlow<LeaderState> = stateFlowOf(LeaderState.NOT_LEADER)
     }
     private lateinit var databaseProvider: TestDatabaseProvider
     private val multiDeviceManager = object : MultiDeviceManager {

+ 9 - 7
app/src/androidTest/java/ch/threema/app/processors/MessageProcessorProvider.kt

@@ -23,6 +23,7 @@ import ch.threema.app.testutils.clearDatabaseAndCaches
 import ch.threema.app.utils.ForwardSecurityStatusSender
 import ch.threema.base.crypto.NonceFactory
 import ch.threema.base.crypto.NonceScope
+import ch.threema.common.stateFlowOf
 import ch.threema.data.datatypes.GroupIdentity
 import ch.threema.data.models.ContactModelDataFactory
 import ch.threema.data.models.GroupModelDataFactory
@@ -55,7 +56,9 @@ import ch.threema.domain.protocol.csp.messages.fs.ForwardSecurityEnvelopeMessage
 import ch.threema.domain.stores.ContactStore
 import ch.threema.domain.stores.IdentityStore
 import ch.threema.domain.taskmanager.ActiveTask
-import ch.threema.domain.taskmanager.QueueSendCompleteListener
+import ch.threema.domain.taskmanager.LeaderState
+import ch.threema.domain.taskmanager.QueueSendCompleteState
+import ch.threema.domain.taskmanager.ReflectionQueueDryState
 import ch.threema.domain.taskmanager.Task
 import ch.threema.domain.taskmanager.TaskCodec
 import ch.threema.domain.taskmanager.TaskManager
@@ -73,6 +76,7 @@ import kotlin.test.AfterTest
 import kotlin.test.BeforeTest
 import kotlinx.coroutines.CompletableDeferred
 import kotlinx.coroutines.Deferred
+import kotlinx.coroutines.flow.StateFlow
 import kotlinx.coroutines.runBlocking
 import okhttp3.OkHttpClient
 import org.junit.Rule
@@ -356,13 +360,11 @@ open class MessageProcessorProvider : KoinComponent {
 
             override fun hasPendingTasks(): Boolean = false
 
-            override fun addQueueSendCompleteListener(listener: QueueSendCompleteListener) {
-                // Nothing to do
-            }
+            override fun watchQueueSendComplete(): StateFlow<QueueSendCompleteState> = stateFlowOf(QueueSendCompleteState.PENDING)
 
-            override fun removeQueueSendCompleteListener(listener: QueueSendCompleteListener) {
-                // Nothing to do
-            }
+            override fun watchReflectionQueueDry(): StateFlow<ReflectionQueueDryState> = stateFlowOf(ReflectionQueueDryState.PENDING)
+
+            override fun watchLeaderState(): StateFlow<LeaderState> = stateFlowOf(LeaderState.NOT_LEADER)
         }
         setTaskManager(mockTaskManager)
 

+ 1 - 1
app/src/libre/play/release-notes/de/default.txt

@@ -1,2 +1,2 @@
-- Neu: Spam-Gruppenchats melden und Admin blockieren
+- Neu: Sie erhalten eine Benachrichtigung, wenn jemand auf Ihre Nachricht reagiert
 - Verbesserungen und Behebung verschiedener Fehler

+ 1 - 1
app/src/libre/play/release-notes/en-US/default.txt

@@ -1,2 +1,2 @@
-- New: Report spam group chats and block the creator
+- New: Receive a notification when someone reacts to your message
 - Various improvements and bug fixes

+ 2 - 0
app/src/main/java/ch/threema/app/activities/wizard/WizardIntroActivity.java

@@ -165,6 +165,8 @@ public class WizardIntroActivity extends ThreemaAppCompatActivity {
         findViewById(R.id.restore_backup_compose).setOnClickListener(v -> restoreBackup());
 
         isContactSyncSettingConflict();
+
+        WizardIntroHelper.checkLicense(this);
     }
 
     @Override

+ 15 - 0
app/src/main/java/ch/threema/app/activities/wizard/WizardIntroHelper.kt

@@ -0,0 +1,15 @@
+package ch.threema.app.activities.wizard
+
+import androidx.lifecycle.lifecycleScope
+import ch.threema.app.usecases.CheckLicenseUseCase
+import kotlinx.coroutines.launch
+import org.koin.mp.KoinPlatform
+
+object WizardIntroHelper {
+    @JvmStatic
+    fun checkLicense(activity: WizardIntroActivity) {
+        activity.lifecycleScope.launch {
+            KoinPlatform.getKoin().get<CheckLicenseUseCase>().call(activity)
+        }
+    }
+}

+ 2 - 0
app/src/main/java/ch/threema/app/di/SessionScopeContainer.kt

@@ -3,6 +3,7 @@ package ch.threema.app.di
 import android.content.Context
 import android.os.PowerManager
 import androidx.annotation.VisibleForTesting
+import androidx.core.app.NotificationManagerCompat
 import androidx.core.content.getSystemService
 import ch.threema.app.BuildFlavor
 import ch.threema.app.GlobalAppState
@@ -460,6 +461,7 @@ class SessionScopeContainer(
     val notificationService: NotificationService by lazyWithClosedCheck {
         NotificationServiceImpl(
             appContext = appContext,
+            notificationManagerCompat = get<NotificationManagerCompat>(),
             getConversationCategoryUseCase = get<GetConversationCategoryUseCase>(),
             lockAppService = get<LockAppService>(),
             notificationPreferenceService = get<NotificationPreferenceService>(),

+ 1 - 0
app/src/main/java/ch/threema/app/errorreporting/ErrorRecord.kt

@@ -18,4 +18,5 @@ data class ErrorRecord(
     val attachments: List<ErrorRecordAttachment>? = null,
     @Serializable(with = InstantSerializer::class)
     val createdAt: Instant,
+    val versionCode: Int,
 )

+ 2 - 0
app/src/main/java/ch/threema/app/errorreporting/ErrorRecordStore.kt

@@ -26,4 +26,6 @@ interface ErrorRecordStore : BaseErrorRecordStore {
 
     @WorkerThread
     fun deleteConfirmedRecord(id: UUID)
+
+    val currentAppVersionCode: Int
 }

+ 4 - 0
app/src/main/java/ch/threema/app/errorreporting/ErrorRecordStoreImpl.kt

@@ -4,6 +4,7 @@ import android.content.Context
 import android.webkit.MimeTypeMap
 import androidx.annotation.VisibleForTesting
 import androidx.annotation.WorkerThread
+import ch.threema.app.BuildConfig
 import ch.threema.base.utils.getThreemaLogger
 import ch.threema.common.TimeProvider
 import ch.threema.common.UUIDGenerator
@@ -24,6 +25,7 @@ constructor(
     private val recordsDirectory: File,
     private val timeProvider: TimeProvider,
     private val uuidGenerator: UUIDGenerator,
+    override val currentAppVersionCode: Int,
 ) : ErrorRecordStore {
     @WorkerThread
     override fun storeFatalError(e: Throwable) {
@@ -83,6 +85,7 @@ constructor(
                 )
             },
             createdAt = timeProvider.get(),
+            versionCode = currentAppVersionCode,
         )
 
         recordsDirectory.mkdir()
@@ -185,6 +188,7 @@ constructor(
             recordsDirectory = getRecordsDirectory(context),
             timeProvider = timeProvider,
             uuidGenerator = uuidGenerator,
+            currentAppVersionCode = BuildConfig.DEFAULT_VERSION_CODE,
         )
 
         private fun getRecordsDirectory(context: Context): File =

+ 5 - 1
app/src/main/java/ch/threema/app/errorreporting/SendErrorReportWorker.kt

@@ -33,7 +33,7 @@ class SendErrorReportWorker(
 
     override suspend fun doWork(): Result {
         errorRecordStore.getConfirmedRecords().forEach { errorRecord ->
-            if (timeProvider.get() - errorRecord.createdAt < MAX_AGE) {
+            if (isStillRelevant(errorRecord)) {
                 try {
                     logger.info("Sending error record {} to Sentry", errorRecord.id)
                     sentryService.sendErrorRecord(errorRecord)
@@ -47,6 +47,10 @@ class SendErrorReportWorker(
         return Result.success()
     }
 
+    private fun isStillRelevant(errorRecord: ErrorRecord): Boolean =
+        timeProvider.get() - errorRecord.createdAt < MAX_AGE &&
+            errorRecord.versionCode == errorRecordStore.currentAppVersionCode
+
     class Scheduler(
         private val workManager: WorkManager,
     ) {

+ 4 - 3
app/src/main/java/ch/threema/app/home/HomeActivity.kt

@@ -673,9 +673,6 @@ class HomeActivity : ThreemaAppCompatActivity(), SMSVerificationDialogCallback,
     private fun initHomeActivity(savedInstanceState: Bundle?) {
         val isAppStart = savedInstanceState == null
 
-        // licensing
-        checkApp()
-
         // start wizard if necessary
         val wizardIsRunning = notificationPreferenceService.getWizardRunning()
         if (wizardIsRunning || !userService.hasIdentity()) {
@@ -716,6 +713,10 @@ class HomeActivity : ThreemaAppCompatActivity(), SMSVerificationDialogCallback,
             }
         }
 
+        // It is important that the license check only happens *after* we are certain that no activities will be started,
+        // because that could interfere with the HMS license check and leave it in an invalid state
+        checkApp()
+
         initActionBar()
         initAppLogo()
         actionBar?.setDisplayShowTitleEnabled(false)

+ 1 - 0
app/src/main/java/ch/threema/app/notifications/CallNotificationManager.kt

@@ -13,6 +13,7 @@ interface CallNotificationManager {
 
     sealed interface IncomingCallNotificationResult {
         object Success : IncomingCallNotificationResult
+        object Failed : IncomingCallNotificationResult
         object IncomingCallNotificationsDisabled : IncomingCallNotificationResult
     }
 }

+ 52 - 10
app/src/main/java/ch/threema/app/notifications/CallNotificationManagerImpl.kt

@@ -1,5 +1,6 @@
 package ch.threema.app.notifications
 
+import android.annotation.SuppressLint
 import android.app.Notification
 import android.app.PendingIntent
 import android.content.Context
@@ -15,6 +16,7 @@ import ch.threema.app.R
 import ch.threema.app.preference.service.PreferenceService
 import ch.threema.app.services.ContactService
 import ch.threema.app.services.NotificationPreferenceService
+import ch.threema.app.services.notification.BaseNotificationService
 import ch.threema.app.usecases.contacts.GetPersonUseCase
 import ch.threema.base.utils.getThreemaLogger
 import ch.threema.data.datatypes.ContactConversationId
@@ -24,14 +26,15 @@ import ch.threema.domain.types.IdentityString
 private val logger = getThreemaLogger("CallNotificationManagerImpl")
 
 class CallNotificationManagerImpl(
-    private val appContext: Context,
+    appContext: Context,
+    notificationManagerCompat: NotificationManagerCompat,
     private val notificationPreferenceService: NotificationPreferenceService,
     private val preferenceService: PreferenceService,
     private val contactService: ContactService,
     private val getPersonUseCase: GetPersonUseCase,
-    private val notificationManager: NotificationManagerCompat,
-) : CallNotificationManager {
+) : CallNotificationManager, BaseNotificationService(appContext, notificationManagerCompat) {
 
+    @SuppressLint("MissingPermission")
     override fun showIncomingCallNotification(
         contactModelData: ContactModelData,
         acceptIntent: PendingIntent,
@@ -64,7 +67,45 @@ class CallNotificationManagerImpl(
         )
 
         // Show the notification
-        notificationManager.notify(contactModelData.identity, NotificationIDs.INCOMING_CALL_NOTIFICATION_ID, notification)
+        try {
+            try {
+                notificationManagerCompat.notify(
+                    contactModelData.identity,
+                    NotificationIDs.INCOMING_CALL_NOTIFICATION_ID,
+                    notification,
+                )
+            } catch (e: SecurityException) {
+                if (contactModelData.androidContactLookupInfo == null) {
+                    throw e
+                }
+                logger.warn("Failed to display notification, trying again without contact lookup info", e)
+
+                // It might be that the SecurityException was caused by the Android contact lookup info,
+                // so we try again without it.
+                val notificationWithoutAndroidContactLookupInfo = getPrivateNotification(
+                    callerIdentity = contactModelData.identity,
+                    contactName = contactName,
+                    acceptIntent = acceptIntent,
+                    inCallPendingIntent = inCallPendingIntent,
+                    rejectIntent = rejectIntent,
+                    person = getPersonUseCase.call(
+                        identity = contactModelData.identity,
+                        androidContactLookupInfo = null,
+                        name = contactName,
+                    ),
+                    publicNotification = getPublicNotification(),
+                )
+
+                notificationManagerCompat.notify(
+                    contactModelData.identity,
+                    NotificationIDs.INCOMING_CALL_NOTIFICATION_ID,
+                    notificationWithoutAndroidContactLookupInfo,
+                )
+            }
+        } catch (e: Exception) {
+            logger.error("Failed to display notification", e)
+            return CallNotificationManager.IncomingCallNotificationResult.Failed
+        }
 
         return CallNotificationManager.IncomingCallNotificationResult.Success
     }
@@ -141,7 +182,7 @@ class CallNotificationManagerImpl(
     }
 
     private fun areIncomingCallNotificationsEnabled(): Boolean {
-        if (!notificationManager.areNotificationsEnabled()) {
+        if (!hasNotificationPermission()) {
             logger.warn("Notifications are disabled.")
             return false
         }
@@ -150,14 +191,15 @@ class CallNotificationManagerImpl(
             return true
         }
 
-        val notificationChannel = notificationManager.getNotificationChannel(NotificationChannels.NOTIFICATION_CHANNEL_INCOMING_CALLS) ?: run {
-            logger.warn("Notification channel for incoming calls is missing.")
-            return false
-        }
+        val notificationChannel = notificationManagerCompat.getNotificationChannel(NotificationChannels.NOTIFICATION_CHANNEL_INCOMING_CALLS)
+            ?: run {
+                logger.warn("Notification channel for incoming calls is missing.")
+                return false
+            }
 
         if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
             val notificationChannelGroup = notificationChannel.group?.let { groupId ->
-                notificationManager.getNotificationChannelGroup(groupId)
+                notificationManagerCompat.getNotificationChannelGroup(groupId)
             }
             if (notificationChannelGroup?.isBlocked == true) {
                 logger.warn("Notification channel group is blocked.")

+ 1 - 9
app/src/main/java/ch/threema/app/notifications/ConversationNotificationUpdaterMonitor.kt

@@ -1,6 +1,5 @@
 package ch.threema.app.notifications
 
-import ch.threema.app.BuildConfig
 import ch.threema.app.di.injectNullableNonBinding
 import ch.threema.app.eventbus.GlobalEventFlows
 import ch.threema.app.eventbus.events.ConversationEvent
@@ -111,7 +110,6 @@ class ConversationNotificationUpdaterMonitor(
         }
     }
 
-    @Suppress("SimplifyBooleanWithConstants")
     private fun onModifiedMessages(messages: List<MessageModel>) {
         val shouldShowEmojiReactionNotificationsInContactConversations = preferenceService
             .shouldShowEmojiReactionNotificationsInContactConversations()
@@ -121,7 +119,7 @@ class ConversationNotificationUpdaterMonitor(
             if (message.isImageOrVideoMessage()) {
                 showConversationNotification(message, updateExisting = true)
             }
-            if (BuildConfig.EMOJI_REACTION_NOTIFICATIONS_ENABLED && message.isOutbox && !message.isStatusMessage) {
+            if (message.isOutbox && !message.isStatusMessage) {
                 when (message) {
                     is ContactMessageModel -> {
                         if (shouldShowEmojiReactionNotificationsInContactConversations) {
@@ -166,9 +164,6 @@ class ConversationNotificationUpdaterMonitor(
     }
 
     private fun shouldShowEmojiReactionNotification(message: MessageModel): Boolean {
-        if (!BuildConfig.EMOJI_REACTION_NOTIFICATIONS_ENABLED) {
-            return false
-        }
         if (!message.isOutbox || message.isStatusMessage) {
             return false
         }
@@ -180,9 +175,6 @@ class ConversationNotificationUpdaterMonitor(
     }
 
     private fun cancelEmojiReactionNotification(message: MessageModel) {
-        if (!BuildConfig.EMOJI_REACTION_NOTIFICATIONS_ENABLED) {
-            return
-        }
         if (!message.isOutbox || message.isStatusMessage) {
             return
         }

+ 0 - 4
app/src/main/java/ch/threema/app/preference/SettingsNotificationsFragment.kt

@@ -17,7 +17,6 @@ import androidx.preference.Preference
 import androidx.preference.PreferenceCategory
 import androidx.preference.TwoStatePreference
 import ch.threema.android.DeviceInfo
-import ch.threema.app.BuildConfig
 import ch.threema.app.BuildFlavor
 import ch.threema.app.R
 import ch.threema.app.dialogs.RingtoneSelectorDialog
@@ -82,9 +81,6 @@ class SettingsNotificationsFragment : ThreemaPreferenceFragment(), RingtoneSelec
         initWorkingTimePrefs()
         setVisibilityOfVersionDependentPreferences()
 
-        getPref<PreferenceCategory>(R.string.preferences__emoji_reaction_notifications).isVisible =
-            BuildConfig.EMOJI_REACTION_NOTIFICATIONS_ENABLED
-
         voipRingtonePreference = getPref(R.string.preferences__voip_ringtone)
         voipRingtonePreference.updateRingtoneSummary(R.string.preferences__voip_ringtone)
         groupCallsRingtonePreference = getPref(R.string.preferences__group_calls_ringtone)

+ 2 - 0
app/src/main/java/ch/threema/app/preference/service/PreferenceService.kt

@@ -260,6 +260,8 @@ interface PreferenceService {
 
     fun watchArePrivateChatsHidden(): Flow<Boolean>
 
+    fun isContactSyncEnabled(): Boolean
+
     fun watchIsContactSyncEnabled(): Flow<Boolean>
 
     fun getLockMechanism(): LockMechanism

+ 3 - 0
app/src/main/java/ch/threema/app/preference/service/PreferenceServiceImpl.kt

@@ -405,6 +405,9 @@ class PreferenceServiceImpl(
     override fun watchArePrivateChatsHidden(): Flow<Boolean> =
         preferenceStore.watchBoolean(getKeyName(R.string.preferences__chats_hidden))
 
+    override fun isContactSyncEnabled(): Boolean =
+        preferenceStore.getBoolean(getKeyName(R.string.preferences__sync_contacts))
+
     override fun watchIsContactSyncEnabled(): Flow<Boolean> =
         preferenceStore.watchBoolean(getKeyName(R.string.preferences__sync_contacts))
 

+ 0 - 4
app/src/main/java/ch/threema/app/processors/incomingcspmessage/conversation/IncomingContactReactionMessageTask.kt

@@ -1,6 +1,5 @@
 package ch.threema.app.processors.incomingcspmessage.conversation
 
-import ch.threema.app.BuildConfig
 import ch.threema.app.di.injectNullableNonBinding
 import ch.threema.app.managers.ServiceManager
 import ch.threema.app.messagereceiver.ContactMessageReceiver
@@ -75,9 +74,6 @@ class IncomingContactReactionMessageTask(
     }
 
     private fun handleNotification(targetMessage: MessageModel) {
-        if (!BuildConfig.EMOJI_REACTION_NOTIFICATIONS_ENABLED) {
-            return
-        }
         if (!targetMessage.isOutbox) {
             return
         }

+ 0 - 4
app/src/main/java/ch/threema/app/processors/incomingcspmessage/conversation/IncomingGroupReactionMessageTask.kt

@@ -1,6 +1,5 @@
 package ch.threema.app.processors.incomingcspmessage.conversation
 
-import ch.threema.app.BuildConfig
 import ch.threema.app.di.injectNullableNonBinding
 import ch.threema.app.managers.ServiceManager
 import ch.threema.app.notifications.ConversationNotificationConverter
@@ -102,9 +101,6 @@ class IncomingGroupReactionMessageTask(
     }
 
     private fun handleNotification(targetMessage: MessageModel) {
-        if (!BuildConfig.EMOJI_REACTION_NOTIFICATIONS_ENABLED) {
-            return
-        }
         if (!targetMessage.isOutbox) {
             return
         }

+ 0 - 200
app/src/main/java/ch/threema/app/services/PollingHelper.java

@@ -1,200 +0,0 @@
-package ch.threema.app.services;
-
-import android.app.AlarmManager;
-import android.app.PendingIntent;
-import android.content.Context;
-import android.content.Intent;
-import android.os.PowerManager;
-import android.text.format.DateUtils;
-
-import org.koin.java.KoinJavaComponent;
-import org.slf4j.Logger;
-
-import java.util.Timer;
-import java.util.TimerTask;
-
-import androidx.annotation.NonNull;
-import ch.threema.app.BuildConfig;
-import ch.threema.app.GlobalAppState;
-import ch.threema.app.connection.ServerConnectionManager;
-import ch.threema.app.managers.ServiceManager;
-import ch.threema.app.receivers.FetchMessagesBroadcastReceiver;
-
-import static ch.threema.android.PendingIntentExtensionsKt.getPendingIntentForBroadcast;
-import static ch.threema.base.utils.LoggingKt.getThreemaLogger;
-import ch.threema.domain.protocol.connection.ConnectionState;
-import ch.threema.domain.taskmanager.QueueSendCompleteListener;
-
-import ch.threema.app.utils.IntentDataUtil;
-
-/**
- * Helper class to simplify polling (both time-based and FCM based) by handling all the gory details
- * of connecting for new messages and ensuring that the connection is released once the server
- * has sent all new messages.
- */
-public class PollingHelper implements QueueSendCompleteListener {
-    private static final Logger logger = getThreemaLogger("PollingHelper");
-
-    private static final int CONNECTION_TIMEOUT = 1000 * 120;       /* maximum time to stay connected for each poll (usually the connection will be terminated earlier as the server signals the end of the queue) */
-    private static final int CONNECTION_TIMEOUT_ALREADY_CONNECTED = 1000 * 60;      /* same, but timeout to use if we're already connected when polling */
-    static final int CONNECTION_LINGER = 1000 * 5;          /* linger a bit to allow outgoing delivery receipts to be sent */
-
-    private static volatile Timer timer;     /* same timer for all instances */
-    private static final Object timerLock = new Object();
-
-    private final @NonNull Context context;
-    private final @NonNull String lifetimeServiceTag;
-    private final @NonNull GlobalAppState globalAppState = KoinJavaComponent.get(GlobalAppState.class);
-
-    private boolean connectionAcquired;
-    private PowerManager.WakeLock wakeLock;
-    private TimerTask timeoutTask;
-
-    public PollingHelper(@NonNull Context context, @NonNull String lifetimeServiceTag) {
-        this.context = context;
-        this.lifetimeServiceTag = lifetimeServiceTag;
-    }
-
-    /**
-     * Return whether polling was successful.
-     */
-    public synchronized boolean poll(final boolean useWakeLock) {
-        logger.info("Fetch attempt. Source = {}", lifetimeServiceTag);
-
-        final ServiceManager serviceManager = ServiceManager.get();
-        if (serviceManager == null) {
-            return false;
-        }
-
-        // If the device is not online, there's no use in trying to connect.
-        boolean isOnline = serviceManager.getDeviceService().isOnline();
-        if (!isOnline) {
-            logger.info("Not polling, device is offline");
-            return false;
-        }
-
-        if (!connectionAcquired) {
-            // Don't poll if the app is currently in a special mode
-            if (globalAppState.getSpecialMode() != null) {
-                return false;
-            }
-
-            // If requested, acquire a wakelock
-            if (useWakeLock) {
-                logger.info("Acquiring wakelock");
-                if (wakeLock == null) {
-                    PowerManager pm = (PowerManager) context.getApplicationContext().getSystemService(Context.POWER_SERVICE);
-                    wakeLock = pm.newWakeLock(
-                        PowerManager.PARTIAL_WAKE_LOCK,
-                        BuildConfig.APPLICATION_ID + ":PollingHelper"
-                    );
-                }
-                wakeLock.acquire(DateUtils.MINUTE_IN_MILLIS * 10);
-            }
-
-            // We want to be notified when the server signals that the message queue was flushed completely
-            serviceManager.getTaskManager().addQueueSendCompleteListener(this);
-
-            // Determine timeout duration. If we're already connected it can be shorter.
-            long timeout = CONNECTION_TIMEOUT;
-            ServerConnectionManager serverConnectionManager = KoinJavaComponent.get(ServerConnectionManager.class);
-            if (serverConnectionManager.getConnection().getConnectionState() == ConnectionState.LOGGED_IN) {
-                logger.info("Already connected");
-                timeout = CONNECTION_TIMEOUT_ALREADY_CONNECTED;
-            }
-
-            // Acquire a connection to the Threema server
-            final LifetimeService lifetimeService = serviceManager.getLifetimeService();
-            lifetimeService.acquireConnection(this.lifetimeServiceTag);
-
-            if (!lifetimeService.isActive()) {
-                AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
-                PendingIntent pendingIntent = getPendingIntentForBroadcast(
-                    this.context,
-                    0,
-                    new Intent(this.context, FetchMessagesBroadcastReceiver.class),
-                    IntentDataUtil.PENDING_INTENT_FLAG_MUTABLE
-                );
-
-                // cancel pending alarms
-                alarmManager.cancel(pendingIntent);
-
-                // try again in two minutes
-                logger.info("Schedule another fetching attempt in two minutes");
-                alarmManager.setAndAllowWhileIdle(AlarmManager.RTC, System.currentTimeMillis() + timeout, pendingIntent);
-
-                // return false
-                connectionAcquired = false;
-                return false;
-            }
-
-            // Polling was successful
-            connectionAcquired = true;
-
-            /* schedule a TimerTask so we will release this connection if it's taking too long to receive the queue completion message */
-            if (timeoutTask != null)
-                timeoutTask.cancel();
-
-            timeoutTask = new TimerTask() {
-                @Override
-                public void run() {
-                    logger.warn("Timeout fetching message. Releasing connection");
-                    releaseConnection();
-                }
-            };
-
-            this.schedule(timeoutTask, timeout);
-
-            return true;
-        } else {
-            logger.info("Fetch attempt. Connection already acquired.");
-
-            return true;
-        }
-    }
-
-    private void schedule(TimerTask timerTask, long timeout) {
-        if (timer == null) {
-            synchronized (timerLock) {
-                if (timer == null) {
-                    timer = new Timer("PollingHelper");
-                }
-            }
-        }
-        timer.schedule(timerTask, timeout);
-    }
-
-    @Override
-    public synchronized void queueSendComplete() {
-        logger.info("Received queue send complete message from server");
-        releaseConnection();
-    }
-
-    private synchronized void releaseConnection() {
-        logger.debug("release connection");
-
-        if (connectionAcquired) {
-            ServiceManager serviceManager = ServiceManager.get();
-
-            if (serviceManager != null) {
-                serviceManager.getTaskManager().removeQueueSendCompleteListener(this);
-
-                final LifetimeService lifetimeService = serviceManager.getLifetimeService();
-                lifetimeService.releaseConnectionLinger(this.lifetimeServiceTag, CONNECTION_LINGER);
-                connectionAcquired = false;
-
-                if (timeoutTask != null) {
-                    timeoutTask.cancel();
-                    timeoutTask = null;
-                }
-
-                if (wakeLock != null && wakeLock.isHeld()) {
-                    logger.info("Releasing wakelock");
-                    wakeLock.release();
-                }
-            } else {
-                connectionAcquired = false;
-            }
-        }
-    }
-}

+ 217 - 0
app/src/main/java/ch/threema/app/services/PollingHelper.kt

@@ -0,0 +1,217 @@
+package ch.threema.app.services
+
+import android.app.AlarmManager
+import android.content.Context
+import android.content.Intent
+import android.os.PowerManager
+import androidx.core.content.getSystemService
+import ch.threema.android.getPendingIntentForBroadcast
+import ch.threema.app.BuildConfig
+import ch.threema.app.GlobalAppState
+import ch.threema.app.connection.ServerConnectionManager
+import ch.threema.app.di.injectNullableNonBinding
+import ch.threema.app.receivers.FetchMessagesBroadcastReceiver
+import ch.threema.app.utils.IntentDataUtil
+import ch.threema.base.utils.getThreemaLogger
+import ch.threema.common.DispatcherProvider
+import ch.threema.common.TimeProvider
+import ch.threema.common.await
+import ch.threema.common.plus
+import ch.threema.domain.protocol.connection.ConnectionState
+import ch.threema.domain.taskmanager.QueueSendCompleteState
+import ch.threema.domain.taskmanager.TaskManager
+import kotlin.time.Duration
+import kotlin.time.Duration.Companion.minutes
+import kotlin.time.Duration.Companion.seconds
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.TimeoutCancellationException
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withTimeout
+import org.koin.core.component.KoinComponent
+import org.koin.core.component.inject
+
+private val logger = getThreemaLogger("PollingHelper")
+
+/**
+ * Helper class to simplify polling (both time-based and FCM-based) by handling all the gory details of connecting to fetch new messages and of
+ * ensuring that the connection is released once the server has sent all new messages.
+ *
+ * This class is thread-safe. However, wake lock handling is best-effort: if multiple instances of this class exist, the wake lock may be released
+ * too early.
+ */
+class PollingHelper(
+    appContext: Context,
+    private val lifetimeServiceTag: LifetimeService.SourceTag,
+) : KoinComponent {
+    private val context: Context = appContext.applicationContext
+    private val globalAppState: GlobalAppState by inject()
+    private val deviceService: DeviceService? by injectNullableNonBinding()
+    private val taskManager: TaskManager? by injectNullableNonBinding()
+    private val lifetimeService: LifetimeService? by injectNullableNonBinding()
+    private val serverConnectionManager: ServerConnectionManager? by injectNullableNonBinding()
+    private val dispatcherProvider: DispatcherProvider by inject()
+    private val timeProvider: TimeProvider by inject()
+    private val pollScope = CoroutineScope(dispatcherProvider.worker)
+
+    @Volatile
+    private var connectionAcquired = false
+
+    // The wake lock handle, cached to avoid creating a new one for every poll
+    private var wakeLock: PowerManager.WakeLock? = null
+
+    /**
+     * Try to connect to the server and fetch new messages.
+     *
+     * If a connection slot is already held by this instance, this method does nothing.
+     *
+     * @param useWakeLock if set to true, a partial wake lock will be acquired while polling and during the connection linger phase
+     * @return true if a connection slot was (or already is) acquired, false otherwise
+     */
+    @Synchronized
+    fun poll(useWakeLock: Boolean): Boolean {
+        logger.info("Fetch attempt. Source = {}", lifetimeServiceTag)
+
+        val deviceService = this.deviceService ?: return false
+        val taskManager = this.taskManager ?: return false
+        val lifetimeService = this.lifetimeService ?: return false
+
+        // If the device is not online, there's no use in trying to connect.
+        if (!deviceService.isOnline()) {
+            logger.info("Not polling, device is offline")
+            return false
+        }
+
+        if (connectionAcquired) {
+            logger.info("Fetch attempt. Connection already acquired.")
+            return true
+        }
+
+        // Don't poll if the app is currently in a special mode
+        if (globalAppState.specialMode != null) {
+            return false
+        }
+
+        // If requested, acquire a wakelock
+        val wakeLock = if (useWakeLock) acquireWakeLock() else null
+
+        // Determine timeout duration. If we're already connected it can be shorter.
+        var timeout = CONNECTION_TIMEOUT
+        if (serverConnectionManager?.connection?.connectionState == ConnectionState.LOGGED_IN) {
+            logger.info("Already connected")
+            timeout = CONNECTION_TIMEOUT_ALREADY_CONNECTED
+        }
+
+        // Acquire a connection to the Threema server
+        lifetimeService.acquireConnection(lifetimeServiceTag)
+
+        if (!lifetimeService.isActive) {
+            scheduleRetryAlarm(timeout)
+            releaseWakeLock(wakeLock)
+            return false
+        }
+
+        // Polling was successful, run the poll in the background
+        connectionAcquired = true
+        pollScope.launch {
+            runPoll(taskManager, lifetimeService, timeout, wakeLock)
+        }
+
+        return true
+    }
+
+    /**
+     * Waits until the queue of the current connection is dry or the timeout is reached, then releases the connection (it will linger for a bit,
+     * so that outgoing delivery receipts can be sent) and the wake lock (if any).
+     *
+     * The DRY state is only reported while the connection is open, so if the connection drops we keep waiting for the next connection attempt, up
+     * to the timeout.
+     */
+    private suspend fun runPoll(
+        taskManager: TaskManager,
+        lifetimeService: LifetimeService,
+        timeout: Duration,
+        wakeLock: PowerManager.WakeLock?,
+    ) {
+        try {
+            withTimeout(timeout) {
+                taskManager.watchQueueSendComplete().await(QueueSendCompleteState.DRY)
+            }
+            logger.info("Queue of the current connection is dry, releasing connection (source={})", lifetimeServiceTag)
+        } catch (_: TimeoutCancellationException) {
+            logger.warn("Timeout fetching message (source={}). Releasing connection", lifetimeServiceTag)
+        }
+
+        logger.debug("Releasing connection (source={})", lifetimeServiceTag)
+
+        // Release the connection slot and mark the connection as released, atomically. The slot is released while the flag is still set, so a
+        // concurrent poll cannot re-acquire it.
+        synchronized(this) {
+            lifetimeService.releaseConnectionLinger(lifetimeServiceTag, CONNECTION_LINGER)
+            connectionAcquired = false
+        }
+
+        // Keep the wakelock until the connection linger phase is over, so the app is not killed while the connection is still active.
+        delay(CONNECTION_LINGER)
+        releaseWakeLock(wakeLock)
+    }
+
+    private fun scheduleRetryAlarm(timeout: Duration) {
+        val alarmManager = context.getSystemService<AlarmManager>()
+        val pendingIntent = getPendingIntentForBroadcast(
+            context = context,
+            requestCode = 0,
+            intent = Intent(context, FetchMessagesBroadcastReceiver::class.java),
+            flags = IntentDataUtil.PENDING_INTENT_FLAG_MUTABLE,
+        )
+
+        // Cancel pending alarms
+        alarmManager?.cancel(pendingIntent)
+
+        logger.info("Schedule another fetching attempt in two minutes")
+        alarmManager?.setAndAllowWhileIdle(
+            AlarmManager.RTC,
+            (timeProvider.get() + timeout).toEpochMilli(),
+            pendingIntent,
+        )
+    }
+
+    private fun acquireWakeLock(): PowerManager.WakeLock? {
+        val powerManager = context.getSystemService<PowerManager>()
+        if (powerManager == null) {
+            logger.warn("PowerManager not available, continuing without wakelock")
+            return null
+        }
+        logger.info("Acquiring wakelock")
+        val lock = wakeLock
+            ?: powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKE_LOCK_TAG).also { wakeLock = it }
+        lock.acquire(WAKE_LOCK_TIMEOUT.inWholeMilliseconds)
+        return lock
+    }
+
+    private fun releaseWakeLock(wakeLock: PowerManager.WakeLock?) {
+        if (wakeLock?.isHeld == true) {
+            logger.info("Releasing wakelock")
+            wakeLock.release()
+        }
+    }
+
+    companion object {
+        /** Tag identifying the wake locks acquired by this class. Must be unique per consumer. */
+        private const val WAKE_LOCK_TAG = BuildConfig.APPLICATION_ID + ":PollingHelper"
+
+        /** Maximum time to hold the wake lock (the release is always much earlier in practice) */
+        private val WAKE_LOCK_TIMEOUT = 10.minutes
+
+        /**
+         * Maximum time to stay connected for each poll (usually the connection will be terminated earlier as the server signals the end of the queue)
+         */
+        private val CONNECTION_TIMEOUT = 2.minutes
+
+        /** Same, but timeout to use if we're already connected when polling */
+        private val CONNECTION_TIMEOUT_ALREADY_CONNECTED = 60.seconds
+
+        /** Linger a bit to allow outgoing delivery receipts to be sent */
+        private val CONNECTION_LINGER = 5.seconds
+    }
+}

+ 4 - 2
app/src/main/java/ch/threema/app/services/notification/BaseNotificationService.kt

@@ -20,9 +20,8 @@ private val logger = getThreemaLogger("BaseNotificationService")
 
 abstract class BaseNotificationService(
     protected val appContext: Context,
+    protected val notificationManagerCompat: NotificationManagerCompat,
 ) {
-    protected val notificationManagerCompat: NotificationManagerCompat = NotificationManagerCompat.from(appContext)
-
     protected fun notify(
         notificationId: Int,
         notification: Notification,
@@ -82,4 +81,7 @@ abstract class BaseNotificationService(
             logger.warn("Failed to cancel notification {}", notificationId, e)
         }
     }
+
+    protected fun hasNotificationPermission(): Boolean =
+        notificationManagerCompat.areNotificationsEnabled()
 }

+ 1 - 1
app/src/main/java/ch/threema/app/services/notification/ConversationReactionNotification.kt

@@ -36,7 +36,7 @@ abstract class ConversationReactionNotification(
     thumbnailMimeType: String?,
     fetchThumbnailUri: FetchCacheUri?,
     senderPerson: Person?,
-    private val targetMessage: MessageModel,
+    val targetMessage: MessageModel,
     val emojiSequences: List<String>,
 ) : ConversationNotification(
     messageId = messageId,

+ 16 - 11
app/src/main/java/ch/threema/app/services/notification/NotificationServiceImpl.kt

@@ -10,6 +10,7 @@ import android.content.Intent
 import android.media.AudioManager
 import android.os.Build
 import androidx.core.app.NotificationCompat
+import androidx.core.app.NotificationManagerCompat
 import androidx.core.app.Person
 import androidx.core.app.RemoteInput
 import androidx.core.content.ContextCompat
@@ -24,7 +25,6 @@ import ch.threema.android.getPendingIntentForActivity
 import ch.threema.android.getPendingIntentForBroadcast
 import ch.threema.android.getPendingIntentForService
 import ch.threema.app.AppConstants
-import ch.threema.app.BuildConfig
 import ch.threema.app.R
 import ch.threema.app.activities.BackupAdminActivity
 import ch.threema.app.activities.ComposeMessageActivity
@@ -90,6 +90,7 @@ private val logger = getThreemaLogger("NotificationServiceImpl")
 @SessionScoped
 class NotificationServiceImpl(
     appContext: Context,
+    notificationManagerCompat: NotificationManagerCompat,
     private val getConversationCategoryUseCase: GetConversationCategoryUseCase,
     private val lockAppService: LockAppService,
     private val notificationPreferenceService: NotificationPreferenceService,
@@ -100,7 +101,7 @@ class NotificationServiceImpl(
     private val doNotDisturbUtil: DoNotDisturbUtil,
     private val timeProvider: TimeProvider,
     private val widgetUpdater: WidgetUpdater,
-) : BaseNotificationService(appContext), NotificationService, KoinComponent {
+) : BaseNotificationService(appContext, notificationManagerCompat), NotificationService, KoinComponent {
 
     private val conversationNotificationStore = ConversationNotificationStore()
     private var visibleConversationId: ConversationId? = null
@@ -1173,10 +1174,6 @@ class NotificationServiceImpl(
     }
 
     override fun showEmojiReactionNotification(reactionNotification: ConversationReactionNotification) {
-        if (!BuildConfig.EMOJI_REACTION_NOTIFICATIONS_ENABLED) {
-            return
-        }
-
         if (ConfigUtils.hasInvalidCredentials()) {
             logger.debug("Credentials are not (or no longer) valid. Suppressing reaction notification.")
             return
@@ -1237,9 +1234,6 @@ class NotificationServiceImpl(
     }
 
     override fun cancelEmojiReactionNotification(conversationId: ConversationId, messageUid: MessageUid) {
-        if (!BuildConfig.EMOJI_REACTION_NOTIFICATIONS_ENABLED) {
-            return
-        }
         accessExclusively { accessor ->
             accessor.removeReactionNotification(messageUid)
             // It is important here that we cancel the notification even if the conversationNotificationStore does not know about it,
@@ -1365,8 +1359,8 @@ class NotificationServiceImpl(
             }
 
             setContentIntent(
-                createPendingIntentForConversation(
-                    conversationId = conversationId,
+                createPendingIntentForConversationJumpToMessage(
+                    message = headerReaction.targetMessage,
                     requestCode = conversationHandle.getRequestCode(ConversationNotificationAction.OPEN),
                 ),
             )
@@ -1389,6 +1383,17 @@ class NotificationServiceImpl(
         notifyConversationsSummary(defaultChannelId)
     }
 
+    private fun createPendingIntentForConversationJumpToMessage(message: MessageModel, requestCode: Int): PendingIntent {
+        val intent = ComposeMessageActivity.createIntentJumpToMessage(appContext, message)
+            .setFlags(
+                Intent.FLAG_ACTIVITY_NEW_TASK or
+                    Intent.FLAG_ACTIVITY_CLEAR_TOP or
+                    Intent.FLAG_ACTIVITY_SINGLE_TOP or
+                    Intent.FLAG_ACTIVITY_NO_USER_ACTION,
+            )
+        return createPendingIntentWithTaskStack(intent, requestCode)
+    }
+
     override fun cancelAllConversationNotifications(conversationId: ConversationId) {
         cancelAllConversationNotifications(setOf(conversationId))
     }

+ 3 - 1
app/src/main/java/ch/threema/app/services/notification/PassphraseNotificationService.kt

@@ -3,6 +3,7 @@ package ch.threema.app.services.notification
 import android.content.Context
 import android.media.AudioManager
 import androidx.core.app.NotificationCompat
+import androidx.core.app.NotificationManagerCompat
 import ch.threema.android.buildNotification
 import ch.threema.app.R
 import ch.threema.app.notifications.NotificationChannels
@@ -11,8 +12,9 @@ import ch.threema.app.services.NotificationPreferenceService
 
 class PassphraseNotificationService(
     appContext: Context,
+    notificationManagerCompat: NotificationManagerCompat,
     private val notificationPreferenceService: NotificationPreferenceService,
-) : BaseNotificationService(appContext) {
+) : BaseNotificationService(appContext, notificationManagerCompat) {
     fun showNewMessagesPassphraseNotification() {
         val notification = buildNotification(appContext, NotificationChannels.NOTIFICATION_CHANNEL_CHATS_DEFAULT) {
             setSmallIcon(R.drawable.ic_notification_small)

+ 4 - 0
app/src/main/java/ch/threema/app/usecases/CheckLicenseUseCase.kt

@@ -31,6 +31,10 @@ class CheckLicenseUseCase(
 ) {
     /**
      * Checks the license.
+     *
+     * Warning: The HMS license check might open an activity. It is important that this method is only called if we are certain that
+     * no other activity will be started immediately after. The later activity could cover up HMS license check's activity, which leaves it
+     * in an invalid state from which it can not recover.
      */
     suspend fun call(activity: Activity) {
         logger.info("Running license check")

+ 1 - 0
app/src/main/java/ch/threema/app/usecases/GetDebugMetaDataUseCase.kt

@@ -80,6 +80,7 @@ class GetDebugMetaDataUseCase(
             )
             keyValuePair("uses multi device", multiDeviceManager?.isMultiDeviceActive)
             keyValuePair("uses threema push", preferenceService.mustUseThreemaPush())
+            keyValuePair("uses contact sync", preferenceService.isContactSyncEnabled())
         }
     }
 

+ 0 - 1
app/src/main/java/ch/threema/app/utils/ContactUtil.java

@@ -147,7 +147,6 @@ public class ContactUtil {
 
     public static boolean canHaveCustomAvatar(@Nullable ContactModel contact) {
         return contact != null
-            && !contact.isLinkedToAndroidContact()
             && !isGatewayContact(contact.getIdentity());
     }
 

+ 62 - 0
app/src/main/java/ch/threema/app/voicemessage/SamsungQuirkAudioSink.kt

@@ -1,9 +1,17 @@
 package ch.threema.app.voicemessage
 
 import android.content.Context
+import android.media.AudioDeviceInfo
+import android.os.Build
+import androidx.annotation.RequiresApi
+import androidx.media3.common.Format
+import androidx.media3.common.util.Clock
 import androidx.media3.common.util.UnstableApi
 import androidx.media3.exoplayer.DefaultRenderersFactory
+import androidx.media3.exoplayer.analytics.PlayerId
 import androidx.media3.exoplayer.audio.AudioCapabilities
+import androidx.media3.exoplayer.audio.AudioOffloadSupport
+import androidx.media3.exoplayer.audio.AudioOutputProvider
 import androidx.media3.exoplayer.audio.AudioSink
 import androidx.media3.exoplayer.audio.DefaultAudioSink
 import ch.threema.base.utils.getThreemaLogger
@@ -43,6 +51,60 @@ class SamsungQuirkAudioSink(
         }
         return false
     }
+
+    override fun configure(audioSinkConfig: AudioSink.AudioSinkConfig) {
+        delegate.configure(audioSinkConfig)
+    }
+
+    override fun getAudioCapabilities(): AudioCapabilities? =
+        delegate.audioCapabilities
+
+    override fun setPreferredDevice(audioDeviceInfo: AudioDeviceInfo?) {
+        delegate.setPreferredDevice(audioDeviceInfo)
+    }
+
+    override fun setVirtualDeviceId(virtualDeviceId: Int) {
+        delegate.setVirtualDeviceId(virtualDeviceId)
+    }
+
+    override fun setOutputStreamOffsetUs(outputStreamOffsetUs: Long) {
+        delegate.setOutputStreamOffsetUs(outputStreamOffsetUs)
+    }
+
+    @RequiresApi(Build.VERSION_CODES.Q)
+    override fun setOffloadMode(offloadMode: Int) {
+        delegate.setOffloadMode(offloadMode)
+    }
+
+    @RequiresApi(Build.VERSION_CODES.Q)
+    override fun setOffloadDelayPadding(delayInFrames: Int, paddingInFrames: Int) {
+        delegate.setOffloadDelayPadding(delayInFrames, paddingInFrames)
+    }
+
+    override fun setAudioOutputProvider(audioOutputProvider: AudioOutputProvider) {
+        delegate.setAudioOutputProvider(audioOutputProvider)
+    }
+
+    override fun release() {
+        delegate.release()
+    }
+
+    override fun setPlayerId(playerId: PlayerId?) {
+        delegate.setPlayerId(playerId)
+    }
+
+    override fun setClock(clock: Clock) {
+        delegate.setClock(clock)
+    }
+
+    override fun getFormatOffloadSupport(format: Format): AudioOffloadSupport {
+        return delegate.getFormatOffloadSupport(format)
+    }
+
+    @Deprecated("Deprecated in Java")
+    override fun configure(inputFormat: Format, specifiedBufferSize: Int, outputChannels: IntArray?) {
+        delegate.configure(inputFormat, specifiedBufferSize, outputChannels)
+    }
 }
 
 class SamsungQuirkRenderersFactory(val context: Context) : DefaultRenderersFactory(context) {

+ 3 - 1
app/src/main/java/ch/threema/app/voip/services/VoipStateService.java

@@ -717,6 +717,9 @@ public class VoipStateService implements AudioManager.OnAudioFocusChangeListener
         } else if (notificationResult instanceof IncomingCallNotificationResult.IncomingCallNotificationsDisabled) {
             logger.warn("Notifications are disabled. Trying to start call activity.");
             launchCallActivityIntent(inCallPendingIntent);
+        } else if (notificationResult instanceof IncomingCallNotificationResult.Failed) {
+            logger.warn("Failed to display notification. Trying to start call activity.");
+            launchCallActivityIntent(inCallPendingIntent);
         }
 
         // Update conversation timestamp
@@ -1457,7 +1460,6 @@ public class VoipStateService implements AudioManager.OnAudioFocusChangeListener
     }
 
     private void launchCallActivityIntent(@NonNull PendingIntent inCallPendingIntent) {
-        // notifications disabled in system settings - fire inCall pending intent to show CallActivity
         try {
             if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
                 ActivityOptions options = ActivityOptions.makeBasic().setPendingIntentBackgroundActivityStartMode(ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_DENIED);

+ 1 - 1
app/src/main/java/ch/threema/storage/factories/DistributionListMessageModelFactory.java

@@ -197,7 +197,7 @@ public class DistributionListMessageModelFactory extends MessageModelFactory {
     public long countMessages(long distributionListId) {
         return readCountQueryResult(getReadableDatabase().rawQuery(
             "SELECT COUNT(*) FROM " + this.getTableName()
-                + " WHERE " + DistributionListMessageModel.COLUMN_ID + "=?",
+                + " WHERE " + DistributionListMessageModel.COLUMN_DISTRIBUTION_LIST_ID + "=?",
             new String[]{
                 String.valueOf(distributionListId)
             }

+ 50 - 0
app/src/main/res/values-sk/strings.xml

@@ -171,9 +171,11 @@
     <!-- ${app_name_short} is a placeholder for the app's name, e.g. "Threema". It must be left as-is and not translated. -->
     <string name="backup_sum">Exportovať vaše ${app_name_short} ID</string>
     <string name="backup_and_delete">Záloha a odstránenie</string>
+    <string name="delete_id_menu_title">Odstrániť ID a údaje</string>
     <string name="delete_id_message">Ak ste si nevytvorili zálohu alebo neexportovali a neuložili kópiu tohto ID, už nikdy nebudete môcť odosielať ani prijímať
         správy s týmto ID.\n\nAk už nechcete toto ID používať, odporúčame vám pred jeho vymazaním nastaviť heslo na zrušenie a ID zrušiť na stránke myid.threema.ch/revoke.</string>
     <string name="delete_id_message2">Posledné varovanie: naozaj chcete z tohto zariadenia vymazať vaše ID?</string>
+    <string name="delete_id_summary">Odstrániť svoje ${app_name_short}-ID a všetky údaje z tohto zariadenia</string>
     <string name="delete_all_data_prompt">Odstrániť všetky údaje aplikácie?</string>
     <string name="backup_password_summary">Export vášho ID bude zašifrovaný heslom. Použite kombináciu písmen, čísel a symbolov. Nezabudnite, čo sem zadáte!</string>
     <string name="backup_password_again_summary">Vložte heslo znovu</string>
@@ -241,6 +243,7 @@ alebo naskenovať QR kód pomocou iného zariadenia.</string>
     <string name="an_error_occurred">Vyskytla sa chyba</string>
     <string name="an_error_occurred_more">Vyskytla sa chyba: “%1$s”</string>
     <!-- Error message shown to the user if the app fails to start. ${app_name_short} is a placeholder for the app's name, e.g. "Threema". It must be left as-is and not translated. -->
+    <string name="startup_error_details">Aplikáciu ${app_name_short} sa nepodarilo otvoriť kvôli neočakávanej chybe.  Prosím, exportujte nižšie uvedený súbor protokolu a kontaktujte náš tím technickej podpory, aby sme mohli tento problém prešetriť. Ospravedlňujeme sa za spôsobené nepríjemnosti.</string>
     <string name="acknowledge">Súhlasím</string>
     <string name="decline">Nesúhlasím</string>
     <string name="forward_message">Preposlať správu</string>
@@ -789,6 +792,8 @@ Už ich nebude možné obnoviť.</string>
     <string name="text">Text</string>
     <string name="undo">Vrátiť späť</string>
     <string name="android_backup_date">Posledná záloha</string>
+    <string name="threema_safe_configuration_title">Konfigurácia</string>
+    <string name="threema_safe_last_backup_date_and_time">Čas</string>
     <string name="discard">Zrušiť</string>
     <string name="android_backup_restart_threema">Vydržte. Aplikácia sa reštartuje o pár sekúnd.</string>
     <string name="battery_optimizations_title">Vypnúť optimalizáciu batérie</string>
@@ -1290,6 +1295,7 @@ Vykonajte prosím zálohú vašich údajov vhodnou metódou.</string>
     <string name="prefs_header_receipts">Potvrdenia</string>
     <string name="prefs_title_reset_receipts">Vymazať individuálne nastavenia</string>
     <string name="prefs_sum_reset_receipts">Obnovenie predvolených nastavení špecifických pre kontakt pre potvrdenia o prečítaní a indikátor písania</string>
+    <string name="confirm_sum_reset_receipts">Obnoviť predvolené nastavenia pre jednotlivé kontakty týkajúce sa potvrdení o prečítaní a indikátora písania?</string>
     <string name="reset_successful">Predvolené nastavenia úspešne obnovené</string>
     <!-- ${app_name_short} is a placeholder for the app's name, e.g. "Threema". It must be left as-is and not translated. -->
     <string name="qr_scanner_id_hint">Naskenujte QR kód kontaktu a overte jeho identitu. Ak chcete zobraziť kód, požiadajte svoj kontakt, aby klikol na profilový obrázok v ľavom hornom rohu domovskej obrazovky ${app_name_short}.</string>
@@ -1554,7 +1560,9 @@ Vykonajte prosím zálohú vašich údajov vhodnou metódou.</string>
     <!-- ${app_name_short} is a placeholder for the app's name, e.g. "Threema". It must be left as-is and not translated. -->
     <string name="problemsolver_explain_app_battery_usgae_optimized">Aplikácia nemá povolené udržiavať trvalé pripojenie k serverom, ktoré je potrebné na fungovanie služby ${app_name_short} Push. Keď je aplikácia na pozadí, nebudete informovaní o nových správach. Ak to chcete napraviť, klepnite v informáciach o aplikácii na položku \"Batéria\" a vyberte možnosť \"Neobmedzené\".</string>
     <!-- Title of warning message that informs the user that the version of Android they are using will soon no longer be supported. -->
+    <string name="problemsolver_title_android_version_deprecated">Táto verzia už čoskoro nebude podporovaná</string>
     <!-- Details of warning message that informs the user that the version of Android they are using will soon no longer be supported. ${app_name} is a placeholder that should be kept as-is and not translated. -->
+    <string name="problemsolver_explain_android_version_deprecated">Používate zariadenie s operačným systémom Android, ktoré už nedostáva softvérové aktualizácie. Z bezpečnostných dôvodov bude táto verzia systému Android čoskoro prestane byť podporovaná aplikáciou ${app_name}.</string>
     <string name="problemsolver_to_settings">K nastaveniam</string>
     <!-- Label on button to dismiss/hide a warning -->
     <string name="problemsolver_dismiss">Zatvoriť</string>
@@ -1784,18 +1792,21 @@ Vykonajte prosím zálohú vašich údajov vhodnou metódou.</string>
     Placeholder %1$s will be replaced with the emojis.
     Placeholder %2$s will be replaced with a preview of the message that was reacted on.
     -->
+    <string name="emoji_reaction_notification_body_contact">Reagoval %1$s na: %2$s</string>
     <!--
     Text that is displayed in an emoji reaction system notification for a 1 to 1 conversation with many emojis.
     Placeholder %1$s will be replaced with the emojis until a defined count.
     Placeholder %2$d will be replaced with the remaining emoji count that is not displayed in %1$s.
     Placeholder %3$s will be replaced with a preview of the message that was reacted on.
     -->
+    <string name="emoji_reaction_notification_body_contact_more">Reagoval %1$s +%2$d na: %3$s</string>
     <!--
     Text that is displayed in an emoji reaction system notification for a group conversation and a single reactor person.
     Placeholder %1$s will be replaced with the name of the reacting person.
     Placeholder %2$s will be replaced with the emojis.
     Placeholder %3$s will be replaced with a preview of the message that was reacted on.
     -->
+    <string name="emoji_reaction_notification_body_group_one_person">%1$s reagoval(a) %2$s na: %3$s</string>
     <!--
     Text that is displayed in an emoji reaction system notification for a group conversation and a single reactor person with many emojis.
     Placeholder %1$s will be replaced with the name of the reacting person.
@@ -1803,30 +1814,63 @@ Vykonajte prosím zálohú vašich údajov vhodnou metódou.</string>
     Placeholder %3$d will be replaced with the remaining emoji count that is not displayed in %2$s.
     Placeholder %4$s will be replaced with a preview of the message that was reacted on.
     -->
+    <string name="emoji_reaction_notification_body_group_one_person_more">%1$s reagoval(a) %2$s +%3$d na: %4$s</string>
     <!--
     Text that is displayed in an emoji reaction system notification for a group conversation with 2 reacting persons.
     Placeholder %1$s will be replaced with the name of the reacting person.
     Placeholder %2$s will be replaced with the name of the other reacting person.
     Placeholder %3$s will be replaced with a preview of the message that was reacted on.
     -->
+    <string name="emoji_reaction_notification_body_group_two_persons">%1$s a %2$s reagovali na: %3$s</string>
     <!--
     Text that is displayed in an emoji reaction system notification for a group conversation with more than 2 reacting persons.
     Placeholder %1$s will be replaced with the name of the most recent reacting person.
     Placeholder %2$d will be replaced with the remaining person count that also reacted.
     Placeholder %3$s will be replaced with a preview of the message that was reacted on.
     -->
+    <string name="emoji_reaction_notification_body_group_more_persons">%1$s a %2$d ďalších ľudí reagovalo na: %3$s</string>
     <!-- Placeholder %1$s will be replaced with the message body of the text message that was reacted on. -->
+    <string name="emoji_reaction_notification_preview_text">“%1$s”</string>
+    <string name="emoji_reaction_notification_preview_image">Obrázok</string>
     <!-- Placeholder %1$s will be replaced with the caption text of the image message that was reacted on. -->
+    <string name="emoji_reaction_notification_preview_image_caption">“%1$s”</string>
+    <string name="emoji_reaction_notification_preview_video">Video</string>
     <!-- Placeholder %1$s will be replaced with the caption text of the video message that was reacted on. -->
+    <string name="emoji_reaction_notification_preview_video_caption">“%1$s”</string>
     <!-- Placeholder %1$s will be replaced with the duration of the audio message that was reacted on. -->
+    <string name="emoji_reaction_notification_preview_audio">Zvuk (%1$s)</string>
     <!-- Placeholder %1$s will be replaced with the caption text of the audio message that was reacted on. -->
+    <string name="emoji_reaction_notification_preview_audio_caption">Zvuk „%1$s“</string>
     <!-- Placeholder %1$s will be replaced with the duration of the voice message that was reacted on. -->
+    <string name="emoji_reaction_notification_preview_voice_message">Hlasová správa (%1$s)</string>
     <!-- Placeholder %1$s will be replaced with the caption or filename of the file message that was reacted on. -->
+    <string name="emoji_reaction_notification_preview_file">Súbor „%1$s“</string>
+    <string name="emoji_reaction_notification_preview_poll">Anketa</string>
     <!-- Placeholder %1$s will be replaced with the poll's name of the poll message that was reacted on. -->
+    <string name="emoji_reaction_notification_preview_poll_named">Anketa „%1$s“</string>
+    <string name="emoji_reaction_notification_preview_location">Poloha</string>
     <!-- Placeholder %1$s will be replaced with the POI name of the location message that was reacted on. -->
+    <string name="emoji_reaction_notification_preview_location_named">Poloha „%1$s“</string>
+    <string name="emoji_reaction_notification_preview_contact">Kontakt</string>
     <!-- Placeholder %1$s will be replaced with the contact name of the contact message that was reacted on. -->
+    <string name="emoji_reaction_notification_preview_contact_named">Kontakt „%1$s“</string>
+    <string name="prefs_title_emoji_reaction_notifications">Notifikácie o reakciách prostredníctvom emodži</string>
+    <string name="prefs_title_emoji_reaction_contact_notifications">V konverzaciách</string>
+    <string name="prefs_description_emoji_reaction_contact_notifications">Nechajte si zasielať upozornenia na reakcie pomocou emodži na vaše správy v individuálnych konverzáciách</string>
+    <string name="prefs_title_emoji_reaction_group_notifications">V skupinových konverzáciách</string>
+    <string name="prefs_description_emoji_reaction_group_notifications">Nechajte si zasielať upozornenia na reakcie pomocou emodži na vaše správy v skupinových konverzáciách</string>
+    <string name="group_spam_banner_message">Táto skupina pochádza od neznámeho používateľa</string>
+    <string name="group_spam_banner_button_not_spam">Nie je to spam</string>
+    <string name="group_spam_banner_button_report_spam">Nahlásiť spam</string>
     <!-- Placeholder 1 holds the display name of a group conversation -->
+    <string name="group_spam_report_dialog_title_named">Nahlásiť %1$s</string>
+    <string name="group_spam_report_dialog_title">Nahlásiť skupinu</string>
+    <string name="group_spam_report_dialog_message">ID tejto skupiny, počet členov, ako aj ID a prezývka zakladateľa skupiny budú spolu s vaším ID odoslané spoločnosti Threema. Obsah správ ani žiadne ďalšie osobné údaje nebudú zdieľané a nikto zo skupiny o tom nebude informovaný.</string>
+    <string name="group_spam_report_dialog_also_block_and_delete">Tiež zablokovať tvorcu a vymazať konverzáciu</string>
+    <string name="group_spam_report_dialog_cancel">Zrušiť</string>
+    <string name="group_spam_report_dialog_report">Nahlásiť</string>
     <!-- This is shown in a loading indicator dialog while a spam group is being reported -->
+    <string name="reporting_group_in_progress">Nahlasovanie skupiny</string>
     <plurals name="contacts_counter_label">
         <item quantity="one">%d kontakt</item>
         <item quantity="few">%d kontakty</item>
@@ -1863,6 +1907,12 @@ Vykonajte prosím zálohú vašich údajov vhodnou metódou.</string>
         <item quantity="many">%d nových správ</item>
         <item quantity="other">%d nových správ</item>
     </plurals>
+    <plurals name="new_emoji_reactions">
+        <item quantity="one">%d nová reakcia</item>
+        <item quantity="few">%d nové reakcie</item>
+        <item quantity="many">%d nových reakcií</item>
+        <item quantity="other">%d nových reakcií</item>
+    </plurals>
     <plurals name="unread_messages">
         <item quantity="one">%d neprečítaná správa</item>
         <item quantity="few">%d neprečítané správy</item>

+ 6 - 0
app/src/main/res/values-tr/strings.xml

@@ -1555,7 +1555,9 @@ sunucularımıza güvenli bir şekilde iletildi. Kişisel anahtar hiçbir zaman
     <!-- ${app_name_short} is a placeholder for the app's name, e.g. "Threema". It must be left as-is and not translated. -->
     <string name="problemsolver_explain_app_battery_usgae_optimized">Uygulamanın, ${app_name_short} Push\'un çalışması için gerekli olan sunucularla kalıcı bir bağlantı kurmasına izin verilmez. Uygulama arka plandayken yeni mesajlardan haberdar olmazsınız. Bunu düzeltmek için \"Uygulama pil kullanımı\" seçeneğine dokunun ve \"Kısıtlanmamış\" seçeneğini seçin.</string>
     <!-- Title of warning message that informs the user that the version of Android they are using will soon no longer be supported. -->
+    <string name="problemsolver_title_android_version_deprecated">Bu Android sürümü yakında artık desteklenmeyecek</string>
     <!-- Details of warning message that informs the user that the version of Android they are using will soon no longer be supported. ${app_name} is a placeholder that should be kept as-is and not translated. -->
+    <string name="problemsolver_explain_android_version_deprecated">Artık yazılım güncellemesi almayan bir Android cihaz kullanıyorsunuz. Güvenlik nedenleriyle, bu Android sürümü kısa süre içinde ${app_name} tarafından desteklenmeyecektir.</string>
     <string name="problemsolver_to_settings">Ayarlara</string>
     <!-- Label on button to dismiss/hide a warning -->
     <string name="problemsolver_dismiss">Reddet</string>
@@ -1886,6 +1888,10 @@ Nasıl Çalışır?</string>
         <item quantity="one">%d yeni mesaj</item>
         <item quantity="other">%d yeni mesaj</item>
     </plurals>
+    <plurals name="new_emoji_reactions">
+        <item quantity="one">%d yeni tepki</item>
+        <item quantity="other">%d yeni tepkiler</item>
+    </plurals>
     <plurals name="unread_messages">
         <item quantity="one">%d okunmamış Mesaj</item>
         <item quantity="other">%d okunmamış Mesaj</item>

+ 5 - 3
app/src/service_type_specific/google_services_based/java/ch/threema/app/services/VoiceActionService.java

@@ -43,6 +43,8 @@ public class VoiceActionService extends SearchActionVerificationClientService {
 
     private static final String CHANNEL_ID_GOOGLE_ASSISTANT = "Voice_Actions";
 
+    private static final int CONNECTION_LINGER_MS = 5000;
+
     private static final int FG_SERVICE_TYPE =
         Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE
             ? FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING
@@ -121,14 +123,14 @@ public class VoiceActionService extends SearchActionVerificationClientService {
             @Override
             public void onError(String errorMessage) {
                 logger.debug("Error sending audio message: {}", errorMessage);
-                lifetimeService.releaseConnectionLinger(TAG, PollingHelper.CONNECTION_LINGER);
+                lifetimeService.releaseConnectionLinger(TAG, CONNECTION_LINGER_MS);
             }
 
             @Override
             public void onCompleted() {
                 logger.debug("Audio message sent");
                 messageService.markConversationAsRead(messageReceiver, notificationService);
-                lifetimeService.releaseConnectionLinger(TAG, PollingHelper.CONNECTION_LINGER);
+                lifetimeService.releaseConnectionLinger(TAG, CONNECTION_LINGER_MS);
             }
         });
         return true;
@@ -158,7 +160,7 @@ public class VoiceActionService extends SearchActionVerificationClientService {
                             logger.error("Exception", e);
                         }
 
-                        lifetimeService.releaseConnectionLinger(TAG, PollingHelper.CONNECTION_LINGER);
+                        lifetimeService.releaseConnectionLinger(TAG, CONNECTION_LINGER_MS);
                     }
                 }
             }

+ 12 - 0
app/src/test/java/ch/threema/app/errorreporting/ErrorRecordStoreImplTest.kt

@@ -45,6 +45,7 @@ class ErrorRecordStoreImplTest {
             recordsDirectory = recordsDirectory,
             timeProvider = TestTimeProvider(1_762_270_272_000L),
             uuidGenerator = uuidGenerator,
+            currentAppVersionCode = 1234,
         )
 
         errorRecordStore.storeFatalError(createMockException())
@@ -63,6 +64,7 @@ class ErrorRecordStoreImplTest {
             recordsDirectory = recordsDirectory,
             timeProvider = TestTimeProvider(1_762_270_272_000L),
             uuidGenerator = uuidGenerator,
+            currentAppVersionCode = 1234,
         )
 
         errorRecordStore.storeHandledError("This is a %s", listOf("test"), null)
@@ -83,6 +85,7 @@ class ErrorRecordStoreImplTest {
             recordsDirectory = recordsDirectory,
             timeProvider = TestTimeProvider(1_762_270_272_000L),
             uuidGenerator = uuidGenerator,
+            currentAppVersionCode = 1234,
         )
         val file = File("/some/file.txt")
 
@@ -102,6 +105,7 @@ class ErrorRecordStoreImplTest {
             recordsDirectory = recordsDirectory,
             timeProvider = TestTimeProvider(),
             uuidGenerator = uuidGenerator,
+            currentAppVersionCode = 1234,
         )
         assertEquals(emptySet(), errorRecordStore.getErrorTypeIdsFromPendingRecords())
 
@@ -119,6 +123,7 @@ class ErrorRecordStoreImplTest {
             recordsDirectory = recordsDirectory,
             timeProvider = timeProvider,
             uuidGenerator = uuidGenerator,
+            currentAppVersionCode = 1234,
         )
         errorRecordStore.storeFatalError(createMockException())
         assertTrue(errorRecordStore.getConfirmedRecords().toList().isEmpty())
@@ -172,6 +177,7 @@ class ErrorRecordStoreImplTest {
                     ),
                 ),
                 createdAt = timeProvider.get(),
+                versionCode = 1234,
             ),
             errorRecord,
         )
@@ -188,6 +194,7 @@ class ErrorRecordStoreImplTest {
             recordsDirectory = recordsDirectory,
             timeProvider = TestTimeProvider(),
             uuidGenerator = uuidGenerator,
+            currentAppVersionCode = 1234,
         )
 
         val errorRecord = errorRecordStore.getConfirmedRecords().single()
@@ -233,6 +240,7 @@ class ErrorRecordStoreImplTest {
                     ),
                 ),
                 createdAt = Instant.ofEpochMilli(1762270272000),
+                versionCode = 1234,
             ),
             errorRecord,
         )
@@ -247,6 +255,7 @@ class ErrorRecordStoreImplTest {
             recordsDirectory = recordsDirectory,
             timeProvider = TestTimeProvider(),
             uuidGenerator = uuidGenerator,
+            currentAppVersionCode = 1234,
         )
 
         val errorRecord = errorRecordStore.getConfirmedRecords().single()
@@ -259,6 +268,7 @@ class ErrorRecordStoreImplTest {
                     parameters = listOf("test"),
                 ),
                 createdAt = Instant.ofEpochMilli(1762270272000),
+                versionCode = 1234,
             ),
             errorRecord,
         )
@@ -270,6 +280,7 @@ class ErrorRecordStoreImplTest {
             recordsDirectory = recordsDirectory,
             timeProvider = TestTimeProvider(),
             uuidGenerator = uuidGenerator,
+            currentAppVersionCode = 1234,
         )
         errorRecordStore.storeFatalError(createMockException())
         errorRecordStore.confirmPendingRecords()
@@ -291,6 +302,7 @@ class ErrorRecordStoreImplTest {
             recordsDirectory = recordsDirectory,
             timeProvider = TestTimeProvider(),
             uuidGenerator = uuidGenerator,
+            currentAppVersionCode = 1234,
         )
 
         errorRecordStore.deleteConfirmedRecord(uuidFromString(ERROR_RECORD_UUID))

+ 2 - 0
app/src/test/java/ch/threema/app/errorreporting/ErrorReportDetailsProviderTest.kt

@@ -98,6 +98,7 @@ class ErrorReportDetailsProviderTest {
                 ),
             ),
             createdAt = Instant.ofEpochMilli(1762270272000),
+            versionCode = 1234,
         )
         private val nonFatalErrorRecord = ErrorRecord(
             id = UUID.fromString(ERROR_RECORD_UUID2),
@@ -107,6 +108,7 @@ class ErrorReportDetailsProviderTest {
                 parameters = listOf("test"),
             ),
             createdAt = Instant.ofEpochMilli(1762270272000),
+            versionCode = 1234,
         )
     }
 }

+ 3 - 0
app/src/test/java/ch/threema/app/errorreporting/SentryServiceTest.kt

@@ -119,6 +119,7 @@ class SentryServiceTest {
                     ),
                 ),
                 createdAt = timeProvider.get() - 10.minutes,
+                versionCode = 1234,
             ),
         )
 
@@ -140,6 +141,7 @@ class SentryServiceTest {
                     parameters = listOf("test"),
                 ),
                 createdAt = timeProvider.get() - 10.minutes,
+                versionCode = 1234,
             ),
         )
 
@@ -180,6 +182,7 @@ class SentryServiceTest {
                     ),
                 ),
                 createdAt = timeProvider.get() - 10.minutes,
+                versionCode = 1234,
             ),
         )
 

+ 4 - 6
app/src/test/java/ch/threema/app/notifications/CallNotificationManagerTest.kt

@@ -3,11 +3,9 @@ package ch.threema.app.notifications
 import android.app.NotificationChannel
 import androidx.core.app.NotificationManagerCompat
 import ch.threema.android.DeviceInfo
-import ch.threema.app.utils.ConfigUtils
 import io.mockk.every
 import io.mockk.mockk
 import io.mockk.mockkStatic
-import io.mockk.unmockkObject
 import io.mockk.unmockkStatic
 import kotlin.test.Test
 import kotlin.test.assertIs
@@ -22,11 +20,11 @@ class CallNotificationManagerTest {
 
         val callNotificationManager = CallNotificationManagerImpl(
             appContext = mockk(),
+            notificationManagerCompat = notificationManagerMock,
             notificationPreferenceService = mockk(),
             preferenceService = mockk(),
             contactService = mockk(),
             getPersonUseCase = mockk(),
-            notificationManager = notificationManagerMock,
         )
 
         val result = callNotificationManager.showIncomingCallNotification(
@@ -50,11 +48,11 @@ class CallNotificationManagerTest {
 
         val callNotificationManager = CallNotificationManagerImpl(
             appContext = mockk(),
+            notificationManagerCompat = notificationManagerMock,
             notificationPreferenceService = mockk(),
             preferenceService = mockk(),
             contactService = mockk(),
             getPersonUseCase = mockk(),
-            notificationManager = notificationManagerMock,
         )
 
         val result = callNotificationManager.showIncomingCallNotification(
@@ -84,11 +82,11 @@ class CallNotificationManagerTest {
         }
         val callNotificationManager = CallNotificationManagerImpl(
             appContext = mockk(),
+            notificationManagerCompat = notificationManagerMock,
             notificationPreferenceService = mockk(),
             preferenceService = mockk(),
             contactService = mockk(),
             getPersonUseCase = mockk(),
-            notificationManager = notificationManagerMock,
         )
 
         val result = callNotificationManager.showIncomingCallNotification(
@@ -99,6 +97,6 @@ class CallNotificationManagerTest {
         )
         assertIs<CallNotificationManager.IncomingCallNotificationResult.IncomingCallNotificationsDisabled>(result)
 
-        unmockkObject(ConfigUtils::class)
+        unmockkStatic(DeviceInfo::class)
     }
 }

+ 4 - 0
app/src/test/java/ch/threema/app/usecases/GetDebugMetaDataUseCaseTest.kt

@@ -62,6 +62,7 @@ class GetDebugMetaDataUseCaseTest : AutoCloseKoinTest() {
             },
             preferenceService = mockk {
                 every { mustUseThreemaPush() } returns true
+                every { isContactSyncEnabled() } returns true
             },
             timeProvider = TestTimeProvider(utcDate(2026, 4, 13)),
         )
@@ -86,6 +87,7 @@ class GetDebugMetaDataUseCaseTest : AutoCloseKoinTest() {
             uses passphrase:	false
             uses multi device:	true
             uses threema push:	true
+            uses contact sync:	true
 
             # restrictions
             mdm source:	m
@@ -126,6 +128,7 @@ class GetDebugMetaDataUseCaseTest : AutoCloseKoinTest() {
             },
             preferenceService = mockk {
                 every { mustUseThreemaPush() } returns false
+                every { isContactSyncEnabled() } returns false
             },
             timeProvider = TestTimeProvider(utcDate(2026, 4, 13)),
         )
@@ -149,6 +152,7 @@ class GetDebugMetaDataUseCaseTest : AutoCloseKoinTest() {
             uses passphrase:	null
             uses multi device:	null
             uses threema push:	false
+            uses contact sync:	false
 
             # app version history
         """.trimIndent().trim()

+ 9 - 7
app/src/test/java/ch/threema/data/ContactModelTest.kt

@@ -4,6 +4,7 @@ import ch.threema.app.multidevice.MultiDeviceManager
 import ch.threema.app.tasks.ReflectContactSyncUpdateTask
 import ch.threema.common.emptyByteArray
 import ch.threema.common.plus
+import ch.threema.common.stateFlowOf
 import ch.threema.data.datatypes.AndroidContactLookupInfo
 import ch.threema.data.datatypes.AvailabilityStatus
 import ch.threema.data.datatypes.ConversationCategory
@@ -20,7 +21,9 @@ import ch.threema.domain.models.ReadReceiptPolicy
 import ch.threema.domain.models.TypingIndicatorPolicy
 import ch.threema.domain.models.VerificationLevel
 import ch.threema.domain.models.WorkVerificationLevel
-import ch.threema.domain.taskmanager.QueueSendCompleteListener
+import ch.threema.domain.taskmanager.LeaderState
+import ch.threema.domain.taskmanager.QueueSendCompleteState
+import ch.threema.domain.taskmanager.ReflectionQueueDryState
 import ch.threema.domain.taskmanager.Task
 import ch.threema.domain.taskmanager.TaskCodec
 import ch.threema.domain.taskmanager.TaskManager
@@ -41,6 +44,7 @@ import kotlin.test.fail
 import kotlin.time.Duration.Companion.days
 import kotlinx.coroutines.CompletableDeferred
 import kotlinx.coroutines.Deferred
+import kotlinx.coroutines.flow.StateFlow
 import testdata.TestData
 
 class ContactModelTest {
@@ -58,13 +62,11 @@ class ContactModelTest {
 
         override fun hasPendingTasks(): Boolean = scheduledTasks.isNotEmpty()
 
-        override fun addQueueSendCompleteListener(listener: QueueSendCompleteListener) {
-            // Nothing to do
-        }
+        override fun watchQueueSendComplete(): StateFlow<QueueSendCompleteState> = stateFlowOf(QueueSendCompleteState.PENDING)
 
-        override fun removeQueueSendCompleteListener(listener: QueueSendCompleteListener) {
-            // Nothing to do
-        }
+        override fun watchReflectionQueueDry(): StateFlow<ReflectionQueueDryState> = stateFlowOf(ReflectionQueueDryState.PENDING)
+
+        override fun watchLeaderState(): StateFlow<LeaderState> = stateFlowOf(LeaderState.NOT_LEADER)
     }
     private val identityProvider = TestIdentityProvider(TestData.Identities.ME)
 

+ 9 - 7
app/src/test/java/ch/threema/data/GroupModelTest.kt

@@ -4,6 +4,7 @@ import ch.threema.app.eventbus.EventBus
 import ch.threema.app.eventbus.GlobalEventBuses
 import ch.threema.app.eventbus.events.GroupEvent
 import ch.threema.app.multidevice.MultiDeviceManager
+import ch.threema.common.stateFlowOf
 import ch.threema.data.datatypes.ConversationCategory
 import ch.threema.data.datatypes.ConversationSpamReportingState
 import ch.threema.data.datatypes.ConversationVisibility
@@ -14,7 +15,9 @@ import ch.threema.data.models.GroupModel
 import ch.threema.data.models.GroupModelData
 import ch.threema.data.storage.DatabaseBackend
 import ch.threema.domain.models.UserState
-import ch.threema.domain.taskmanager.QueueSendCompleteListener
+import ch.threema.domain.taskmanager.LeaderState
+import ch.threema.domain.taskmanager.QueueSendCompleteState
+import ch.threema.domain.taskmanager.ReflectionQueueDryState
 import ch.threema.domain.taskmanager.Task
 import ch.threema.domain.taskmanager.TaskCodec
 import ch.threema.domain.taskmanager.TaskManager
@@ -34,6 +37,7 @@ import kotlin.test.assertEquals
 import kotlin.test.assertFailsWith
 import kotlinx.coroutines.CompletableDeferred
 import kotlinx.coroutines.Deferred
+import kotlinx.coroutines.flow.StateFlow
 
 class GroupModelTest {
     private val databaseBackendMock = mockk<DatabaseBackend> {
@@ -56,13 +60,11 @@ class GroupModelTest {
 
         override fun hasPendingTasks(): Boolean = scheduledTasks.isNotEmpty()
 
-        override fun addQueueSendCompleteListener(listener: QueueSendCompleteListener) {
-            // Nothing to do
-        }
+        override fun watchQueueSendComplete(): StateFlow<QueueSendCompleteState> = stateFlowOf(QueueSendCompleteState.PENDING)
 
-        override fun removeQueueSendCompleteListener(listener: QueueSendCompleteListener) {
-            // Nothing to do
-        }
+        override fun watchReflectionQueueDry(): StateFlow<ReflectionQueueDryState> = stateFlowOf(ReflectionQueueDryState.PENDING)
+
+        override fun watchLeaderState(): StateFlow<LeaderState> = stateFlowOf(LeaderState.NOT_LEADER)
     }
     private val identityProvider = TestIdentityProvider(Identity("TESTTEST"))
 

+ 1 - 1
app/src/test/resources/error-reporting/fatal-error-record-v2.json

@@ -1 +1 @@
-{"id":"d3bc6807-c4c7-47c2-af55-aa929d86fd09","exceptions":[{"type":"IllegalStateException","message":"This is the cause","packageName":"java.lang","stackTrace":[{"fileName":"Cause.kt","className":"com.example.Cause","lineNumber":1337,"methodName":"causeTheCause","isNative":false}]},{"type":"RuntimeException","message":"This is a test","packageName":"java.lang","stackTrace":[{"fileName":"SomeOtherClass.kt","className":"com.example.SomeOtherClass","lineNumber":42,"methodName":"fooBar","isNative":true},{"fileName":"MyClass.kt","className":"MyClass","lineNumber":67,"methodName":"testStuff","isNative":false}]}],"createdAt":1762270272000}
+{"id":"d3bc6807-c4c7-47c2-af55-aa929d86fd09","exceptions":[{"type":"IllegalStateException","message":"This is the cause","packageName":"java.lang","stackTrace":[{"fileName":"Cause.kt","className":"com.example.Cause","lineNumber":1337,"methodName":"causeTheCause","isNative":false}]},{"type":"RuntimeException","message":"This is a test","packageName":"java.lang","stackTrace":[{"fileName":"SomeOtherClass.kt","className":"com.example.SomeOtherClass","lineNumber":42,"methodName":"fooBar","isNative":true},{"fileName":"MyClass.kt","className":"MyClass","lineNumber":67,"methodName":"testStuff","isNative":false}]}],"createdAt":1762270272000,"versionCode":1234}

+ 1 - 1
app/src/test/resources/error-reporting/non-fatal-error-record-v2.json

@@ -1 +1 @@
-{"id":"d3bc6807-c4c7-47c2-af55-aa929d86fd09","level":"ERROR","message":{"message":"This is a %s","parameters":["test"]},"createdAt":1762270272000}
+{"id":"d3bc6807-c4c7-47c2-af55-aa929d86fd09","level":"ERROR","message":{"message":"This is a %s","parameters":["test"]},"createdAt":1762270272000,"versionCode":1234}

+ 1 - 1
app/src/test/resources/error-reporting/non-fatal-error-record-with-attachment-v2.json

@@ -1 +1 @@
-{"id":"d3bc6807-c4c7-47c2-af55-aa929d86fd09","level":"ERROR","message":{"message":"here be attachments","parameters":[]},"attachments":[{"file":"/some/file.txt","mimeType":"text/plain"}],"createdAt":1762270272000}
+{"id":"d3bc6807-c4c7-47c2-af55-aa929d86fd09","level":"ERROR","message":{"message":"here be attachments","parameters":[]},"attachments":[{"file":"/some/file.txt","mimeType":"text/plain"}],"createdAt":1762270272000,"versionCode":1234}

+ 10 - 10
domain/src/main/java/ch/threema/domain/protocol/connection/BaseServerConnection.kt

@@ -1,6 +1,7 @@
 package ch.threema.domain.protocol.connection
 
 import androidx.annotation.WorkerThread
+import ch.threema.common.await
 import ch.threema.domain.protocol.ServerAddressProvider
 import ch.threema.domain.protocol.Version
 import ch.threema.domain.protocol.connection.csp.DeviceCookieManager
@@ -11,7 +12,7 @@ import ch.threema.domain.protocol.connection.util.MainConnectionController
 import ch.threema.domain.protocol.csp.ProtocolDefines
 import ch.threema.domain.stores.IdentityStore
 import ch.threema.domain.taskmanager.IncomingMessageProcessor
-import ch.threema.domain.taskmanager.QueueSendCompleteListener
+import ch.threema.domain.taskmanager.QueueSendCompleteState
 import ch.threema.domain.taskmanager.TaskManager
 import java.io.IOException
 import java.net.SocketException
@@ -120,7 +121,7 @@ internal abstract class BaseServerConnection(
             awaitAppReady()
             while (canConnect) {
                 var monitorCloseEventJob: Job? = null
-                var queueSendCompleteListener: QueueSendCompleteListener? = null
+                var queueSendCompleteJob: Job? = null
                 try {
                     setup()
 
@@ -144,16 +145,15 @@ internal abstract class BaseServerConnection(
                         break
                     }
 
-                    // We must keep the CPU awake until we have processed all incoming messages
-                    // to avoid missing messages in deeper sleep states.
-                    queueSendCompleteListener = QueueSendCompleteListener {
+                    // We must keep the CPU awake until we have processed all incoming messages to avoid missing messages in deeper sleep states.
+                    // The state is set to DRY by the task manager once the queue send complete message has been processed. If the connection is
+                    // lost, the state is reset and this job is cancelled, in which case the connection lock is released when the connection
+                    // cycle ends.
+                    queueSendCompleteJob = launch {
+                        dependencies.taskManager.watchQueueSendComplete().await(QueueSendCompleteState.DRY)
                         logger.info("CSP queue was processed, releasing connection lock")
                         connectionLock?.release()
                     }
-                    // The listener must be registered before processing io has been started.
-                    // Otherwise the queue send complete event could already have been triggered
-                    // before the listener was added.
-                    dependencies.taskManager.addQueueSendCompleteListener(queueSendCompleteListener)
 
                     // Handle IO until the connection dies
                     ioJob = launch { processIo() }
@@ -200,7 +200,7 @@ internal abstract class BaseServerConnection(
 
                 controller.connectionClosed.complete(Unit)
 
-                queueSendCompleteListener?.let { dependencies.taskManager.removeQueueSendCompleteListener(it) }
+                queueSendCompleteJob?.cancel()
 
                 if (canConnect) {
                     prepareReconnect()

+ 4 - 1
domain/src/main/java/ch/threema/domain/protocol/connection/layer/EndToEndLayer.kt

@@ -48,7 +48,10 @@ internal class EndToEndLayer(
 
             connectionController.cspAuthenticated.await()
             // Start task manager when csp has been authenticated
-            taskManager.startRunningTasks(this@EndToEndLayer, incomingMessageProcessor)
+            taskManager.startRunningTasks(
+                this@EndToEndLayer,
+                incomingMessageProcessor,
+            )
 
             // Forward inbound messages to task manager after it has been started
             inboundMessageChannel.receiveAsFlow().collect { (inboundMessage, lock) ->

+ 10 - 3
domain/src/main/java/ch/threema/domain/protocol/connection/layer/MonitoringLayer.kt

@@ -109,13 +109,19 @@ internal class MonitoringLayer(
 
     private fun handleInboundD2mMessage(message: InboundD2mMessage) {
         when (message) {
-            is InboundD2mMessage.RolePromotedToLeader -> handlePromotedToLeader()
-            is InboundD2mMessage.ReflectionQueueDry -> mdController.reflectionQueueDry.complete(Unit)
+            is InboundD2mMessage.RolePromotedToLeader -> handlePromotedToLeader(message)
+            is InboundD2mMessage.ReflectionQueueDry -> handleReflectionQueueDry(message)
             else -> inbound.send(message)
         }
     }
 
-    private fun handlePromotedToLeader() {
+    private fun handleReflectionQueueDry(message: InboundD2mMessage.ReflectionQueueDry) {
+        logger.info("Handle ReflectionQueueDry")
+        mdController.reflectionQueueDry.complete(Unit)
+        inbound.send(message)
+    }
+
+    private fun handlePromotedToLeader(message: InboundD2mMessage.RolePromotedToLeader) {
         logger.info("Handle RolePromotedToLeader")
         if (!mdController.reflectionQueueDry.isCompleted || mdController.reflectionQueueDry.isCancelled) {
             throw D2mProtocolException("RolePromotedToLeader was received before ReflectionQueueDry")
@@ -132,6 +138,7 @@ internal class MonitoringLayer(
                 ),
             )
         }
+        inbound.send(message)
     }
 
     private fun handleInboundCspContainer(message: CspContainer) {

+ 4 - 2
domain/src/main/java/ch/threema/domain/taskmanager/IncomingCspMessageTask.kt

@@ -5,12 +5,14 @@ import ch.threema.domain.protocol.connection.PayloadProcessingException
 import ch.threema.domain.protocol.connection.data.CspMessage
 import ch.threema.domain.protocol.csp.ProtocolDefines
 import ch.threema.domain.protocol.csp.coders.MessageBox
+import kotlinx.coroutines.flow.MutableStateFlow
 
 private val logger = getThreemaLogger("IncomingCspMessageTask")
 
 class IncomingCspMessageTask(
     private val message: CspMessage,
     private val incomingMessageProcessor: IncomingMessageProcessor,
+    private val queueSendCompleteState: MutableStateFlow<QueueSendCompleteState>,
 ) : ActiveTask<Unit> {
     override val type: String = "IncomingCspMessageTask"
 
@@ -68,8 +70,8 @@ class IncomingCspMessageTask(
     }
 
     private fun processQueueSendComplete() {
-        // Note that queue send complete messages are already processed in the task manager
-        logger.warn("Processed queue send complete inside incoming csp message task")
+        logger.info("Incoming message queue was flushed; setting the queue send complete state to DRY")
+        queueSendCompleteState.value = QueueSendCompleteState.DRY
     }
 
     private fun processDeviceCookieChangeIndication() {

+ 16 - 0
domain/src/main/java/ch/threema/domain/taskmanager/IncomingD2mMessageTask.kt

@@ -3,12 +3,15 @@ package ch.threema.domain.taskmanager
 import ch.threema.base.utils.getThreemaLogger
 import ch.threema.domain.protocol.D2mPayloadType
 import ch.threema.domain.protocol.connection.data.InboundD2mMessage
+import kotlinx.coroutines.flow.MutableStateFlow
 
 private val logger = getThreemaLogger("IncomingD2mMessageTask")
 
 class IncomingD2mMessageTask(
     private val message: InboundD2mMessage,
     private val incomingMessageProcessor: IncomingMessageProcessor,
+    private val reflectionQueueDryState: MutableStateFlow<ReflectionQueueDryState>,
+    private val leaderState: MutableStateFlow<LeaderState>,
 ) : ActiveTask<Unit> {
     override val type: String = "IncomingD2mMessageTask"
 
@@ -17,6 +20,9 @@ class IncomingD2mMessageTask(
             D2mPayloadType.REFLECTED ->
                 handleReflected(message as InboundD2mMessage.Reflected, handle)
 
+            D2mPayloadType.REFLECTION_QUEUE_DRY -> handleReflectionQueueDry()
+            D2mPayloadType.ROLE_PROMOTED_TO_LEADER -> handlePromotedToLeader()
+
             else -> logger.warn(
                 "Unexpected d2m message of type 0x{} received",
                 message.payloadType.toHexString(),
@@ -30,4 +36,14 @@ class IncomingD2mMessageTask(
     ) {
         incomingMessageProcessor.processIncomingD2mMessage(message, handle)
     }
+
+    private fun handleReflectionQueueDry() {
+        logger.info("Reflection queue was flushed; setting the reflection queue dry state to DRY")
+        reflectionQueueDryState.value = ReflectionQueueDryState.DRY
+    }
+
+    private fun handlePromotedToLeader() {
+        logger.info("Device was promoted to leader; setting the leader state to LEADER")
+        leaderState.value = LeaderState.LEADER
+    }
 }

+ 7 - 1
domain/src/main/java/ch/threema/domain/taskmanager/IncomingMessageTaskQueue.kt

@@ -6,11 +6,15 @@ import ch.threema.domain.protocol.connection.data.InboundD2mMessage
 import ch.threema.domain.protocol.connection.data.InboundMessage
 import kotlinx.coroutines.CancellationException
 import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.flow.MutableStateFlow
 
 private val logger = getThreemaLogger("IncomingMessageTaskQueue")
 
 internal class IncomingMessageTaskQueue(
     private val incomingMessageProcessor: IncomingMessageProcessor,
+    private val queueSendCompleteState: MutableStateFlow<QueueSendCompleteState>,
+    private val reflectionQueueDryState: MutableStateFlow<ReflectionQueueDryState>,
+    private val leaderState: MutableStateFlow<LeaderState>,
     private val getDebugString: Task<*, *>.() -> String,
 ) {
     /**
@@ -122,10 +126,12 @@ internal class IncomingMessageTaskQueue(
     ) : TaskQueue.TaskQueueElement {
         private val task by lazy {
             when (inboundMessage) {
-                is CspMessage -> IncomingCspMessageTask(inboundMessage, incomingMessageProcessor)
+                is CspMessage -> IncomingCspMessageTask(inboundMessage, incomingMessageProcessor, queueSendCompleteState)
                 is InboundD2mMessage -> IncomingD2mMessageTask(
                     inboundMessage,
                     incomingMessageProcessor,
+                    reflectionQueueDryState,
+                    leaderState,
                 )
             }
         }

+ 18 - 0
domain/src/main/java/ch/threema/domain/taskmanager/LeaderState.kt

@@ -0,0 +1,18 @@
+package ch.threema.domain.taskmanager
+
+/**
+ * The state of the leader role of this device in multi-device mode.
+ *
+ * Note: If multi-device is not active, there is no leader role, so the state remains NOT_LEADER.
+ */
+enum class LeaderState {
+    /**
+     * There is no connection, multi device is disabled, or the server has not promoted this device to leader on the current connection yet.
+     */
+    NOT_LEADER,
+
+    /**
+     * The server has promoted this device to leader on the current connection, which is still open.
+     */
+    LEADER,
+}

+ 0 - 12
domain/src/main/java/ch/threema/domain/taskmanager/QueueSendCompleteListener.java

@@ -1,12 +0,0 @@
-package ch.threema.domain.taskmanager;
-
-/**
- * Interface for objects that wish to be notified when the server has signalled that the message
- * queue has been flushed completely.
- *
- * Note: This implies that the D2M ReflectionQueueDry has also been processed because the CSP
- * queue will not be opened until the reflection process is complete.
- */
-public interface QueueSendCompleteListener {
-    void queueSendComplete();
-}

+ 16 - 0
domain/src/main/java/ch/threema/domain/taskmanager/QueueSendCompleteState.kt

@@ -0,0 +1,16 @@
+package ch.threema.domain.taskmanager
+
+/**
+ * The state of the message queue of the current connection.
+ */
+enum class QueueSendCompleteState {
+    /**
+     * There is no connection or the server has not sent the entire message queue of the current connection yet.
+     */
+    PENDING,
+
+    /**
+     * The server has sent the entire message queue of the current connection, which is still open.
+     */
+    DRY,
+}

+ 18 - 0
domain/src/main/java/ch/threema/domain/taskmanager/ReflectionQueueDryState.kt

@@ -0,0 +1,18 @@
+package ch.threema.domain.taskmanager
+
+/**
+ * The state of the reflection queue of the current connection.
+ *
+ * Note: If multi-device is not active, the reflection queue does not exist, so the state remains PENDING.
+ */
+enum class ReflectionQueueDryState {
+    /**
+     * There is no connection or the server has not sent the reflection queue dry message for the current connection yet.
+     */
+    PENDING,
+
+    /**
+     * The server has sent the reflection queue dry message for the current connection, which is still open.
+     */
+    DRY,
+}

+ 69 - 35
domain/src/main/java/ch/threema/domain/taskmanager/TaskManager.kt

@@ -14,6 +14,9 @@ import ch.threema.domain.protocol.csp.ProtocolDefines
 import kotlinx.coroutines.CompletableDeferred
 import kotlinx.coroutines.CoroutineScope
 import kotlinx.coroutines.Deferred
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
 import kotlinx.coroutines.launch
 
 private val logger = getThreemaLogger("TaskManager")
@@ -38,14 +41,35 @@ interface TaskManager {
     fun hasPendingTasks(): Boolean
 
     /**
-     * Add a queue send complete listener.
+     * Watch the state of the message queue of the current connection.
+     *
+     * The [QueueSendCompleteState.DRY] state is only reported while the connection is open, so reading it guarantees that the server has sent the
+     * entire message queue of an open connection. In case the connection is lost, this state is reset to PENDING.
+     *
+     * Note: In multi-device mode, the queue send complete message is only sent to the leader device, so on non-leader devices the state
+     * may remain PENDING while the connection is open.
+     */
+    fun watchQueueSendComplete(): StateFlow<QueueSendCompleteState>
+
+    /**
+     * Watch the state of the reflection queue of the current connection.
+     *
+     * The [ReflectionQueueDryState.DRY] state is only reported while the connection is open, so reading it guarantees that the server has sent the
+     * reflection queue dry message of an open connection. In case the connection is lost, this state is reset to PENDING.
+     *
+     * Note: The reflection queue only exists in multi-device mode, so if multi-device is not active, the state remains PENDING.
      */
-    fun addQueueSendCompleteListener(listener: QueueSendCompleteListener)
+    fun watchReflectionQueueDry(): StateFlow<ReflectionQueueDryState>
 
     /**
-     * Remove a queue send complete listener.
+     * Watch the leader state of this device.
+     *
+     * The [LeaderState.LEADER] state is only reported while the connection is open, so reading it guarantees that the server has promoted this device
+     * to leader on the open connection. In case the connection is lost, this state is reset to NOT_LEADER.
+     *
+     * Note: The leader role only exists in multi-device mode, so if multi-device is not active, the state remains NOT_LEADER.
      */
-    fun removeQueueSendCompleteListener(listener: QueueSendCompleteListener)
+    fun watchLeaderState(): StateFlow<LeaderState>
 }
 
 /**
@@ -83,7 +107,29 @@ internal class TaskManagerImpl(
     private val dispatchers: TaskManagerDispatchers,
     private val getDebugString: Task<*, *>.() -> String,
 ) : InternalTaskManager, TaskManager {
-    private val queueSendCompleteListeners: MutableSet<QueueSendCompleteListener> = mutableSetOf()
+    /**
+     * The state of the message queue of the current connection.
+     *
+     * It is set to [QueueSendCompleteState.DRY] by the incoming csp message task when the 'queue send complete message' of the current connection
+     * has been processed, and reset to [QueueSendCompleteState.PENDING] when a new connection is established or the connection ends.
+     */
+    private val queueSendCompleteState = MutableStateFlow(QueueSendCompleteState.PENDING)
+
+    /**
+     * The state of the reflection queue of the current connection.
+     *
+     * It is set to [ReflectionQueueDryState.DRY] when the server has sent the 'reflection queue dry message', and reset to
+     * [ReflectionQueueDryState.PENDING] when a new connection is established or the connection ends.
+     */
+    private val reflectionQueueDryState = MutableStateFlow(ReflectionQueueDryState.PENDING)
+
+    /**
+     * The state of the leader role of this device.
+     *
+     * It is set to [LeaderState.LEADER] by the incoming d2m message task when the 'role promoted to leader message' of the current connection has
+     * been processed, and reset to [LeaderState.NOT_LEADER] when a new connection is established or the connection ends.
+     */
+    private val leaderState = MutableStateFlow(LeaderState.NOT_LEADER)
 
     private var incomingMessageProcessor: IncomingMessageProcessor? = null
 
@@ -113,12 +159,24 @@ internal class TaskManagerImpl(
     ) {
         this.incomingMessageProcessor = incomingMessageProcessor
 
-        taskRunner.value.startTaskRunner(layer5Codec, incomingMessageProcessor)
+        taskRunner.value.startTaskRunner(
+            layer5Codec,
+            incomingMessageProcessor,
+            queueSendCompleteState,
+            reflectionQueueDryState,
+            leaderState,
+        )
     }
 
     override suspend fun pauseRunningTasks(closeReason: ServerSocketCloseReason) {
         if (taskRunner.isInitialized()) {
             taskRunner.value.stopTaskRunner(closeReason)
+            // The connection is gone, so the states of its queues and its leader role are not valid anymore. Note that stopTaskRunner waits
+            // for all in-flight tasks to finish, so this reset always happens after the last queue send complete message of this connection
+            // has been processed.
+            queueSendCompleteState.value = QueueSendCompleteState.PENDING
+            reflectionQueueDryState.value = ReflectionQueueDryState.PENDING
+            leaderState.value = LeaderState.NOT_LEADER
         }
     }
 
@@ -143,17 +201,11 @@ internal class TaskManagerImpl(
 
     override fun hasPendingTasks(): Boolean = taskQueue.hasPendingTasks()
 
-    override fun addQueueSendCompleteListener(listener: QueueSendCompleteListener) {
-        synchronized(queueSendCompleteListeners) {
-            queueSendCompleteListeners.add(listener)
-        }
-    }
+    override fun watchQueueSendComplete(): StateFlow<QueueSendCompleteState> = queueSendCompleteState.asStateFlow()
 
-    override fun removeQueueSendCompleteListener(listener: QueueSendCompleteListener) {
-        synchronized(queueSendCompleteListeners) {
-            queueSendCompleteListeners.remove(listener)
-        }
-    }
+    override fun watchReflectionQueueDry(): StateFlow<ReflectionQueueDryState> = reflectionQueueDryState.asStateFlow()
+
+    override fun watchLeaderState(): StateFlow<LeaderState> = leaderState.asStateFlow()
 
     override fun processInboundMessage(message: InboundMessage, lock: ConnectionLock) {
         when (message) {
@@ -198,10 +250,7 @@ internal class TaskManagerImpl(
 
             ProtocolDefines.PLTYPE_OUTGOING_MESSAGE_ACK -> schedule(message, lock)
             ProtocolDefines.PLTYPE_INCOMING_MESSAGE -> schedule(message, lock)
-            ProtocolDefines.PLTYPE_QUEUE_SEND_COMPLETE -> {
-                notifyQueueSendComplete()
-                lock.release()
-            }
+            ProtocolDefines.PLTYPE_QUEUE_SEND_COMPLETE -> schedule(message, lock)
             ProtocolDefines.PLTYPE_DEVICE_COOKIE_CHANGE_INDICATION -> {
                 processDeviceCookieChangeIndication()
                 lock.release()
@@ -230,21 +279,6 @@ internal class TaskManagerImpl(
         sendClearDeviceCookieChangeIndication()
     }
 
-    private fun notifyQueueSendComplete() {
-        synchronized(queueSendCompleteListeners) {
-            // Iterate over a copy of the set to prevent concurrent modification. This is necessary,
-            // because the queue complete listeners may remove themselves from the list inside
-            // 'queueSendComplete'.
-            queueSendCompleteListeners.toList().forEach {
-                try {
-                    it.queueSendComplete()
-                } catch (e: Exception) {
-                    logger.warn("Exception while invoking queue send complete listener", e)
-                }
-            }
-        }
-    }
-
     private fun sendClearDeviceCookieChangeIndication() {
         logger.debug("Clearing device cookie change indication")
         taskRunner.value.sendImmediately(

+ 10 - 1
domain/src/main/java/ch/threema/domain/taskmanager/TaskQueue.kt

@@ -6,6 +6,7 @@ import ch.threema.domain.protocol.connection.socket.ServerSocketCloseReason
 import kotlinx.coroutines.CompletableDeferred
 import kotlinx.coroutines.channels.BufferOverflow
 import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.flow.MutableStateFlow
 import kotlinx.coroutines.runBlocking
 
 internal class TaskQueue(
@@ -76,11 +77,19 @@ internal class TaskQueue(
      * Recreates the incoming message queue. This is needed when the server connection has been re-
      * established. Locally created tasks aren't affected by this.
      */
-    internal fun recreateIncomingMessageQueue(incomingMessageProcessor: IncomingMessageProcessor) {
+    internal fun recreateIncomingMessageQueue(
+        incomingMessageProcessor: IncomingMessageProcessor,
+        queueSendCompleteState: MutableStateFlow<QueueSendCompleteState>,
+        reflectionQueueDryState: MutableStateFlow<ReflectionQueueDryState>,
+        leaderState: MutableStateFlow<LeaderState>,
+    ) {
         dispatcherAsserters.executorDispatcher.assertDispatcherContext()
 
         incomingMessageQueue = IncomingMessageTaskQueue(
             incomingMessageProcessor = incomingMessageProcessor,
+            queueSendCompleteState = queueSendCompleteState,
+            reflectionQueueDryState = reflectionQueueDryState,
+            leaderState = leaderState,
             getDebugString = getDebugString,
         )
     }

+ 26 - 2
domain/src/main/java/ch/threema/domain/taskmanager/TaskRunner.kt

@@ -17,6 +17,7 @@ import kotlinx.coroutines.CoroutineScope
 import kotlinx.coroutines.Job
 import kotlinx.coroutines.awaitCancellation
 import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.MutableStateFlow
 import kotlinx.coroutines.isActive
 import kotlinx.coroutines.launch
 import kotlinx.coroutines.sync.Semaphore
@@ -152,10 +153,17 @@ internal class TaskRunner(
      * Start the task runner after the connection has been established.
      *
      * @param layer5Codec the current layer 5 codec for sending messages
+     * @param queueSendCompleteState the state of the queue of the current connection, which is set to DRY by the incoming csp message task
+     * when the queue send complete message has been processed
+     * @param reflectionQueueDryState the state of the reflection queue of the current connection
+     * @param leaderState the state of the leader role of the current connection
      */
     internal suspend fun startTaskRunner(
         layer5Codec: Layer5Codec,
         incomingMessageProcessor: IncomingMessageProcessor,
+        queueSendCompleteState: MutableStateFlow<QueueSendCompleteState>,
+        reflectionQueueDryState: MutableStateFlow<ReflectionQueueDryState>,
+        leaderState: MutableStateFlow<LeaderState>,
     ) {
         logger.info("Starting task runner")
 
@@ -180,13 +188,23 @@ internal class TaskRunner(
             logger.info("Old executor job already inactive")
         }
 
+        // All tasks of the previous connection have been stopped, so the states of the new connection have not been set yet.
+        queueSendCompleteState.value = QueueSendCompleteState.PENDING
+        reflectionQueueDryState.value = ReflectionQueueDryState.PENDING
+        leaderState.value = LeaderState.NOT_LEADER
+
         this.layer5Codec = layer5Codec
 
         // Clear incoming message queue to get rid of old unprocessed messages
         withContext(executorCoroutineContext) {
             logger.info("Flushing incoming message queues")
             // As the connection just has been initiated, we will again receive un-acked messages
-            taskQueue.recreateIncomingMessageQueue(incomingMessageProcessor)
+            taskQueue.recreateIncomingMessageQueue(
+                incomingMessageProcessor,
+                queueSendCompleteState,
+                reflectionQueueDryState,
+                leaderState,
+            )
         }
 
         // We handle the exceptions in invokeOnCompletion instead of the exception handler
@@ -234,7 +252,13 @@ internal class TaskRunner(
                         CoroutineScope(scheduleCoroutineContext).launch {
                             // To avoid a busy loop, we delay the restarting of the task runner a bit here
                             delay(10.seconds)
-                            startTaskRunner(layer5Codec, incomingMessageProcessor)
+                            startTaskRunner(
+                                layer5Codec,
+                                incomingMessageProcessor,
+                                queueSendCompleteState,
+                                reflectionQueueDryState,
+                                leaderState,
+                            )
                         }
                     }
                 }

+ 9 - 7
domain/src/test/java/ch/threema/domain/protocol/connection/CspConnectionTest.kt

@@ -1,5 +1,6 @@
 package ch.threema.domain.protocol.connection
 
+import ch.threema.common.stateFlowOf
 import ch.threema.domain.protocol.Version
 import ch.threema.domain.protocol.connection.csp.CspConnectionConfiguration
 import ch.threema.domain.protocol.connection.csp.CspConnectionImpl
@@ -21,7 +22,9 @@ import ch.threema.domain.protocol.csp.coders.MessageBox
 import ch.threema.domain.taskmanager.ActiveTaskCodec
 import ch.threema.domain.taskmanager.IncomingMessageProcessor
 import ch.threema.domain.taskmanager.InternalTaskManager
-import ch.threema.domain.taskmanager.QueueSendCompleteListener
+import ch.threema.domain.taskmanager.LeaderState
+import ch.threema.domain.taskmanager.QueueSendCompleteState
+import ch.threema.domain.taskmanager.ReflectionQueueDryState
 import ch.threema.domain.taskmanager.Task
 import ch.threema.domain.taskmanager.TaskArchiver
 import ch.threema.domain.taskmanager.TaskCodec
@@ -32,6 +35,7 @@ import io.mockk.mockk
 import kotlin.time.Duration
 import kotlinx.coroutines.CompletableDeferred
 import kotlinx.coroutines.Deferred
+import kotlinx.coroutines.flow.StateFlow
 
 internal class CspConnectionTest : ServerConnectionTest() {
     private val connectionLockProvider = object : ConnectionLockProvider {
@@ -69,13 +73,11 @@ internal class CspConnectionTest : ServerConnectionTest() {
 
             override fun hasPendingTasks(): Boolean = false
 
-            override fun addQueueSendCompleteListener(listener: QueueSendCompleteListener) {
-                // Nothing to do
-            }
+            override fun watchQueueSendComplete(): StateFlow<QueueSendCompleteState> = stateFlowOf(QueueSendCompleteState.PENDING)
 
-            override fun removeQueueSendCompleteListener(listener: QueueSendCompleteListener) {
-                // Nothing to do
-            }
+            override fun watchReflectionQueueDry(): StateFlow<ReflectionQueueDryState> = stateFlowOf(ReflectionQueueDryState.PENDING)
+
+            override fun watchLeaderState(): StateFlow<LeaderState> = stateFlowOf(LeaderState.NOT_LEADER)
         }
 
         val dependencyProvider = ServerConnectionDependencyProvider {

+ 9 - 7
domain/src/testFixtures/java/ch/threema/domain/helpers/ControlledTaskManager.kt

@@ -1,11 +1,15 @@
 package ch.threema.domain.helpers
 
-import ch.threema.domain.taskmanager.QueueSendCompleteListener
+import ch.threema.common.stateFlowOf
+import ch.threema.domain.taskmanager.LeaderState
+import ch.threema.domain.taskmanager.QueueSendCompleteState
+import ch.threema.domain.taskmanager.ReflectionQueueDryState
 import ch.threema.domain.taskmanager.Task
 import ch.threema.domain.taskmanager.TaskCodec
 import ch.threema.domain.taskmanager.TaskManager
 import kotlinx.coroutines.CompletableDeferred
 import kotlinx.coroutines.Deferred
+import kotlinx.coroutines.flow.StateFlow
 import kotlinx.coroutines.runBlocking
 
 class ControlledTaskManager(
@@ -32,11 +36,9 @@ class ControlledTaskManager(
 
     override fun hasPendingTasks() = false
 
-    override fun addQueueSendCompleteListener(listener: QueueSendCompleteListener) {
-        // Nothing to do
-    }
+    override fun watchQueueSendComplete(): StateFlow<QueueSendCompleteState> = stateFlowOf(QueueSendCompleteState.PENDING)
 
-    override fun removeQueueSendCompleteListener(listener: QueueSendCompleteListener) {
-        // Nothing to do
-    }
+    override fun watchReflectionQueueDry(): StateFlow<ReflectionQueueDryState> = stateFlowOf(ReflectionQueueDryState.PENDING)
+
+    override fun watchLeaderState(): StateFlow<LeaderState> = stateFlowOf(LeaderState.NOT_LEADER)
 }

+ 3 - 3
gradle/libs.versions.toml

@@ -18,8 +18,8 @@ androidx_lifecycle = "2.10.0" # TODO(ANDR-4869): Version 2.11.0 requires AGP 9.1
 androidx_lifecycleCompose = "2.10.0" # TODO(ANDR-4869): Should be updated together with androidx_lifecycle
 androidx_lifecycleExtensions = "2.2.0"
 androidx_media = "1.8.0"
-androidx_mmedia3 = "1.10.1"
-androidx_pagingRuntime = "3.5.0"
+androidx_mmedia3 = "1.11.1"
+androidx_pagingRuntime = "3.5.1"
 androidx_palette = "1.0.0"
 androidx_preference = "1.2.1"
 androidx_recyclerview = "1.4.0"
@@ -81,7 +81,7 @@ subsamplingScaleImageView = "3.10.0"
 taptargetview = "1.15.0"
 turbine = "1.2.1"
 uiautomator = "2.3.0"
-webrtcAndroid = "144.0.0"
+webrtcAndroid = "149.0.0"
 zip4j = "2.11.6"
 zxing = "3.5.4"