]> nmode's Git Repositories - signal-cli/blobdiff - lib/src/main/java/org/asamk/signal/manager/ManagerImpl.java
Merge multiple SendReceiptActions to same recipient to only send one receipt
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / ManagerImpl.java
index bbef8a069378e20e6d36a7bbc4c32923ba9dbc56..756c0a9474894ff8ca770c6b7b8b62f727f74fe9 100644 (file)
@@ -17,6 +17,7 @@
 package org.asamk.signal.manager;
 
 import org.asamk.signal.manager.actions.HandleAction;
+import org.asamk.signal.manager.api.Configuration;
 import org.asamk.signal.manager.api.Device;
 import org.asamk.signal.manager.api.Group;
 import org.asamk.signal.manager.api.Identity;
@@ -26,6 +27,7 @@ import org.asamk.signal.manager.api.Message;
 import org.asamk.signal.manager.api.Pair;
 import org.asamk.signal.manager.api.RecipientIdentifier;
 import org.asamk.signal.manager.api.SendGroupMessageResults;
+import org.asamk.signal.manager.api.SendMessageResult;
 import org.asamk.signal.manager.api.SendMessageResults;
 import org.asamk.signal.manager.api.TypingAction;
 import org.asamk.signal.manager.api.UpdateGroup;
@@ -69,14 +71,12 @@ import org.whispersystems.libsignal.InvalidKeyException;
 import org.whispersystems.libsignal.ecc.ECPublicKey;
 import org.whispersystems.libsignal.util.guava.Optional;
 import org.whispersystems.signalservice.api.SignalSessionLock;
-import org.whispersystems.signalservice.api.messages.SendMessageResult;
-import org.whispersystems.signalservice.api.messages.SignalServiceAttachmentRemoteId;
 import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage;
 import org.whispersystems.signalservice.api.messages.SignalServiceEnvelope;
 import org.whispersystems.signalservice.api.messages.SignalServiceReceiptMessage;
 import org.whispersystems.signalservice.api.messages.SignalServiceTypingMessage;
+import org.whispersystems.signalservice.api.push.ACI;
 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
-import org.whispersystems.signalservice.api.push.exceptions.UnregisteredUserException;
 import org.whispersystems.signalservice.api.util.DeviceNameUtil;
 import org.whispersystems.signalservice.api.util.InvalidNumberException;
 import org.whispersystems.signalservice.api.util.PhoneNumberFormatter;
@@ -108,6 +108,7 @@ import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
 import java.util.concurrent.locks.ReentrantLock;
 import java.util.stream.Collectors;
+import java.util.stream.Stream;
 
 import static org.asamk.signal.manager.config.ServiceConfig.capabilities;
 
