]> nmode's Git Repositories - signal-cli/blobdiff - src/main/java/org/asamk/signal/manager/Manager.java
Update gradle wrapper
[signal-cli] / src / main / java / org / asamk / signal / manager / Manager.java
index 04bef98ea82160176e8bfa213e5d04ff5be6e874..590610681b81d7409138d5f2ef4c75c26f2851bb 100644 (file)
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2015-2018 AsamK
+  Copyright (C) 2015-2020 AsamK and contributors
 
   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
@@ -53,6 +53,7 @@ import org.whispersystems.libsignal.state.PreKeyRecord;
 import org.whispersystems.libsignal.state.SignedPreKeyRecord;
 import org.whispersystems.libsignal.util.KeyHelper;
 import org.whispersystems.libsignal.util.Medium;
+import org.whispersystems.libsignal.util.Pair;
 import org.whispersystems.libsignal.util.guava.Optional;
 import org.whispersystems.signalservice.api.SignalServiceAccountManager;
 import org.whispersystems.signalservice.api.SignalServiceMessagePipe;
@@ -70,6 +71,7 @@ import org.whispersystems.signalservice.api.messages.SignalServiceContent;
 import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage;
 import org.whispersystems.signalservice.api.messages.SignalServiceEnvelope;
 import org.whispersystems.signalservice.api.messages.SignalServiceGroup;
+import org.whispersystems.signalservice.api.messages.multidevice.BlockedListMessage;
 import org.whispersystems.signalservice.api.messages.multidevice.ContactsMessage;
 import org.whispersystems.signalservice.api.messages.multidevice.DeviceContact;
 import org.whispersystems.signalservice.api.messages.multidevice.DeviceContactsInputStream;
