diff --git a/AndroidManifest.xml b/AndroidManifest.xml index 13dbb534ab..40c5a414b5 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -682,7 +682,7 @@ @@ -700,13 +700,6 @@ - - - - - WorkManager + * API instead. */ public abstract class Job { diff --git a/src/org/thoughtcrime/securesms/jobmanager/migration/WorkManagerFactoryMappings.java b/src/org/thoughtcrime/securesms/jobmanager/migration/WorkManagerFactoryMappings.java index 1449ace743..5f82cae0c6 100644 --- a/src/org/thoughtcrime/securesms/jobmanager/migration/WorkManagerFactoryMappings.java +++ b/src/org/thoughtcrime/securesms/jobmanager/migration/WorkManagerFactoryMappings.java @@ -44,7 +44,6 @@ import org.thoughtcrime.securesms.jobs.SmsSentJob; import org.thoughtcrime.securesms.jobs.TrimThreadJob; import org.thoughtcrime.securesms.jobs.TypingSendJob; import org.thoughtcrime.securesms.jobs.UpdateApkJob; -import org.thoughtcrime.securesms.loki.api.BackgroundPollJob; import org.thoughtcrime.securesms.loki.protocol.ClosedGroupUpdateMessageSendJob; import org.thoughtcrime.securesms.loki.protocol.NullMessageSendJob; import org.thoughtcrime.securesms.loki.protocol.SessionRequestMessageSendJob; @@ -59,7 +58,6 @@ public class WorkManagerFactoryMappings { put(AttachmentDownloadJob.class.getName(), AttachmentDownloadJob.KEY); put(AttachmentUploadJob.class.getName(), AttachmentUploadJob.KEY); put(AvatarDownloadJob.class.getName(), AvatarDownloadJob.KEY); - put(BackgroundPollJob.class.getName(), BackgroundPollJob.KEY); put(CleanPreKeysJob.class.getName(), CleanPreKeysJob.KEY); put(ClosedGroupUpdateMessageSendJob.class.getName(), ClosedGroupUpdateMessageSendJob.KEY); put(CreateSignedPreKeyJob.class.getName(), CreateSignedPreKeyJob.KEY); diff --git a/src/org/thoughtcrime/securesms/jobs/BaseJob.java b/src/org/thoughtcrime/securesms/jobs/BaseJob.java index 73053b0479..7e8852cd55 100644 --- a/src/org/thoughtcrime/securesms/jobs/BaseJob.java +++ b/src/org/thoughtcrime/securesms/jobs/BaseJob.java @@ -6,6 +6,11 @@ import org.thoughtcrime.securesms.jobmanager.Job; import org.thoughtcrime.securesms.jobmanager.JobLogger; import org.thoughtcrime.securesms.logging.Log; +/** + * @deprecated + * use WorkManager + * API instead. + */ public abstract class BaseJob extends Job { private static final String TAG = BaseJob.class.getSimpleName(); diff --git a/src/org/thoughtcrime/securesms/jobs/JobManagerFactories.java b/src/org/thoughtcrime/securesms/jobs/JobManagerFactories.java index 6f3c34e310..111f7968e7 100644 --- a/src/org/thoughtcrime/securesms/jobs/JobManagerFactories.java +++ b/src/org/thoughtcrime/securesms/jobs/JobManagerFactories.java @@ -14,7 +14,6 @@ import org.thoughtcrime.securesms.jobmanager.impl.NetworkConstraintObserver; import org.thoughtcrime.securesms.jobmanager.impl.NetworkOrCellServiceConstraint; import org.thoughtcrime.securesms.jobmanager.impl.SqlCipherMigrationConstraint; import org.thoughtcrime.securesms.jobmanager.impl.SqlCipherMigrationConstraintObserver; -import org.thoughtcrime.securesms.loki.api.BackgroundPollJob; import org.thoughtcrime.securesms.loki.protocol.ClosedGroupUpdateMessageSendJob; import org.thoughtcrime.securesms.loki.protocol.NullMessageSendJob; import org.thoughtcrime.securesms.loki.protocol.SessionRequestMessageSendJob; @@ -32,7 +31,6 @@ public final class JobManagerFactories { put(AttachmentDownloadJob.KEY, new AttachmentDownloadJob.Factory()); put(AttachmentUploadJob.KEY, new AttachmentUploadJob.Factory()); put(AvatarDownloadJob.KEY, new AvatarDownloadJob.Factory()); - put(BackgroundPollJob.KEY, new BackgroundPollJob.Factory()); put(CleanPreKeysJob.KEY, new CleanPreKeysJob.Factory()); put(ClosedGroupUpdateMessageSendJob.KEY, new ClosedGroupUpdateMessageSendJob.Factory()); put(CreateSignedPreKeyJob.KEY, new CreateSignedPreKeyJob.Factory()); diff --git a/src/org/thoughtcrime/securesms/loki/api/BackgroundPollJob.kt b/src/org/thoughtcrime/securesms/loki/api/BackgroundPollJob.kt deleted file mode 100644 index 1cf97b3c64..0000000000 --- a/src/org/thoughtcrime/securesms/loki/api/BackgroundPollJob.kt +++ /dev/null @@ -1,84 +0,0 @@ -package org.thoughtcrime.securesms.loki.api - -import android.content.Context -import kotlinx.coroutines.awaitAll -import nl.komponents.kovenant.Promise -import nl.komponents.kovenant.all -import nl.komponents.kovenant.functional.map -import org.thoughtcrime.securesms.ApplicationContext -import org.thoughtcrime.securesms.database.DatabaseFactory -import org.thoughtcrime.securesms.dependencies.InjectableType -import org.thoughtcrime.securesms.jobmanager.Data -import org.thoughtcrime.securesms.jobmanager.Job -import org.thoughtcrime.securesms.jobmanager.impl.NetworkConstraint -import org.thoughtcrime.securesms.jobs.BaseJob -import org.thoughtcrime.securesms.jobs.PushContentReceiveJob -import org.thoughtcrime.securesms.jobs.RotateCertificateJob -import org.thoughtcrime.securesms.logging.Log -import org.thoughtcrime.securesms.util.TextSecurePreferences -import org.whispersystems.signalservice.api.SignalServiceAccountManager -import org.whispersystems.signalservice.api.messages.SignalServiceEnvelope -import org.whispersystems.signalservice.api.push.exceptions.PushNetworkException -import org.whispersystems.signalservice.loki.api.SnodeAPI -import java.io.IOException -import java.util.concurrent.TimeUnit -import javax.inject.Inject - -class BackgroundPollJob private constructor(parameters: Parameters) : BaseJob(parameters) { - - companion object { - const val KEY = "BackgroundPollJob" - } - - constructor(context: Context) : this(Parameters.Builder() - .addConstraint(NetworkConstraint.KEY) - .setQueue(KEY) - .setLifespan(TimeUnit.DAYS.toMillis(1)) - .setMaxAttempts(Parameters.UNLIMITED) - .build()) { - setContext(context) - } - - override fun serialize(): Data { - return Data.EMPTY - } - - override fun getFactoryKey(): String { return KEY } - - public override fun onRun() { - try { - Log.d("Loki", "Performing background poll.") - val userPublicKey = TextSecurePreferences.getLocalNumber(context) - val promises = mutableListOf>() - val promise = SnodeAPI.shared.getMessages(userPublicKey).map { envelopes -> - envelopes.forEach { - PushContentReceiveJob(context).processEnvelope(SignalServiceEnvelope(it), false) - } - } - promises.add(promise) - promises.addAll(ClosedGroupPoller.shared.pollOnce()) - val openGroups = DatabaseFactory.getLokiThreadDatabase(context).getAllPublicChats().map { it.value } - for (openGroup in openGroups) { - val poller = PublicChatPoller(context, openGroup) - poller.stop() - promises.add(poller.pollForNewMessages()) - } - all(promises).get() - } catch (exception: Exception) { - Log.d("Loki", "Background poll failed due to error: $exception.") - } - } - - public override fun onShouldRetry(e: Exception): Boolean { - return false - } - - override fun onCanceled() { } - - class Factory : Job.Factory { - - override fun create(parameters: Parameters, data: Data): BackgroundPollJob { - return BackgroundPollJob(parameters) - } - } -} diff --git a/src/org/thoughtcrime/securesms/loki/api/BackgroundPollListener.kt b/src/org/thoughtcrime/securesms/loki/api/BackgroundPollListener.kt deleted file mode 100644 index da17528b4f..0000000000 --- a/src/org/thoughtcrime/securesms/loki/api/BackgroundPollListener.kt +++ /dev/null @@ -1,36 +0,0 @@ -package org.thoughtcrime.securesms.loki.api - -import android.content.Context -import android.content.Intent -import nl.komponents.kovenant.functional.map -import org.thoughtcrime.securesms.ApplicationContext -import org.thoughtcrime.securesms.database.DatabaseFactory -import org.thoughtcrime.securesms.jobs.PushContentReceiveJob -import org.thoughtcrime.securesms.service.PersistentAlarmManagerListener -import org.thoughtcrime.securesms.util.TextSecurePreferences -import org.whispersystems.signalservice.api.messages.SignalServiceEnvelope -import org.whispersystems.signalservice.loki.api.SnodeAPI -import java.util.concurrent.TimeUnit - -class BackgroundPollListener : PersistentAlarmManagerListener() { - - companion object { - private val pollInterval = TimeUnit.MINUTES.toMillis(15) - - @JvmStatic - fun schedule(context: Context) { - BackgroundPollListener().onReceive(context, Intent()) - } - } - - override fun getNextScheduledExecutionTime(context: Context): Long { - return TextSecurePreferences.getBackgroundPollTime(context) - } - - override fun onAlarm(context: Context, scheduledTime: Long): Long { - ApplicationContext.getInstance(context).jobManager.add(BackgroundPollJob(context)) - val nextTime = System.currentTimeMillis() + pollInterval - TextSecurePreferences.setBackgroundPollTime(context, nextTime) - return nextTime - } -} diff --git a/src/org/thoughtcrime/securesms/loki/api/BackgroundPollWorker.kt b/src/org/thoughtcrime/securesms/loki/api/BackgroundPollWorker.kt new file mode 100644 index 0000000000..66ce90905d --- /dev/null +++ b/src/org/thoughtcrime/securesms/loki/api/BackgroundPollWorker.kt @@ -0,0 +1,113 @@ +package org.thoughtcrime.securesms.loki.api + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import androidx.work.* +import nl.komponents.kovenant.Promise +import nl.komponents.kovenant.all +import nl.komponents.kovenant.functional.map +import org.thoughtcrime.securesms.database.DatabaseFactory +import org.thoughtcrime.securesms.jobs.PushContentReceiveJob +import org.thoughtcrime.securesms.logging.Log +import org.thoughtcrime.securesms.util.TextSecurePreferences +import org.whispersystems.signalservice.api.messages.SignalServiceEnvelope +import org.whispersystems.signalservice.loki.api.SnodeAPI +import java.util.concurrent.TimeUnit + +class BackgroundPollWorker(val context: Context, params: WorkerParameters) : Worker(context, params) { + + companion object { + const val TAG = "BackgroundPollWorker" + + private const val RETRY_ATTEMPTS = 3 + + @JvmStatic + fun scheduleInstant(context: Context) { + val workRequest = OneTimeWorkRequestBuilder() + .setConstraints( + Constraints.Builder() + .setRequiredNetworkType(NetworkType.CONNECTED) + .build() + ) + .build() + + WorkManager + .getInstance(context) + .enqueue(workRequest) + } + + @JvmStatic + fun schedulePeriodic(context: Context) { + Log.v(TAG, "Scheduling periodic work.") + val workRequest = PeriodicWorkRequestBuilder(15, TimeUnit.MINUTES) + .setConstraints( + Constraints.Builder() + .setRequiredNetworkType(NetworkType.CONNECTED) + .build() + ) + .build() + + WorkManager + .getInstance(context) + .enqueueUniquePeriodicWork( + TAG, + ExistingPeriodicWorkPolicy.KEEP, + workRequest + ) + } + } + + override fun doWork(): Result { + if (TextSecurePreferences.getLocalNumber(context) == null) { + Log.v(TAG, "Background poll is canceled due to the Session user is not set up yet.") + return Result.failure() + } + + try { + Log.v(TAG, "Performing background poll.") + val promises = mutableListOf>() + + // Private chats + val userPublicKey = TextSecurePreferences.getLocalNumber(context) + val privateChatsPromise = SnodeAPI.shared.getMessages(userPublicKey).map { envelopes -> + envelopes.forEach { + PushContentReceiveJob(context).processEnvelope(SignalServiceEnvelope(it), false) + } + } + promises.add(privateChatsPromise) + + // Closed groups + val sskDatabase = DatabaseFactory.getSSKDatabase(context) + ClosedGroupPoller.configureIfNeeded(context, sskDatabase) + promises.addAll(ClosedGroupPoller.shared.pollOnce()) + + // Open Groups + val openGroups = DatabaseFactory.getLokiThreadDatabase(context).getAllPublicChats().map { it.value } + for (openGroup in openGroups) { + val poller = PublicChatPoller(context, openGroup) + promises.add(poller.pollForNewMessages()) + } + + // Wait till all the promises get resolved + all(promises).get() + + return Result.success() + } catch (exception: Exception) { + Log.v(TAG, "Background poll failed due to error: ${exception.message}.", exception) + + return if (runAttemptCount < RETRY_ATTEMPTS) Result.retry() else Result.failure() + } + } + + class BootBroadcastReceiver: BroadcastReceiver() { + + override fun onReceive(context: Context, intent: Intent) { + if (intent.action == Intent.ACTION_BOOT_COMPLETED) { + Log.v(TAG, "Boot broadcast caught.") + BackgroundPollWorker.scheduleInstant(context) + BackgroundPollWorker.schedulePeriodic(context) + } + } + } +} diff --git a/src/org/thoughtcrime/securesms/loki/api/ClosedGroupPoller.kt b/src/org/thoughtcrime/securesms/loki/api/ClosedGroupPoller.kt index 77b973f57b..4f1a1d1930 100644 --- a/src/org/thoughtcrime/securesms/loki/api/ClosedGroupPoller.kt +++ b/src/org/thoughtcrime/securesms/loki/api/ClosedGroupPoller.kt @@ -17,7 +17,7 @@ import org.whispersystems.signalservice.loki.utilities.getRandomElementOrNull class ClosedGroupPoller private constructor(private val context: Context, private val database: SharedSenderKeysDatabase) { private var isPolling = false - private val handler = Handler() + private val handler: Handler by lazy { Handler() } private val task = object : Runnable { diff --git a/src/org/thoughtcrime/securesms/loki/api/PublicChatPoller.kt b/src/org/thoughtcrime/securesms/loki/api/PublicChatPoller.kt index 374f8b68c6..cc2ef6facb 100644 --- a/src/org/thoughtcrime/securesms/loki/api/PublicChatPoller.kt +++ b/src/org/thoughtcrime/securesms/loki/api/PublicChatPoller.kt @@ -3,6 +3,7 @@ package org.thoughtcrime.securesms.loki.api import android.content.Context import android.os.Handler import android.util.Log +import androidx.annotation.WorkerThread import nl.komponents.kovenant.Promise import nl.komponents.kovenant.functional.bind import nl.komponents.kovenant.functional.map @@ -30,9 +31,10 @@ import org.whispersystems.signalservice.loki.api.opengroups.PublicChatMessage import org.whispersystems.signalservice.loki.protocol.shelved.multidevice.MultiDeviceProtocol import java.security.MessageDigest import java.util.* +import java.util.concurrent.CompletableFuture class PublicChatPoller(private val context: Context, private val group: PublicChat) { - private val handler = Handler() + private val handler by lazy { Handler() } private var hasStarted = false private var isPollOngoing = false public var isCaughtUp = false