@@ -139,6 +140,7 @@ public class ManagerImpl implements Manager {
     private boolean ignoreAttachments = false;
 
     private Thread receiveThread;
+    private final Set<ReceiveMessageHandler> weakHandlers = new HashSet<>();
     private final Set<ReceiveMessageHandler> messageHandlers = new HashSet<>();
     private boolean isReceivingSynchronous;
 
@@ -151,7 +153,7 @@ public class ManagerImpl implements Manager {
         this.account = account;
         this.serviceEnvironmentConfig = serviceEnvironmentConfig;
 
-        final var credentialsProvider = new DynamicCredentialsProvider(account.getUuid(),
+        final var credentialsProvider = new DynamicCredentialsProvider(account.getAci(),
                 account.getUsername(),
                 account.getPassword(),
                 account.getDeviceId());
@@ -264,8 +266,8 @@ public class ManagerImpl implements Manager {
             }
         }
         preKeyHelper.refreshPreKeysIfNecessary();
-        if (account.getUuid() == null) {
-            account.setUuid(dependencies.getAccountManager().getOwnUuid());
+        if (account.getAci() == null) {
+            account.setAci(dependencies.getAccountManager().getOwnAci());
         }
         updateAccountAttributes(null);
     }
@@ -295,8 +297,8 @@ public class ManagerImpl implements Manager {
 
         return numbers.stream().collect(Collectors.toMap(n -> n, n -> {
             final var number = canonicalizedNumbers.get(n);
-            final var uuid = registeredUsers.get(number);
-            return new Pair<>(number.isEmpty() ? null : number, uuid);
+            final var aci = registeredUsers.get(number);
+            return new Pair<>(number.isEmpty() ? null : number, aci == null ? null : aci.uuid());
         }));
     }
 
@@ -323,29 +325,35 @@ public class ManagerImpl implements Manager {
                         account.isDiscoverableByPhoneNumber());
     }
 
+    @Override
+    public Configuration getConfiguration() {
+        final var configurationStore = account.getConfigurationStore();
+        return new Configuration(java.util.Optional.ofNullable(configurationStore.getReadReceipts()),
+                java.util.Optional.ofNullable(configurationStore.getUnidentifiedDeliveryIndicators()),
+                java.util.Optional.ofNullable(configurationStore.getTypingIndicators()),
+                java.util.Optional.ofNullable(configurationStore.getLinkPreviews()));
+    }
+
     @Override
     public void updateConfiguration(
-            final Boolean readReceipts,
-            final Boolean unidentifiedDeliveryIndicators,
-            final Boolean typingIndicators,
-            final Boolean linkPreviews
+            Configuration configuration
     ) throws IOException, NotMasterDeviceException {
         if (!account.isMasterDevice()) {
             throw new NotMasterDeviceException();
         }
 
         final var configurationStore = account.getConfigurationStore();
-        if (readReceipts != null) {
-            configurationStore.setReadReceipts(readReceipts);
+        if (configuration.readReceipts().isPresent()) {
+            configurationStore.setReadReceipts(configuration.readReceipts().get());
         }
-        if (unidentifiedDeliveryIndicators != null) {
-            configurationStore.setUnidentifiedDeliveryIndicators(unidentifiedDeliveryIndicators);
+        if (configuration.unidentifiedDeliveryIndicators().isPresent()) {
+            configurationStore.setUnidentifiedDeliveryIndicators(configuration.unidentifiedDeliveryIndicators().get());
         }
-        if (typingIndicators != null) {
-            configurationStore.setTypingIndicators(typingIndicators);
+        if (configuration.typingIndicators().isPresent()) {
+            configurationStore.setTypingIndicators(configuration.typingIndicators().get());
         }
-        if (linkPreviews != null) {
-            configurationStore.setLinkPreviews(linkPreviews);
+        if (configuration.linkPreviews().isPresent()) {
+            configurationStore.setLinkPreviews(configuration.linkPreviews().get());
         }
         syncHelper.sendConfigurationMessage();
     }
@@ -383,7 +391,7 @@ public class ManagerImpl implements Manager {
     public void deleteAccount() throws IOException {
         try {
             pinHelper.removeRegistrationLockPin();
-        } catch (UnauthenticatedResponseException e) {
+        } catch (IOException e) {
             logger.warn("Failed to remove registration lock pin");
         }
         account.setRegistrationLockPin(null, null);
@@ -395,6 +403,8 @@ public class ManagerImpl implements Manager {
 
     @Override
     public void submitRateLimitRecaptchaChallenge(String challenge, String captcha) throws IOException {
+        captcha = captcha == null ? null : captcha.replace("signalcaptcha://", "");
+
         dependencies.getAccountManager().submitRateLimitRecaptchaChallenge(challenge, captcha);
     }
 
@@ -454,7 +464,7 @@ public class ManagerImpl implements Manager {
     }
 
     @Override
-    public void setRegistrationLockPin(java.util.Optional<String> pin) throws IOException, UnauthenticatedResponseException {
+    public void setRegistrationLockPin(java.util.Optional<String> pin) throws IOException {
         if (!account.isMasterDevice()) {
             throw new RuntimeException("Only master device can set a PIN");
         }
@@ -479,7 +489,7 @@ public class ManagerImpl implements Manager {
     }
 
     @Override
-    public Profile getRecipientProfile(RecipientIdentifier.Single recipient) throws UnregisteredUserException {
+    public Profile getRecipientProfile(RecipientIdentifier.Single recipient) throws IOException {
         return profileHelper.getRecipientProfile(resolveRecipient(recipient));
     }
 
@@ -583,13 +593,24 @@ public class ManagerImpl implements Manager {
             if (recipient instanceof RecipientIdentifier.Single single) {
                 final var recipientId = resolveRecipient(single);
                 final var result = sendHelper.sendMessage(messageBuilder, recipientId);
-                results.put(recipient, List.of(result));
+                results.put(recipient,
+                        List.of(SendMessageResult.from(result,
+                                account.getRecipientStore(),
+                                account.getRecipientStore()::resolveRecipientAddress)));
             } else if (recipient instanceof RecipientIdentifier.NoteToSelf) {
                 final var result = sendHelper.sendSelfMessage(messageBuilder);
-                results.put(recipient, List.of(result));
+                results.put(recipient,
+                        List.of(SendMessageResult.from(result,
+                                account.getRecipientStore(),
+                                account.getRecipientStore()::resolveRecipientAddress)));
             } else if (recipient instanceof RecipientIdentifier.Group group) {
-                final var result = sendHelper.sendAsGroupMessage(messageBuilder, group.groupId);
-                results.put(recipient, result);
+                final var result = sendHelper.sendAsGroupMessage(messageBuilder, group.groupId());
+                results.put(recipient,
+                        result.stream()
+                                .map(sendMessageResult -> SendMessageResult.from(sendMessageResult,
+                                        account.getRecipientStore(),
+                                        account.getRecipientStore()::resolveRecipientAddress))
+                                .collect(Collectors.toList()));
             }
         }
         return new SendMessageResults(timestamp, results);
@@ -605,7 +626,7 @@ public class ManagerImpl implements Manager {
                 final var recipientId = resolveRecipient((RecipientIdentifier.Single) recipient);
                 sendHelper.sendTypingMessage(message, recipientId);
             } else if (recipient instanceof RecipientIdentifier.Group) {
-                final var groupId = ((RecipientIdentifier.Group) recipient).groupId;
+                final var groupId = ((RecipientIdentifier.Group) recipient).groupId();
                 final var message = new SignalServiceTypingMessage(action, timestamp, Optional.of(groupId.serialize()));
                 sendHelper.sendGroupTypingMessage(message, groupId);
             }
@@ -706,7 +727,7 @@ public class ManagerImpl implements Manager {
     @Override
     public void setContactName(
             RecipientIdentifier.Single recipient, String name
-    ) throws NotMasterDeviceException, UnregisteredUserException {
+    ) throws NotMasterDeviceException, IOException {
         if (!account.isMasterDevice()) {
             throw new NotMasterDeviceException();
         }
@@ -808,22 +829,22 @@ public class ManagerImpl implements Manager {
         return resolveRecipientTrusted(new SignalServiceAddress(uuid, number));
     }
 
-    private UUID getRegisteredUser(final String number) throws IOException {
-        final Map<String, UUID> uuidMap;
+    private ACI getRegisteredUser(final String number) throws IOException {
+        final Map<String, ACI> aciMap;
         try {
-            uuidMap = getRegisteredUsers(Set.of(number));
+            aciMap = getRegisteredUsers(Set.of(number));
         } catch (NumberFormatException e) {
-            throw new UnregisteredUserException(number, e);
+            throw new IOException(number, e);
         }
-        final var uuid = uuidMap.get(number);
+        final var uuid = aciMap.get(number);
         if (uuid == null) {
-            throw new UnregisteredUserException(number, null);
+            throw new IOException(number, null);
         }
         return uuid;
     }
 
-    private Map<String, UUID> getRegisteredUsers(final Set<String> numbers) throws IOException {
-        final Map<String, UUID> registeredUsers;
+    private Map<String, ACI> getRegisteredUsers(final Set<String> numbers) throws IOException {
+        final Map<String, ACI> registeredUsers;
         try {
             registeredUsers = dependencies.getAccountManager()
                     .getRegisteredUsers(ServiceConfig.getIasKeyStore(),
@@ -833,8 +854,8 @@ public class ManagerImpl implements Manager {
             throw new IOException(e);
         }
 
-        // Store numbers as recipients so we have the number/uuid association
-        registeredUsers.forEach((number, uuid) -> resolveRecipientTrusted(new SignalServiceAddress(uuid, number)));
+        // Store numbers as recipients, so we have the number/uuid association
+        registeredUsers.forEach((number, aci) -> resolveRecipientTrusted(new SignalServiceAddress(aci, number)));
 
         return registeredUsers;
     }
@@ -887,14 +908,17 @@ public class ManagerImpl implements Manager {
     }
 
     @Override
-    public void addReceiveHandler(final ReceiveMessageHandler handler) {
+    public void addReceiveHandler(final ReceiveMessageHandler handler, final boolean isWeakListener) {
         if (isReceivingSynchronous) {
             throw new IllegalStateException("Already receiving message synchronously.");
         }
         synchronized (messageHandlers) {
-            messageHandlers.add(handler);
-
-            startReceiveThreadIfRequired();
+            if (isWeakListener) {
+                weakHandlers.add(handler);
+            } else {
+                messageHandlers.add(handler);
+                startReceiveThreadIfRequired();
+            }
         }
     }
 
@@ -903,17 +927,18 @@ public class ManagerImpl implements Manager {
             return;
         }
         receiveThread = new Thread(() -> {
+            logger.debug("Starting receiving messages");
             while (!Thread.interrupted()) {
                 try {
-                    receiveMessagesInternal(1L, TimeUnit.HOURS, false, (envelope, decryptedContent, e) -> {
+                    receiveMessagesInternal(1L, TimeUnit.HOURS, false, (envelope, e) -> {
                         synchronized (messageHandlers) {
-                            for (ReceiveMessageHandler h : messageHandlers) {
+                            Stream.concat(messageHandlers.stream(), weakHandlers.stream()).forEach(h -> {
                                 try {
-                                    h.handleMessage(envelope, decryptedContent, e);
+                                    h.handleMessage(envelope, e);
                                 } catch (Exception ex) {
                                     logger.warn("Message handler failed, ignoring", ex);
                                 }
-                            }
+                            });
                         }
                     });
                     break;
@@ -921,12 +946,14 @@ public class ManagerImpl implements Manager {
                     logger.warn("Receiving messages failed, retrying", e);
                 }
             }
+            logger.debug("Finished receiving messages");
             hasCaughtUpWithOldMessages = false;
             synchronized (messageHandlers) {
                 receiveThread = null;
 
                 // Check if in the meantime another handler has been registered
                 if (!messageHandlers.isEmpty()) {
+                    logger.debug("Another handler has been registered, starting receive thread again");
                     startReceiveThreadIfRequired();
                 }
             }
@@ -939,12 +966,13 @@ public class ManagerImpl implements Manager {
     public void removeReceiveHandler(final ReceiveMessageHandler handler) {
         final Thread thread;
         synchronized (messageHandlers) {
-            thread = receiveThread;
-            receiveThread = null;
+            weakHandlers.remove(handler);
             messageHandlers.remove(handler);
-            if (!messageHandlers.isEmpty() || isReceivingSynchronous) {
+            if (!messageHandlers.isEmpty() || receiveThread == null || isReceivingSynchronous) {
                 return;
             }
+            thread = receiveThread;
+            receiveThread = null;
         }
 
         stopReceiveThread(thread);
@@ -1000,7 +1028,8 @@ public class ManagerImpl implements Manager {
     ) throws IOException {
         retryFailedReceivedMessages(handler);
 
-        Set<HandleAction> queuedActions = new HashSet<>();
+        // Use a Map here because java Set doesn't have a get method ...
+        Map<HandleAction, HandleAction> queuedActions = new HashMap<>();
 
         final var signalWebSocket = dependencies.getSignalWebSocket();
         signalWebSocket.connect();
@@ -1029,7 +1058,7 @@ public class ManagerImpl implements Manager {
                     logger.debug("New message received from server");
                 } else {
                     logger.debug("Received indicator that server queue is empty");
-                    handleQueuedActions(queuedActions);
+                    handleQueuedActions(queuedActions.keySet());
                     queuedActions.clear();
 
                     hasCaughtUpWithOldMessages = true;
@@ -1070,11 +1099,18 @@ public class ManagerImpl implements Manager {
             }
 
             final var result = incomingMessageHandler.handleEnvelope(envelope, ignoreAttachments, handler);
-            queuedActions.addAll(result.first());
+            for (final var h : result.first()) {
+                final var existingAction = queuedActions.get(h);
+                if (existingAction == null) {
+                    queuedActions.put(h, h);
+                } else {
+                    existingAction.mergeOther(h);
+                }
+            }
             final var exception = result.second();
 
             if (hasCaughtUpWithOldMessages) {
-                handleQueuedActions(queuedActions);
+                handleQueuedActions(queuedActions.keySet());
                 queuedActions.clear();
             }
             if (cachedMessage[0] != null) {
@@ -1095,8 +1131,9 @@ public class ManagerImpl implements Manager {
                 }
             }
         }
-        handleQueuedActions(queuedActions);
+        handleQueuedActions(queuedActions.keySet());
         queuedActions.clear();
+        dependencies.getSignalWebSocket().disconnect();
     }
 
     @Override
@@ -1134,17 +1171,12 @@ public class ManagerImpl implements Manager {
         final RecipientId recipientId;
         try {
             recipientId = resolveRecipient(recipient);
-        } catch (UnregisteredUserException e) {
+        } catch (IOException e) {
             return false;
         }
         return contactHelper.isContactBlocked(recipientId);
     }
 
-    @Override
-    public File getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId) {
-        return attachmentHelper.getAttachmentFile(attachmentId);
-    }
-
     @Override
     public void sendContacts() throws IOException {
         syncHelper.sendContacts();
@@ -1164,7 +1196,7 @@ public class ManagerImpl implements Manager {
         final RecipientId recipientId;
         try {
             recipientId = resolveRecipient(recipient);
-        } catch (UnregisteredUserException e) {
+        } catch (IOException e) {
             return null;
         }
 
@@ -1220,7 +1252,7 @@ public class ManagerImpl implements Manager {
         IdentityInfo identity;
         try {
             identity = account.getIdentityKeyStore().getIdentity(resolveRecipient(recipient));
-        } catch (UnregisteredUserException e) {
+        } catch (IOException e) {
             identity = null;
         }
         return identity == null ? List.of() : List.of(toIdentity(identity));
@@ -1237,7 +1269,7 @@ public class ManagerImpl implements Manager {
         RecipientId recipientId;
         try {
             recipientId = resolveRecipient(recipient);
-        } catch (UnregisteredUserException e) {
+        } catch (IOException e) {
             return false;
         }
         return identityHelper.trustIdentityVerified(recipientId, fingerprint);
@@ -1254,7 +1286,7 @@ public class ManagerImpl implements Manager {
         RecipientId recipientId;
         try {
             recipientId = resolveRecipient(recipient);
-        } catch (UnregisteredUserException e) {
+        } catch (IOException e) {
             return false;
         }
         return identityHelper.trustIdentityVerifiedSafetyNumber(recipientId, safetyNumber);
@@ -1271,7 +1303,7 @@ public class ManagerImpl implements Manager {
         RecipientId recipientId;
         try {
             recipientId = resolveRecipient(recipient);
-        } catch (UnregisteredUserException e) {
+        } catch (IOException e) {
             return false;
         }
         return identityHelper.trustIdentityVerifiedSafetyNumber(recipientId, safetyNumber);
@@ -1287,23 +1319,19 @@ public class ManagerImpl implements Manager {
         RecipientId recipientId;
         try {
             recipientId = resolveRecipient(recipient);
-        } catch (UnregisteredUserException e) {
+        } catch (IOException e) {
             return false;
         }
         return identityHelper.trustIdentityAllKeys(recipientId);
     }
 
     private void handleIdentityFailure(
-            final RecipientId recipientId, final SendMessageResult.IdentityFailure identityFailure
+            final RecipientId recipientId,
+            final org.whispersystems.signalservice.api.messages.SendMessageResult.IdentityFailure identityFailure
     ) {
         this.identityHelper.handleIdentityFailure(recipientId, identityFailure);
     }
 
-    @Override
-    public SignalServiceAddress resolveSignalServiceAddress(SignalServiceAddress address) {
-        return resolveSignalServiceAddress(resolveRecipient(address));
-    }
-
     private SignalServiceAddress resolveSignalServiceAddress(RecipientId recipientId) {
         final var address = account.getRecipientStore().resolveRecipientAddress(recipientId);
         if (address.getUuid().isPresent()) {
@@ -1313,18 +1341,18 @@ public class ManagerImpl implements Manager {
         // Address in recipient store doesn't have a uuid, this shouldn't happen
         // Try to retrieve the uuid from the server
         final var number = address.getNumber().get();
-        final UUID uuid;
+        final ACI aci;
         try {
-            uuid = getRegisteredUser(number);
+            aci = getRegisteredUser(number);
         } catch (IOException e) {
             logger.warn("Failed to get uuid for e164 number: {}", number, e);
             // Return SignalServiceAddress with unknown UUID
             return address.toSignalServiceAddress();
         }
-        return resolveSignalServiceAddress(account.getRecipientStore().resolveRecipient(uuid));
+        return resolveSignalServiceAddress(account.getRecipientStore().resolveRecipient(aci));
     }
 
-    private Set<RecipientId> resolveRecipients(Collection<RecipientIdentifier.Single> recipients) throws UnregisteredUserException {
+    private Set<RecipientId> resolveRecipients(Collection<RecipientIdentifier.Single> recipients) throws IOException {
         final var recipientIds = new HashSet<RecipientId>(recipients.size());
         for (var number : recipients) {
             final var recipientId = resolveRecipient(number);
@@ -1333,11 +1361,11 @@ public class ManagerImpl implements Manager {
         return recipientIds;
     }
 
-    private RecipientId resolveRecipient(final RecipientIdentifier.Single recipient) throws UnregisteredUserException {
-        if (recipient instanceof RecipientIdentifier.Uuid) {
-            return account.getRecipientStore().resolveRecipient(((RecipientIdentifier.Uuid) recipient).uuid);
+    private RecipientId resolveRecipient(final RecipientIdentifier.Single recipient) throws IOException {
+        if (recipient instanceof RecipientIdentifier.Uuid uuidRecipient) {
+            return account.getRecipientStore().resolveRecipient(ACI.from(uuidRecipient.uuid()));
         } else {
-            final var number = ((RecipientIdentifier.Number) recipient).number;
+            final var number = ((RecipientIdentifier.Number) recipient).number();
             return account.getRecipientStore().resolveRecipient(number, () -> {
                 try {
                     return getRegisteredUser(number);
@@ -1348,6 +1376,10 @@ public class ManagerImpl implements Manager {
         }
     }
 
+    private RecipientId resolveRecipient(RecipientAddress address) {
+        return account.getRecipientStore().resolveRecipient(address);
+    }
+
     private RecipientId resolveRecipient(SignalServiceAddress address) {
         return account.getRecipientStore().resolveRecipient(address);
     }
@@ -1364,6 +1396,7 @@ public class ManagerImpl implements Manager {
     private void close(boolean closeAccount) throws IOException {
         Thread thread;
         synchronized (messageHandlers) {
+            weakHandlers.clear();
             messageHandlers.clear();
             thread = receiveThread;
             receiveThread = null;