@@ -647,7 +649,20 @@ public class Manager implements Signal {
             throws IOException, EncapsulatedExceptions, AttachmentInvalidException {
         final SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder().withBody(messageText);
         if (attachments != null) {
-            messageBuilder.withAttachments(Utils.getSignalServiceAttachments(attachments));
+            List<SignalServiceAttachment> attachmentStreams = Utils.getSignalServiceAttachments(attachments);
+
+            // Upload attachments here, so we only upload once even for multiple recipients
+            SignalServiceMessageSender messageSender = getMessageSender();
+            List<SignalServiceAttachment> attachmentPointers = new ArrayList<>(attachmentStreams.size());
+            for (SignalServiceAttachment attachment : attachmentStreams) {
+                if (attachment.isStream()) {
+                    attachmentPointers.add(messageSender.uploadAttachment(attachment.asStream()));
+                } else if (attachment.isPointer()) {
+                    attachmentPointers.add(attachment.asPointer());
+                }
+            }
+
+            messageBuilder.withAttachments(attachmentPointers);
         }
         messageBuilder.withProfileKey(account.getProfileKey());
         sendMessageLegacy(messageBuilder, recipients);
@@ -662,8 +677,9 @@ public class Manager implements Signal {
     }
 
     @Override
-    public String getContactName(String number) {
-        ContactInfo contact = account.getContactStore().getContact(number);
+    public String getContactName(String number) throws InvalidNumberException {
+        String canonicalizedNumber = Utils.canonicalizeNumber(number, username);
+        ContactInfo contact = account.getContactStore().getContact(canonicalizedNumber);
         if (contact == null) {
             return "";
         } else {
@@ -672,20 +688,50 @@ public class Manager implements Signal {
     }
 
     @Override
-    public void setContactName(String number, String name) {
+    public void setContactName(String number, String name) throws InvalidNumberException {
+        String canonicalizedNumber = Utils.canonicalizeNumber(number, username);
+        ContactInfo contact = account.getContactStore().getContact(canonicalizedNumber);
+        if (contact == null) {
+            contact = new ContactInfo();
+            contact.number = canonicalizedNumber;
+            System.err.println("Add contact " + canonicalizedNumber + " named " + name);
+        } else {
+            System.err.println("Updating contact " + canonicalizedNumber + " name " + contact.name + " -> " + name);
+        }
+        contact.name = name;
+        account.getContactStore().updateContact(contact);
+        account.save();
+    }
+
+    @Override
+    public void setContactBlocked(String number, boolean blocked) throws InvalidNumberException {
+        number = Utils.canonicalizeNumber(number, username);
         ContactInfo contact = account.getContactStore().getContact(number);
         if (contact == null) {
             contact = new ContactInfo();
             contact.number = number;
-            System.err.println("Add contact " + number + " named " + name);
+            System.err.println("Adding and " + (blocked ? "blocking" : "unblocking") + " contact " + number);
         } else {
-            System.err.println("Updating contact " + number + " name " + contact.name + " -> " + name);
+            System.err.println((blocked ? "Blocking" : "Unblocking") + " contact " + number);
         }
-        contact.name = name;
+        contact.blocked = blocked;
         account.getContactStore().updateContact(contact);
         account.save();
     }
 
+    @Override
+    public void setGroupBlocked(final byte[] groupId, final boolean blocked) throws GroupNotFoundException {
+        GroupInfo group = getGroup(groupId);
+        if (group == null) {
+            throw new GroupNotFoundException(groupId);
+        } else {
+            System.err.println((blocked ? "Blocking" : "Unblocking") + " group " + Base64.encodeBytes(groupId));
+            group.blocked = blocked;
+            account.getGroupStore().updateGroup(group);
+            account.save();
+        }
+    }
+
     @Override
     public List<byte[]> getGroupIds() {
         List<GroupInfo> groups = getGroups();
@@ -1049,6 +1095,19 @@ public class Manager implements Signal {
             }
             contact.profileKey = Base64.encodeBytes(message.getProfileKey().get());
         }
+        if (message.getPreviews().isPresent()) {
+            final List<SignalServiceDataMessage.Preview> previews = message.getPreviews().get();
+            for (SignalServiceDataMessage.Preview preview : previews) {
+                if (preview.getImage().isPresent() && preview.getImage().get().isPointer()) {
+                    SignalServiceAttachmentPointer attachment = preview.getImage().get().asPointer();
+                    try {
+                        retrieveAttachment(attachment);
+                    } catch (IOException | InvalidMessageException e) {
+                        System.err.println("Failed to retrieve attachment (" + attachment.getId() + "): " + e.getMessage());
+                    }
+                }
+            }
+        }
     }
 
     private void retryFailedReceivedMessages(ReceiveMessageHandler handler, boolean ignoreAttachments) {
@@ -1141,7 +1200,9 @@ public class Manager implements Signal {
                     handleMessage(envelope, content, ignoreAttachments);
                 }
                 account.save();
-                handler.handleMessage(envelope, content, exception);
+                if (!isMessageBlocked(envelope, content)) {
+                    handler.handleMessage(envelope, content, exception);
+                }
                 if (!(exception instanceof ProtocolUntrustedIdentityException)) {
                     File cacheFile = null;
                     try {
@@ -1162,6 +1223,33 @@ public class Manager implements Signal {
         }
     }
 
+    private boolean isMessageBlocked(SignalServiceEnvelope envelope, SignalServiceContent content) {
+        SignalServiceAddress source;
+        if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
+            source = envelope.getSourceAddress();
+        } else if (content != null) {
+            source = content.getSender();
+        } else {
+            return false;
+        }
+        ContactInfo sourceContact = getContact(source.getNumber().get());
+        if (sourceContact != null && sourceContact.blocked) {
+            return true;
+        }
+
+        if (content != null && content.getDataMessage().isPresent()) {
+            SignalServiceDataMessage message = content.getDataMessage().get();
+            if (message.getGroupInfo().isPresent()) {
+                SignalServiceGroup groupInfo = message.getGroupInfo().get();
+                GroupInfo group = getGroup(groupInfo.getGroupId());
+                if (groupInfo.getType() == SignalServiceGroup.Type.DELIVER && group != null && group.blocked) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
     private void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, boolean ignoreAttachments) {
         if (content != null) {
             SignalServiceAddress sender;
@@ -1197,7 +1285,14 @@ public class Manager implements Signal {
                             e.printStackTrace();
                         }
                     }
-                    // TODO Handle rm.isBlockedListRequest(); rm.isConfigurationRequest();
+                    if (rm.isBlockedListRequest()) {
+                        try {
+                            sendBlockedList();
+                        } catch (UntrustedIdentityException | IOException e) {
+                            e.printStackTrace();
+                        }
+                    }
+                    // TODO Handle rm.isConfigurationRequest();
                 }
                 if (syncMessage.getGroups().isPresent()) {
                     File tmpFile = null;
@@ -1216,6 +1311,7 @@ public class Manager implements Signal {
                                 }
                                 syncGroup.addMembers(g.getMembers());
                                 syncGroup.active = g.isActive();
+                                syncGroup.blocked = g.isBlocked();
                                 if (g.getColor().isPresent()) {
                                     syncGroup.color = g.getColor().get();
                                 }
@@ -1239,7 +1335,23 @@ public class Manager implements Signal {
                     }
                 }
                 if (syncMessage.getBlockedList().isPresent()) {
-                    // TODO store list of blocked numbers
+                    final BlockedListMessage blockedListMessage = syncMessage.getBlockedList().get();
+                    for (SignalServiceAddress address : blockedListMessage.getAddresses()) {
+                        if (address.getNumber().isPresent()) {
+                            try {
+                                setContactBlocked(address.getNumber().get(), true);
+                            } catch (InvalidNumberException e) {
+                                e.printStackTrace();
+                            }
+                        }
+                    }
+                    for (byte[] groupId : blockedListMessage.getGroupIds()) {
+                        try {
+                            setGroupBlocked(groupId, true);
+                        } catch (GroupNotFoundException e) {
+                            System.err.println("BlockedListMessage contained groupID that was not found in GroupStore: " + Base64.encodeBytes(groupId));
+                        }
+                    }
                 }
                 if (syncMessage.getContacts().isPresent()) {
                     File tmpFile = null;
@@ -1283,9 +1395,7 @@ public class Manager implements Signal {
                                     thread.messageExpirationTime = c.getExpirationTimer().get();
                                     account.getThreadStore().updateThread(thread);
                                 }
-                                if (c.isBlocked()) {
-                                    // TODO store list of blocked numbers
-                                }
+                                contact.blocked = c.isBlocked();
                                 account.getContactStore().updateContact(contact);
 
                                 if (c.getAvatar().isPresent()) {
@@ -1413,7 +1523,7 @@ public class Manager implements Signal {
                     out.write(new DeviceGroup(record.groupId, Optional.fromNullable(record.name),
                             new ArrayList<>(record.getMembers()), createGroupAvatarAttachment(record.groupId),
                             record.active, Optional.fromNullable(info != null ? info.messageExpirationTime : null),
-                            Optional.fromNullable(record.color), false));
+                            Optional.fromNullable(record.color), record.blocked));
                 }
             }
 
@@ -1459,11 +1569,10 @@ public class Manager implements Signal {
                     }
 
                     byte[] profileKey = record.profileKey == null ? null : Base64.decode(record.profileKey);
-                    // TODO store list of blocked numbers
-                    boolean blocked = false;
                     out.write(new DeviceContact(record.getAddress(), Optional.fromNullable(record.name),
                             createContactAvatarAttachment(record.number), Optional.fromNullable(record.color),
-                            Optional.fromNullable(verifiedMessage), Optional.fromNullable(profileKey), blocked, Optional.fromNullable(info != null ? info.messageExpirationTime : null)));
+                            Optional.fromNullable(verifiedMessage), Optional.fromNullable(profileKey), record.blocked,
+                            Optional.fromNullable(info != null ? info.messageExpirationTime : null)));
                 }
 
                 if (account.getProfileKey() != null) {
@@ -1496,6 +1605,22 @@ public class Manager implements Signal {
         }
     }
 
+    private void sendBlockedList() throws IOException, UntrustedIdentityException {
+        List<SignalServiceAddress> addresses = new ArrayList<>();
+        for (ContactInfo record : account.getContactStore().getContacts()) {
+            if (record.blocked) {
+                addresses.add(record.getAddress());
+            }
+        }
+        List<byte[]> groupIds = new ArrayList<>();
+        for (GroupInfo record : account.getGroupStore().getGroups()) {
+            if (record.blocked) {
+                groupIds.add(record.groupId);
+            }
+        }
+        sendSyncMessage(SignalServiceSyncMessage.forBlocked(new BlockedListMessage(addresses, groupIds)));
+    }
+
     private void sendVerifiedMessage(SignalServiceAddress destination, IdentityKey identityKey, TrustLevel trustLevel) throws IOException, UntrustedIdentityException {
         VerifiedMessage verifiedMessage = new VerifiedMessage(destination, identityKey, trustLevel.toVerifiedState(), System.currentTimeMillis());
         sendSyncMessage(SignalServiceSyncMessage.forVerified(verifiedMessage));
@@ -1517,8 +1642,9 @@ public class Manager implements Signal {
         return account.getSignalProtocolStore().getIdentities();
     }
 
-    public List<JsonIdentityKeyStore.Identity> getIdentities(String number) {
-        return account.getSignalProtocolStore().getIdentities(number);
+    public Pair<String, List<JsonIdentityKeyStore.Identity>> getIdentities(String number) throws InvalidNumberException {
+        String canonicalizedNumber = Utils.canonicalizeNumber(number, username);
+        return new Pair<>(canonicalizedNumber, account.getSignalProtocolStore().getIdentities(canonicalizedNumber));
     }
 
     /**