2019-08-07 14:22:51 -04:00
|
|
|
package org.thoughtcrime.securesms.recipients;
|
|
|
|
|
|
|
|
|
|
import android.annotation.SuppressLint;
|
|
|
|
|
import android.content.Context;
|
|
|
|
|
|
|
|
|
|
import androidx.annotation.AnyThread;
|
|
|
|
|
import androidx.annotation.NonNull;
|
|
|
|
|
import androidx.annotation.WorkerThread;
|
|
|
|
|
import androidx.lifecycle.MutableLiveData;
|
|
|
|
|
|
|
|
|
|
import org.thoughtcrime.securesms.database.DatabaseFactory;
|
|
|
|
|
import org.thoughtcrime.securesms.database.RecipientDatabase;
|
2019-10-02 12:06:13 -04:00
|
|
|
import org.thoughtcrime.securesms.database.RecipientDatabase.MissingRecipientError;
|
2019-08-07 14:22:51 -04:00
|
|
|
import org.thoughtcrime.securesms.util.LRUCache;
|
|
|
|
|
import org.thoughtcrime.securesms.util.TextSecurePreferences;
|
|
|
|
|
import org.thoughtcrime.securesms.util.concurrent.SignalExecutors;
|
|
|
|
|
|
|
|
|
|
import java.util.Map;
|
|
|
|
|
|
|
|
|
|
public final class LiveRecipientCache {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
private final Context context;
|
|
|
|
|
private final RecipientDatabase recipientDatabase;
|
|
|
|
|
private final Map<RecipientId, LiveRecipient> recipients;
|
|
|
|
|
|
|
|
|
|
private RecipientId localRecipientId;
|
|
|
|
|
|
|
|
|
|
@SuppressLint("UseSparseArrays")
|
|
|
|
|
public LiveRecipientCache(@NonNull Context context) {
|
|
|
|
|
this.context = context.getApplicationContext();
|
|
|
|
|
this.recipientDatabase = DatabaseFactory.getRecipientDatabase(context);
|
|
|
|
|
this.recipients = new LRUCache<>(1000);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@AnyThread
|
|
|
|
|
synchronized @NonNull LiveRecipient getLive(@NonNull RecipientId id) {
|
|
|
|
|
LiveRecipient live = recipients.get(id);
|
|
|
|
|
|
|
|
|
|
if (live == null) {
|
|
|
|
|
final LiveRecipient newLive = new LiveRecipient(context, new MutableLiveData<>(), new Recipient(id));
|
|
|
|
|
|
|
|
|
|
recipients.put(id, newLive);
|
2019-10-02 12:06:13 -04:00
|
|
|
|
|
|
|
|
MissingRecipientError prettyStackTraceError = new MissingRecipientError(newLive.getId());
|
|
|
|
|
|
|
|
|
|
SignalExecutors.BOUNDED.execute(() -> {
|
|
|
|
|
try {
|
|
|
|
|
newLive.resolve();
|
|
|
|
|
} catch (MissingRecipientError e) {
|
|
|
|
|
throw prettyStackTraceError;
|
|
|
|
|
}
|
|
|
|
|
});
|
2019-08-07 14:22:51 -04:00
|
|
|
|
|
|
|
|
live = newLive;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return live;
|
|
|
|
|
}
|
|
|
|
|
|
2019-09-24 12:03:33 -04:00
|
|
|
@NonNull Recipient getSelf() {
|
|
|
|
|
synchronized (this) {
|
|
|
|
|
if (localRecipientId == null) {
|
|
|
|
|
localRecipientId = recipientDatabase.getOrInsertFromE164(TextSecurePreferences.getLocalNumber(context));
|
|
|
|
|
}
|
2019-08-07 14:22:51 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return getLive(localRecipientId).resolve();
|
|
|
|
|
}
|
|
|
|
|
}
|