]> nmode's Git Repositories - signal-cli/blobdiff - src/main/java/org/asamk/signal/Manager.java
Update gradle wrapper
[signal-cli] / src / main / java / org / asamk / signal / Manager.java
index 5bff3cf3fa009d90d64635428c5c02e856f13d8c..6295f730bd6aab4a83259a2228daaaf4d1a03ec9 100644 (file)
@@ -79,7 +79,7 @@ class Manager implements Signal {
 
     private final ObjectMapper jsonProcessot = new ObjectMapper();
     private String username;
-    int deviceId = SignalServiceAddress.DEFAULT_DEVICE_ID;
+    private int deviceId = SignalServiceAddress.DEFAULT_DEVICE_ID;
     private String password;
     private String signalingKey;
     private int preKeyIdOffset;
@@ -90,6 +90,7 @@ class Manager implements Signal {
     private SignalProtocolStore signalProtocolStore;
     private SignalServiceAccountManager accountManager;
     private JsonGroupStore groupStore;
+    private JsonContactsStore contactStore;
 
     public Manager(String username, String settingsPath) {
         this.username = username;
@@ -107,6 +108,10 @@ class Manager implements Signal {
         return username;
     }
 
+    public int getDeviceId() {
+        return deviceId;
+    }
+
     public String getFileName() {
         new File(dataPath).mkdirs();
         return dataPath + "/" + username;
@@ -164,6 +169,14 @@ class Manager implements Signal {
         if (groupStore == null) {
             groupStore = new JsonGroupStore();
         }
+        JsonNode contactStoreNode = rootNode.get("contactStore");
+        if (contactStoreNode != null) {
+            contactStore = jsonProcessot.convertValue(contactStoreNode, JsonContactsStore.class);
+        }
+        if (contactStore == null) {
+            contactStore = new JsonContactsStore();
+        }
+
         accountManager = new SignalServiceAccountManager(URL, TRUST_STORE, username, password, deviceId, USER_AGENT);
         try {
             if (registered && accountManager.getPreKeysCount() < PREKEY_MINIMUM_COUNT) {
@@ -176,6 +189,9 @@ class Manager implements Signal {
     }
 
     private void save() {
+        if (username == null) {
+            return;
+        }
         ObjectNode rootNode = jsonProcessot.createObjectNode();
         rootNode.put("username", username)
                 .put("deviceId", deviceId)
@@ -186,6 +202,7 @@ class Manager implements Signal {
                 .put("registered", registered)
                 .putPOJO("axolotlStore", signalProtocolStore)
                 .putPOJO("groupStore", groupStore)
+                .putPOJO("contactStore", contactStore)
         ;
         try {
             jsonProcessot.writeValue(new File(getFileName()), rootNode);
@@ -256,6 +273,13 @@ class Manager implements Signal {
         save();
     }
 
+    public List<DeviceInfo> getLinkedDevices() throws IOException {
+        return accountManager.getDevices();
+    }
+
+    public void removeLinkedDevices(int deviceId) throws IOException {
+        accountManager.removeDevice(deviceId);
+    }
 
     public static Map<String, String> getQueryMap(String query) {
         String[] params = query.split("&");
@@ -279,7 +303,7 @@ class Manager implements Signal {
     }
 
     public void addDeviceLink(URI linkUri) throws IOException, InvalidKeyException {
-        Map<String, String> query = getQueryMap(linkUri.getQuery());
+        Map<String, String> query = getQueryMap(linkUri.getRawQuery());
         String deviceIdentifier = query.get("uuid");
         String publicKeyEncoded = query.get("pub_key");
 
@@ -289,10 +313,10 @@ class Manager implements Signal {
 
         ECPublicKey deviceKey = Curve.decodePoint(Base64.decode(publicKeyEncoded), 0);
 
-        addDeviceLink(deviceIdentifier, deviceKey);
+        addDevice(deviceIdentifier, deviceKey);
     }
 
-    private void addDeviceLink(String deviceIdentifier, ECPublicKey deviceKey) throws IOException, InvalidKeyException {
+    private void addDevice(String deviceIdentifier, ECPublicKey deviceKey) throws IOException, InvalidKeyException {
         IdentityKeyPair identityKeyPair = signalProtocolStore.getIdentityKeyPair();
         String verificationCode = accountManager.getNewDeviceVerificationCode();
 
@@ -411,7 +435,9 @@ class Manager implements Signal {
         }
         SignalServiceDataMessage message = messageBuilder.build();
 
-        sendMessage(message, groupStore.getGroup(groupId).members);
+        Set<String> members = groupStore.getGroup(groupId).members;
+        members.remove(this.username);
+        sendMessage(message, members);
     }
 
     public void sendQuitGroupMessage(byte[] groupId) throws GroupNotFoundException, IOException, EncapsulatedExceptions, UntrustedIdentityException {
@@ -423,7 +449,11 @@ class Manager implements Signal {
                 .asGroupMessage(group)
                 .build();
 
-        sendMessage(message, groupStore.getGroup(groupId).members);
+        final GroupInfo g = groupStore.getGroup(groupId);
+        g.members.remove(this.username);
+        groupStore.updateGroup(g);
+
+        sendMessage(message, g.members);
     }
 
     public byte[] sendUpdateGroupMessage(byte[] groupId, String name, Collection<String> members, String avatarFile) throws IOException, EncapsulatedExceptions, GroupNotFoundException, AttachmentInvalidException, UntrustedIdentityException {
@@ -473,7 +503,9 @@ class Manager implements Signal {
                 .asGroupMessage(group.build())
                 .build();
 
-        sendMessage(message, g.members);
+        final Set<String> membersSend = g.members;
+        membersSend.remove(this.username);
+        sendMessage(message, membersSend);
         return g.groupId;
     }
 
@@ -540,36 +572,39 @@ class Manager implements Signal {
 
     private void sendMessage(SignalServiceDataMessage message, Collection<String> recipients)
             throws IOException, EncapsulatedExceptions, UntrustedIdentityException {
-        SignalServiceMessageSender messageSender = new SignalServiceMessageSender(URL, TRUST_STORE, username, password,
-                deviceId, signalProtocolStore, USER_AGENT, Optional.<SignalServiceMessageSender.EventListener>absent());
+        try {
+            SignalServiceMessageSender messageSender = new SignalServiceMessageSender(URL, TRUST_STORE, username, password,
+                    deviceId, signalProtocolStore, USER_AGENT, Optional.<SignalServiceMessageSender.EventListener>absent());
 
-        Set<SignalServiceAddress> recipientsTS = new HashSet<>(recipients.size());
-        for (String recipient : recipients) {
-            try {
-                recipientsTS.add(getPushAddress(recipient));
-            } catch (InvalidNumberException e) {
-                System.err.println("Failed to add recipient \"" + recipient + "\": " + e.getMessage());
-                System.err.println("Aborting sending.");
-                save();
-                return;
+            Set<SignalServiceAddress> recipientsTS = new HashSet<>(recipients.size());
+            for (String recipient : recipients) {
+                try {
+                    recipientsTS.add(getPushAddress(recipient));
+                } catch (InvalidNumberException e) {
+                    System.err.println("Failed to add recipient \"" + recipient + "\": " + e.getMessage());
+                    System.err.println("Aborting sending.");
+                    save();
+                    return;
+                }
             }
-        }
 
-        if (message.getGroupInfo().isPresent()) {
-            messageSender.sendMessage(new ArrayList<>(recipientsTS), message);
-        } else {
-            // Send to all individually, so sync messages are sent correctly
-            for (SignalServiceAddress address : recipientsTS) {
-                messageSender.sendMessage(address, message);
+            if (message.getGroupInfo().isPresent()) {
+                messageSender.sendMessage(new ArrayList<>(recipientsTS), message);
+            } else {
+                // Send to all individually, so sync messages are sent correctly
+                for (SignalServiceAddress address : recipientsTS) {
+                    messageSender.sendMessage(address, message);
+                }
             }
-        }
 
-        if (message.isEndSession()) {
-            for (SignalServiceAddress recipient : recipientsTS) {
-                handleEndSession(recipient.getNumber());
+            if (message.isEndSession()) {
+                for (SignalServiceAddress recipient : recipientsTS) {
+                    handleEndSession(recipient.getNumber());
+                }
             }
+        } finally {
+            save();
         }
-        save();
     }
 
     private SignalServiceContent decryptMessage(SignalServiceEnvelope envelope) {
@@ -637,6 +672,7 @@ class Manager implements Signal {
                     try {
                         group = groupStore.getGroup(groupInfo.getGroupId());
                         group.members.remove(source);
+                        groupStore.updateGroup(group);
                     } catch (GroupNotFoundException e) {
                     }
                     break;
@@ -688,7 +724,13 @@ class Manager implements Signal {
                                 if (syncMessage.getRequest().isPresent()) {
                                     RequestMessage rm = syncMessage.getRequest().get();
                                     if (rm.isContactsRequest()) {
-                                        // TODO implement when we have contacts
+                                        try {
+                                            sendContacts();
+                                        } catch (EncapsulatedExceptions encapsulatedExceptions) {
+                                            encapsulatedExceptions.printStackTrace();
+                                        } catch (UntrustedIdentityException e) {
+                                            e.printStackTrace();
+                                        }
                                     }
                                     if (rm.isGroupsRequest()) {
                                         try {
@@ -733,11 +775,12 @@ class Manager implements Signal {
                                         DeviceContactsInputStream s = new DeviceContactsInputStream(retrieveAttachmentAsStream(syncMessage.getContacts().get().asPointer()));
                                         DeviceContact c;
                                         while ((c = s.read()) != null) {
-                                            // TODO implement when we have contact storage
+                                            ContactInfo contact = new ContactInfo();
+                                            contact.number = c.getNumber();
                                             if (c.getName().isPresent()) {
-                                                c.getName().get();
+                                                contact.name = c.getName().get();
                                             }
-                                            c.getNumber();
+                                            contactStore.updateContact(contact);
 
                                             if (c.getAvatar().isPresent()) {
                                                 byte[] ava = new byte[(int) c.getAvatar().get().getLength()];
@@ -842,20 +885,49 @@ class Manager implements Signal {
     }
 
     private void sendGroups() throws IOException, EncapsulatedExceptions, UntrustedIdentityException {
-        File contactsFile = File.createTempFile("multidevice-contact-update", ".tmp");
+        File groupsFile = File.createTempFile("multidevice-group-update", ".tmp");
 
         try {
-            DeviceGroupsOutputStream out = new DeviceGroupsOutputStream(new FileOutputStream(contactsFile));
+            DeviceGroupsOutputStream out = new DeviceGroupsOutputStream(new FileOutputStream(groupsFile));
             try {
                 for (GroupInfo record : groupStore.getGroups()) {
                     out.write(new DeviceGroup(record.groupId, Optional.fromNullable(record.name),
-                            new ArrayList<>(record.members), Optional.of(new SignalServiceAttachmentStream(new FileInputStream("/home/sebastian/Bilder/00026_150512_14-00-18.JPG"), "octet", new File("/home/sebastian/Bilder/00026_150512_14-00-18.JPG").length(), null)),
+                            new ArrayList<>(record.members), Optional.<SignalServiceAttachmentStream>absent(), // TODO
                             record.active));
                 }
             } finally {
                 out.close();
             }
 
+            if (groupsFile.exists() && groupsFile.length() > 0) {
+                FileInputStream contactsFileStream = new FileInputStream(groupsFile);
+                SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
+                        .withStream(contactsFileStream)
+                        .withContentType("application/octet-stream")
+                        .withLength(groupsFile.length())
+                        .build();
+
+                sendMessage(SignalServiceSyncMessage.forGroups(attachmentStream));
+            }
+        } finally {
+            groupsFile.delete();
+        }
+    }
+
+    private void sendContacts() throws IOException, EncapsulatedExceptions, UntrustedIdentityException {
+        File contactsFile = File.createTempFile("multidevice-contact-update", ".tmp");
+
+        try {
+            DeviceContactsOutputStream out = new DeviceContactsOutputStream(new FileOutputStream(contactsFile));
+            try {
+                for (ContactInfo record : contactStore.getContacts()) {
+                    out.write(new DeviceContact(record.number, Optional.fromNullable(record.name),
+                            Optional.<SignalServiceAttachmentStream>absent())); // TODO
+                }
+            } finally {
+                out.close();
+            }
+
             if (contactsFile.exists() && contactsFile.length() > 0) {
                 FileInputStream contactsFileStream = new FileInputStream(contactsFile);
                 SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
@@ -864,10 +936,10 @@ class Manager implements Signal {
                         .withLength(contactsFile.length())
                         .build();
 
-                sendMessage(SignalServiceSyncMessage.forGroups(attachmentStream));
+                sendMessage(SignalServiceSyncMessage.forContacts(attachmentStream));
             }
         } finally {
-            if (contactsFile != null) contactsFile.delete();
+            contactsFile.delete();
         }
     }
 }