session-android/app/src/main/java/org/thoughtcrime/securesms/service/ExpiringMessageManager.java

264 lines
10 KiB
Java
Raw Normal View History

package org.thoughtcrime.securesms.service;
import android.content.Context;
2021-01-13 07:11:30 +01:00
import org.jetbrains.annotations.NotNull;
2022-12-09 03:51:44 +01:00
import org.jetbrains.annotations.Nullable;
import org.session.libsession.messaging.messages.ExpirationConfiguration;
2021-03-25 04:55:23 +01:00
import org.session.libsession.messaging.messages.control.ExpirationTimerUpdate;
import org.session.libsession.messaging.messages.signal.IncomingMediaMessage;
2021-04-15 06:41:29 +02:00
import org.session.libsession.messaging.messages.signal.OutgoingExpirationUpdateMessage;
2021-05-18 08:11:38 +02:00
import org.session.libsession.utilities.Address;
2021-03-25 04:55:23 +01:00
import org.session.libsession.utilities.GroupUtil;
2021-01-13 07:11:30 +01:00
import org.session.libsession.utilities.SSKEnvironment;
import org.session.libsession.utilities.TextSecurePreferences;
import org.session.libsession.utilities.recipients.Recipient;
2021-05-18 01:50:16 +02:00
import org.session.libsignal.messages.SignalServiceGroup;
2021-05-18 01:12:33 +02:00
import org.session.libsignal.utilities.Log;
import org.session.libsignal.utilities.guava.Optional;
import org.thoughtcrime.securesms.database.MmsDatabase;
import org.thoughtcrime.securesms.database.SmsDatabase;
2022-12-16 05:21:48 +01:00
import org.thoughtcrime.securesms.database.ThreadDatabase;
import org.thoughtcrime.securesms.database.model.MessageRecord;
import org.thoughtcrime.securesms.dependencies.DatabaseComponent;
2021-01-13 07:11:30 +01:00
import org.thoughtcrime.securesms.mms.MmsException;
2021-03-25 04:55:23 +01:00
import java.io.IOException;
import java.util.Comparator;
import java.util.TreeSet;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
2021-01-13 07:11:30 +01:00
public class ExpiringMessageManager implements SSKEnvironment.MessageExpirationManagerProtocol {
private static final String TAG = ExpiringMessageManager.class.getSimpleName();
private final TreeSet<ExpiringMessageReference> expiringMessageReferences = new TreeSet<>(new ExpiringMessageComparator());
private final Executor executor = Executors.newSingleThreadExecutor();
private final SmsDatabase smsDatabase;
private final MmsDatabase mmsDatabase;
private final Context context;
public ExpiringMessageManager(Context context) {
this.context = context.getApplicationContext();
this.smsDatabase = DatabaseComponent.get(context).smsDatabase();
this.mmsDatabase = DatabaseComponent.get(context).mmsDatabase();
executor.execute(new LoadTask());
executor.execute(new ProcessTask());
}
public void scheduleDeletion(long id, boolean mms, long expiresInMillis) {
scheduleDeletion(id, mms, System.currentTimeMillis(), expiresInMillis);
}
public void scheduleDeletion(long id, boolean mms, long startedAtTimestamp, long expiresInMillis) {
long expiresAtMillis = startedAtTimestamp + expiresInMillis;
synchronized (expiringMessageReferences) {
expiringMessageReferences.add(new ExpiringMessageReference(id, mms, expiresAtMillis));
expiringMessageReferences.notifyAll();
}
}
public void checkSchedule() {
synchronized (expiringMessageReferences) {
expiringMessageReferences.notifyAll();
}
}
2021-01-13 07:11:30 +01:00
@Override
2022-12-19 09:37:22 +01:00
public void setExpirationTimer(@NotNull ExpirationTimerUpdate message) {
String userPublicKey = TextSecurePreferences.getLocalNumber(context);
String senderPublicKey = message.getSender();
// Notify the user
if (senderPublicKey == null || userPublicKey.equals(senderPublicKey)) {
// sender is self or a linked device
insertOutgoingExpirationTimerMessage(message);
} else {
insertIncomingExpirationTimerMessage(message);
}
if (message.getId() != null) {
DatabaseComponent.get(context).smsDatabase().deleteMessage(message.getId());
}
}
private void insertIncomingExpirationTimerMessage(ExpirationTimerUpdate message) {
MmsDatabase database = DatabaseComponent.get(context).mmsDatabase();
2021-03-25 04:55:23 +01:00
String senderPublicKey = message.getSender();
Long sentTimestamp = message.getSentTimestamp();
String groupId = message.getGroupPublicKey();
int duration = message.getDuration();
2021-03-25 04:55:23 +01:00
Optional<SignalServiceGroup> groupInfo = Optional.absent();
Address address = Address.fromSerialized(senderPublicKey);
Recipient recipient = Recipient.from(context, address, false);
// if the sender is blocked, we don't display the update, except if it's in a closed group
if (recipient.isBlocked() && groupId == null) return;
2021-03-25 04:55:23 +01:00
2021-01-13 07:11:30 +01:00
try {
if (groupId != null) {
String groupID = GroupUtil.doubleEncodeGroupID(groupId);
2021-03-25 04:55:23 +01:00
groupInfo = Optional.of(new SignalServiceGroup(GroupUtil.getDecodedGroupIDAsData(groupID), SignalServiceGroup.GroupType.SIGNAL));
Address groupAddress = Address.fromSerialized(groupID);
recipient = Recipient.from(context, groupAddress, false);
2021-03-25 04:55:23 +01:00
}
IncomingMediaMessage mediaMessage = new IncomingMediaMessage(address, sentTimestamp, -1,
duration * 1000L, true,
false,
false,
Optional.absent(),
groupInfo,
Optional.absent(),
Optional.absent(),
Optional.absent(),
Optional.absent(),
Optional.absent());
//insert the timer update message
Performance improvements and bug fixes (#869) * refactor: fail on testSnode instead of recursively using up snode list. add call timeout on http client * refactor: refactoring batch message receives and pollers * refactor: reduce thread utils pool count to a 2 thread fixed pool. Do a check against pubkey instead of room names for oxenHostedOpenGroup * refactor: caching lib with potential loader fixes and no-cache for giphy * refactor: remove store and instead use ConcurrentHashMap with a backing update coroutine * refactor: queue trim thread jobs instead of add every message processed * fix: wrapping auth token and initial sync for open groups in a threadutils queued runnable, getting initial sync times down * fix: fixing the user contacts cache in ConversationAdapter.kt * refactor: improve polling and initial sync, move group joins from config messages into a background job fetching image. * refactor: improving the job queuing for open groups, replacing placeholder avatar generation with a custom glide loader and archiving initial sync of open groups * feat: add OpenGroupDeleteJob.kt * feat: add open group delete job to process deletions after batch adding * feat: add vacuum and fix job queue re-adding jobs forever, only try to set message hash values in DB if they have changed * refactor: remove redundant inflation for profile image views throughout app * refactor(wip): reducing layout inflation and starting to refactor the open group deletion issues taking a long time * refactor(wip): refactoring group deletion to not iterate through and delete messages individually * refactor(wip): refactoring group deletion to not iterate through and delete messages individually * fix: group deletion optimisation * build: bump build number * build: bump build number and fix batch message receive retry logic * fix: clear out open group deletes * fix: update visible ConversationAdapter.kt binding for initial contact fetching and better traces for debugging background jobs * fix: add in check for / force sync latest encryption key pair from linked devices if we already have that closed group * Rename .java to .kt * refactor: change MmsDatabase to kotlin to make list operations easier * fix: nullable type * fix: compilation issues and constants in .kt instead of .java * fix: bug fix expiration timer on closed group recipient * feat: use the job queue properly across executors * feat: start on open group dispatcher-specific logic, probably a queue factory based on openGroupId if that is the same across new message and deletion jobs to ensure consistent entry and removal * refactor: removing redundant code and fixing jobqueue per opengroup * fix: allow attachments in note to self * fix: make the minWidth in quote view bind max of text / title and body, wrapped ? * fix: fixing up layouts and code view layouts * fix: remove TODO, remove timestamp binding * feat: fix view logic, avatars and padding, downloading attachments lazily (on bind), fixing potential crash, add WindowDebouncer.kt * fix: NPE on viewModel recipient from removed thread while tearing down the Recipient observer in ConversationActivityV2.kt * refactor: replace conversation notification debouncer handler with handlerthread, same as conversation list debouncer * refactor: UI for groups and poller improvements * fix: revert some changes in poller * feat: add header back in for message requests * refactor: remove Trace calls, add more conditions to the HomeDiffUtil for updating more efficiently * feat: try update the home adapter if we get a profile picture modified event * feat: bump build numbers * fix: try to start with list in homeViewModel if we don't have already, render quotes to be width of attachment slide view instead of fixed * fix: set channel to be conflated instead of no buffer * fix: set unreads based off last local user message vs incrementing unreads to be all amount * feat: add profile update flag, update build number * fix: link preview thumbnails download on bind * fix: centercrop placeholder in glide request * feat: recycle the contact selection list and profile image in unbind * fix: try to prevent user KP crash at weird times * fix: remove additional log, improve attachment download success rate, fix share logs dialog issue
2022-06-08 09:12:34 +02:00
database.insertSecureDecryptedMessageInbox(mediaMessage, -1, true, true);
} catch (IOException | MmsException ioe) {
Log.e("Loki", "Failed to insert expiration update message.");
}
}
private void insertOutgoingExpirationTimerMessage(ExpirationTimerUpdate message) {
MmsDatabase database = DatabaseComponent.get(context).mmsDatabase();
Long sentTimestamp = message.getSentTimestamp();
String groupId = message.getGroupPublicKey();
int duration = message.getDuration();
Address address = Address.fromSerialized((message.getSyncTarget() != null && !message.getSyncTarget().isEmpty()) ? message.getSyncTarget() : message.getRecipient());
Recipient recipient = Recipient.from(context, address, false);
try {
2021-04-15 06:41:29 +02:00
OutgoingExpirationUpdateMessage timerUpdateMessage = new OutgoingExpirationUpdateMessage(recipient, sentTimestamp, duration * 1000L, groupId);
Performance improvements and bug fixes (#869) * refactor: fail on testSnode instead of recursively using up snode list. add call timeout on http client * refactor: refactoring batch message receives and pollers * refactor: reduce thread utils pool count to a 2 thread fixed pool. Do a check against pubkey instead of room names for oxenHostedOpenGroup * refactor: caching lib with potential loader fixes and no-cache for giphy * refactor: remove store and instead use ConcurrentHashMap with a backing update coroutine * refactor: queue trim thread jobs instead of add every message processed * fix: wrapping auth token and initial sync for open groups in a threadutils queued runnable, getting initial sync times down * fix: fixing the user contacts cache in ConversationAdapter.kt * refactor: improve polling and initial sync, move group joins from config messages into a background job fetching image. * refactor: improving the job queuing for open groups, replacing placeholder avatar generation with a custom glide loader and archiving initial sync of open groups * feat: add OpenGroupDeleteJob.kt * feat: add open group delete job to process deletions after batch adding * feat: add vacuum and fix job queue re-adding jobs forever, only try to set message hash values in DB if they have changed * refactor: remove redundant inflation for profile image views throughout app * refactor(wip): reducing layout inflation and starting to refactor the open group deletion issues taking a long time * refactor(wip): refactoring group deletion to not iterate through and delete messages individually * refactor(wip): refactoring group deletion to not iterate through and delete messages individually * fix: group deletion optimisation * build: bump build number * build: bump build number and fix batch message receive retry logic * fix: clear out open group deletes * fix: update visible ConversationAdapter.kt binding for initial contact fetching and better traces for debugging background jobs * fix: add in check for / force sync latest encryption key pair from linked devices if we already have that closed group * Rename .java to .kt * refactor: change MmsDatabase to kotlin to make list operations easier * fix: nullable type * fix: compilation issues and constants in .kt instead of .java * fix: bug fix expiration timer on closed group recipient * feat: use the job queue properly across executors * feat: start on open group dispatcher-specific logic, probably a queue factory based on openGroupId if that is the same across new message and deletion jobs to ensure consistent entry and removal * refactor: removing redundant code and fixing jobqueue per opengroup * fix: allow attachments in note to self * fix: make the minWidth in quote view bind max of text / title and body, wrapped ? * fix: fixing up layouts and code view layouts * fix: remove TODO, remove timestamp binding * feat: fix view logic, avatars and padding, downloading attachments lazily (on bind), fixing potential crash, add WindowDebouncer.kt * fix: NPE on viewModel recipient from removed thread while tearing down the Recipient observer in ConversationActivityV2.kt * refactor: replace conversation notification debouncer handler with handlerthread, same as conversation list debouncer * refactor: UI for groups and poller improvements * fix: revert some changes in poller * feat: add header back in for message requests * refactor: remove Trace calls, add more conditions to the HomeDiffUtil for updating more efficiently * feat: try update the home adapter if we get a profile picture modified event * feat: bump build numbers * fix: try to start with list in homeViewModel if we don't have already, render quotes to be width of attachment slide view instead of fixed * fix: set channel to be conflated instead of no buffer * fix: set unreads based off last local user message vs incrementing unreads to be all amount * feat: add profile update flag, update build number * fix: link preview thumbnails download on bind * fix: centercrop placeholder in glide request * feat: recycle the contact selection list and profile image in unbind * fix: try to prevent user KP crash at weird times * fix: remove additional log, improve attachment download success rate, fix share logs dialog issue
2022-06-08 09:12:34 +02:00
database.insertSecureDecryptedMessageOutbox(timerUpdateMessage, -1, sentTimestamp, true);
2022-12-09 03:51:44 +01:00
} catch (MmsException e) {
2021-03-25 04:55:23 +01:00
Log.e("Loki", "Failed to insert expiration update message.");
2021-01-13 07:11:30 +01:00
}
}
2021-01-20 06:29:52 +01:00
@Override
2021-03-02 02:24:09 +01:00
public void startAnyExpiration(long timestamp, @NotNull String author) {
MessageRecord messageRecord = DatabaseComponent.get(context).mmsSmsDatabase().getMessageFor(timestamp, author);
2021-01-20 06:29:52 +01:00
if (messageRecord != null) {
boolean mms = messageRecord.isMms();
2022-12-16 03:35:55 +01:00
ExpirationConfiguration config = DatabaseComponent.get(context).expirationConfigurationDatabase().getExpirationConfiguration(messageRecord.getThreadId());
if (config == null || !config.isEnabled()) return;
2021-01-20 06:29:52 +01:00
if (mms) {
2021-03-02 02:24:09 +01:00
mmsDatabase.markExpireStarted(messageRecord.getId());
2021-01-20 06:29:52 +01:00
} else {
2021-03-02 02:24:09 +01:00
smsDatabase.markExpireStarted(messageRecord.getId());
2021-01-20 06:29:52 +01:00
}
2022-12-16 03:35:55 +01:00
scheduleDeletion(messageRecord.getId(), mms, config.getDurationSeconds() * 1000L);
2021-01-20 06:29:52 +01:00
}
}
private class LoadTask implements Runnable {
public void run() {
SmsDatabase.Reader smsReader = smsDatabase.readerFor(smsDatabase.getExpirationStartedMessages());
MmsDatabase.Reader mmsReader = mmsDatabase.getExpireStartedMessages();
MessageRecord messageRecord;
while ((messageRecord = smsReader.getNext()) != null) {
expiringMessageReferences.add(new ExpiringMessageReference(messageRecord.getId(),
messageRecord.isMms(),
messageRecord.getExpireStarted() + messageRecord.getExpiresIn()));
}
while ((messageRecord = mmsReader.getNext()) != null) {
expiringMessageReferences.add(new ExpiringMessageReference(messageRecord.getId(),
messageRecord.isMms(),
messageRecord.getExpireStarted() + messageRecord.getExpiresIn()));
}
smsReader.close();
mmsReader.close();
}
}
@SuppressWarnings("InfiniteLoopStatement")
private class ProcessTask implements Runnable {
public void run() {
while (true) {
ExpiringMessageReference expiredMessage = null;
synchronized (expiringMessageReferences) {
try {
while (expiringMessageReferences.isEmpty()) expiringMessageReferences.wait();
ExpiringMessageReference nextReference = expiringMessageReferences.first();
long waitTime = nextReference.expiresAtMillis - System.currentTimeMillis();
if (waitTime > 0) {
ExpirationListener.setAlarm(context, waitTime);
expiringMessageReferences.wait(waitTime);
} else {
expiredMessage = nextReference;
expiringMessageReferences.remove(nextReference);
}
} catch (InterruptedException e) {
Log.w(TAG, e);
}
}
if (expiredMessage != null) {
if (expiredMessage.mms) mmsDatabase.deleteMessage(expiredMessage.id);
else smsDatabase.deleteMessage(expiredMessage.id);
}
}
}
}
private static class ExpiringMessageReference {
private final long id;
private final boolean mms;
private final long expiresAtMillis;
private ExpiringMessageReference(long id, boolean mms, long expiresAtMillis) {
this.id = id;
this.mms = mms;
this.expiresAtMillis = expiresAtMillis;
}
@Override
public boolean equals(Object other) {
if (other == null) return false;
if (!(other instanceof ExpiringMessageReference)) return false;
ExpiringMessageReference that = (ExpiringMessageReference)other;
return this.id == that.id && this.mms == that.mms && this.expiresAtMillis == that.expiresAtMillis;
}
@Override
public int hashCode() {
return (int)this.id ^ (mms ? 1 : 0) ^ (int)expiresAtMillis;
}
}
private static class ExpiringMessageComparator implements Comparator<ExpiringMessageReference> {
@Override
public int compare(ExpiringMessageReference lhs, ExpiringMessageReference rhs) {
if (lhs.expiresAtMillis < rhs.expiresAtMillis) return -1;
else if (lhs.expiresAtMillis > rhs.expiresAtMillis) return 1;
else if (lhs.id < rhs.id) return -1;
else if (lhs.id > rhs.id) return 1;
else if (!lhs.mms && rhs.mms) return -1;
else if (lhs.mms && !rhs.mms) return 1;
else return 0;
}
}
}