private SignalServiceAccountManager accountManager;
private JsonGroupStore groupStore;
private JsonContactsStore contactStore;
+ private JsonThreadStore threadStore;
public Manager(String username, String settingsPath) {
this.username = username;
if (contactStore == null) {
contactStore = new JsonContactsStore();
}
+ JsonNode threadStoreNode = rootNode.get("threadStore");
+ if (threadStoreNode != null) {
+ threadStore = jsonProcessor.convertValue(threadStoreNode, JsonThreadStore.class);
+ }
+ if (threadStore == null) {
+ threadStore = new JsonThreadStore();
+ }
}
private void migrateLegacyConfigs() {
.putPOJO("axolotlStore", signalProtocolStore)
.putPOJO("groupStore", groupStore)
.putPOJO("contactStore", contactStore)
+ .putPOJO("threadStore", threadStore)
;
try {
openFileChannel();
.build();
messageBuilder.asGroupMessage(group);
}
- SignalServiceDataMessage message = messageBuilder.build();
+ ThreadInfo thread = threadStore.getThread(Base64.encodeBytes(groupId));
+ if (thread != null) {
+ messageBuilder.withExpiration(thread.messageExpirationTime);
+ }
final GroupInfo g = getGroupForSending(groupId);
// Don't send group message to ourself
final List<String> membersSend = new ArrayList<>(g.members);
membersSend.remove(this.username);
- sendMessage(message, membersSend);
+ sendMessage(messageBuilder, membersSend);
}
public void sendQuitGroupMessage(byte[] groupId) throws GroupNotFoundException, IOException, EncapsulatedExceptions {
.withId(groupId)
.build();
- SignalServiceDataMessage message = SignalServiceDataMessage.newBuilder()
- .asGroupMessage(group)
- .build();
+ SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
+ .asGroupMessage(group);
final GroupInfo g = getGroupForSending(groupId);
g.members.remove(this.username);
groupStore.updateGroup(g);
- sendMessage(message, g.members);
+ sendMessage(messageBuilder, g.members);
}
private static String join(CharSequence separator, Iterable<? extends CharSequence> list) {
}
}
+ if (avatarFile != null) {
+ createPrivateDirectories(avatarsPath);
+ File aFile = getGroupAvatarFile(g.groupId);
+ Files.copy(Paths.get(avatarFile), aFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
+ }
+
+ groupStore.updateGroup(g);
+
+ SignalServiceDataMessage.Builder messageBuilder = getGroupUpdateMessageBuilder(g);
+
+ // Don't send group message to ourself
+ final List<String> membersSend = new ArrayList<>(g.members);
+ membersSend.remove(this.username);
+ sendMessage(messageBuilder, membersSend);
+ return g.groupId;
+ }
+
+ private void sendUpdateGroupMessage(byte[] groupId, String recipient) throws IOException, EncapsulatedExceptions {
+ if (groupId == null) {
+ return;
+ }
+ GroupInfo g = getGroupForSending(groupId);
+
+ if (!g.members.contains(recipient)) {
+ return;
+ }
+
+ SignalServiceDataMessage.Builder messageBuilder = getGroupUpdateMessageBuilder(g);
+
+ // Send group message only to the recipient who requested it
+ final List<String> membersSend = new ArrayList<>();
+ membersSend.add(recipient);
+ sendMessage(messageBuilder, membersSend);
+ }
+
+ private SignalServiceDataMessage.Builder getGroupUpdateMessageBuilder(GroupInfo g) {
SignalServiceGroup.Builder group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.UPDATE)
.withId(g.groupId)
.withName(g.name)
.withMembers(new ArrayList<>(g.members));
File aFile = getGroupAvatarFile(g.groupId);
- if (avatarFile != null) {
- createPrivateDirectories(avatarsPath);
- Files.copy(Paths.get(avatarFile), aFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
- }
if (aFile.exists()) {
try {
group.withAvatar(createAttachment(aFile));
} catch (IOException e) {
- throw new AttachmentInvalidException(avatarFile, e);
+ throw new AttachmentInvalidException(aFile.toString(), e);
}
}
- groupStore.updateGroup(g);
+ return SignalServiceDataMessage.newBuilder()
+ .asGroupMessage(group.build());
+ }
- SignalServiceDataMessage message = SignalServiceDataMessage.newBuilder()
- .asGroupMessage(group.build())
- .build();
+ private void sendGroupInfoRequest(byte[] groupId, String recipient) throws IOException, EncapsulatedExceptions {
+ if (groupId == null) {
+ return;
+ }
- // Don't send group message to ourself
- final List<String> membersSend = new ArrayList<>(g.members);
- membersSend.remove(this.username);
- sendMessage(message, membersSend);
- return g.groupId;
+ SignalServiceGroup.Builder group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.REQUEST_INFO)
+ .withId(groupId);
+
+ SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
+ .asGroupMessage(group.build());
+
+ // Send group info request message to the recipient who sent us a message with this groupId
+ final List<String> membersSend = new ArrayList<>();
+ membersSend.add(recipient);
+ sendMessage(messageBuilder, membersSend);
}
@Override
if (attachments != null) {
messageBuilder.withAttachments(getSignalServiceAttachments(attachments));
}
- SignalServiceDataMessage message = messageBuilder.build();
-
- sendMessage(message, recipients);
+ sendMessage(messageBuilder, recipients);
}
@Override
public void sendEndSessionMessage(List<String> recipients) throws IOException, EncapsulatedExceptions {
- SignalServiceDataMessage message = SignalServiceDataMessage.newBuilder()
- .asEndSessionMessage()
- .build();
+ SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
+ .asEndSessionMessage();
- sendMessage(message, recipients);
+ sendMessage(messageBuilder, recipients);
}
private void requestSyncGroups() throws IOException {
SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder().setType(SignalServiceProtos.SyncMessage.Request.Type.GROUPS).build();
SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
try {
- sendMessage(message);
+ sendSyncMessage(message);
} catch (UntrustedIdentityException e) {
e.printStackTrace();
}
SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder().setType(SignalServiceProtos.SyncMessage.Request.Type.CONTACTS).build();
SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
try {
- sendMessage(message);
+ sendSyncMessage(message);
} catch (UntrustedIdentityException e) {
e.printStackTrace();
}
}
- private void sendMessage(SignalServiceSyncMessage message)
+ private void sendSyncMessage(SignalServiceSyncMessage message)
throws IOException, UntrustedIdentityException {
SignalServiceMessageSender messageSender = new SignalServiceMessageSender(URL, TRUST_STORE, username, password,
deviceId, signalProtocolStore, USER_AGENT, Optional.<SignalServiceMessageSender.EventListener>absent());
}
}
- private void sendMessage(SignalServiceDataMessage message, Collection<String> recipients)
+ private void sendMessage(SignalServiceDataMessage.Builder messageBuilder, Collection<String> recipients)
throws EncapsulatedExceptions, IOException {
- 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 = getSignalServiceAddresses(recipients);
+ if (recipientsTS == null) return;
+ SignalServiceDataMessage message = null;
try {
SignalServiceMessageSender messageSender = new SignalServiceMessageSender(URL, TRUST_STORE, username, password,
deviceId, signalProtocolStore, USER_AGENT, Optional.<SignalServiceMessageSender.EventListener>absent());
+ message = messageBuilder.build();
if (message.getGroupInfo().isPresent()) {
try {
messageSender.sendMessage(new ArrayList<>(recipientsTS), message);
List<UnregisteredUserException> unregisteredUsers = new LinkedList<>();
List<NetworkFailureException> networkExceptions = new LinkedList<>();
for (SignalServiceAddress address : recipientsTS) {
+ ThreadInfo thread = threadStore.getThread(address.getNumber());
+ if (thread != null) {
+ messageBuilder.withExpiration(thread.messageExpirationTime);
+ } else {
+ messageBuilder.withExpiration(0);
+ }
+ message = messageBuilder.build();
try {
messageSender.sendMessage(address, message);
} catch (UntrustedIdentityException e) {
}
}
} finally {
- if (message.isEndSession()) {
+ if (message != null && message.isEndSession()) {
for (SignalServiceAddress recipient : recipientsTS) {
handleEndSession(recipient.getNumber());
}
}
}
+ private Set<SignalServiceAddress> getSignalServiceAddresses(Collection<String> recipients) {
+ 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 null;
+ }
+ }
+ return recipientsTS;
+ }
+
private SignalServiceContent decryptMessage(SignalServiceEnvelope envelope) throws NoSessionException, LegacyMessageException, InvalidVersionException, InvalidMessageException, DuplicateMessageException, InvalidKeyException, InvalidKeyIdException, org.whispersystems.libsignal.UntrustedIdentityException {
SignalServiceCipher cipher = new SignalServiceCipher(new SignalServiceAddress(username), signalProtocolStore);
try {
}
private void handleSignalServiceDataMessage(SignalServiceDataMessage message, boolean isSync, String source, String destination) {
+ String threadId;
if (message.getGroupInfo().isPresent()) {
SignalServiceGroup groupInfo = message.getGroupInfo().get();
+ threadId = Base64.encodeBytes(groupInfo.getGroupId());
+ GroupInfo group = groupStore.getGroup(groupInfo.getGroupId());
switch (groupInfo.getType()) {
case UPDATE:
- GroupInfo group;
- group = groupStore.getGroup(groupInfo.getGroupId());
if (group == null) {
group = new GroupInfo(groupInfo.getGroupId());
}
groupStore.updateGroup(group);
break;
case DELIVER:
+ if (group == null) {
+ try {
+ sendGroupInfoRequest(groupInfo.getGroupId(), source);
+ } catch (IOException | EncapsulatedExceptions e) {
+ e.printStackTrace();
+ }
+ }
break;
case QUIT:
- group = groupStore.getGroup(groupInfo.getGroupId());
- if (group != null) {
+ if (group == null) {
+ try {
+ sendGroupInfoRequest(groupInfo.getGroupId(), source);
+ } catch (IOException | EncapsulatedExceptions e) {
+ e.printStackTrace();
+ }
+ } else {
group.members.remove(source);
groupStore.updateGroup(group);
}
break;
+ case REQUEST_INFO:
+ if (group != null) {
+ try {
+ sendUpdateGroupMessage(groupInfo.getGroupId(), source);
+ } catch (IOException | EncapsulatedExceptions e) {
+ e.printStackTrace();
+ } catch (NotAGroupMemberException e) {
+ // We have left this group, so don't send a group update message
+ }
+ }
+ break;
+ }
+ } else {
+ if (isSync) {
+ threadId = destination;
+ } else {
+ threadId = source;
}
}
if (message.isEndSession()) {
handleEndSession(isSync ? destination : source);
}
+ if (message.isExpirationUpdate() || message.getBody().isPresent()) {
+ ThreadInfo thread = threadStore.getThread(threadId);
+ if (thread == null) {
+ thread = new ThreadInfo();
+ thread.id = threadId;
+ }
+ if (thread.messageExpirationTime != message.getExpiresInSeconds()) {
+ thread.messageExpirationTime = message.getExpiresInSeconds();
+ threadStore.updateThread(thread);
+ }
+ }
if (message.getAttachments().isPresent()) {
for (SignalServiceAttachment attachment : message.getAttachments().get()) {
if (attachment.isPointer()) {
continue;
}
- String sender = dir.getName();
for (final File fileEntry : dir.listFiles()) {
if (!fileEntry.isFile()) {
continue;
}
save();
handler.handleMessage(envelope, content, null);
- fileEntry.delete();
+ try {
+ Files.delete(fileEntry.toPath());
+ } catch (IOException e) {
+ System.out.println("Failed to delete cached message file “" + fileEntry + "”: " + e.getMessage());
+ }
}
}
}
- public void receiveMessages(int timeoutSeconds, boolean returnOnTimeout, ReceiveMessageHandler handler) throws IOException {
+ public void receiveMessages(long timeout, TimeUnit unit, boolean returnOnTimeout, ReceiveMessageHandler handler) throws IOException {
retryFailedReceivedMessages(handler);
final SignalServiceMessageReceiver messageReceiver = new SignalServiceMessageReceiver(URL, TRUST_STORE, username, password, deviceId, signalingKey, USER_AGENT);
SignalServiceMessagePipe messagePipe = null;
Exception exception = null;
final long now = new Date().getTime();
try {
- envelope = messagePipe.read(timeoutSeconds, TimeUnit.SECONDS, new SignalServiceMessagePipe.MessagePipeCallback() {
+ envelope = messagePipe.read(timeout, unit, new SignalServiceMessagePipe.MessagePipeCallback() {
@Override
public void onMessage(SignalServiceEnvelope envelope) {
// store message on disk, before acknowledging receipt to the server
save();
handler.handleMessage(envelope, content, exception);
if (exception == null || !(exception instanceof org.whispersystems.libsignal.UntrustedIdentityException)) {
+ File cacheFile = null;
try {
- File cacheFile = getMessageCacheFile(envelope.getSource(), now, envelope.getTimestamp());
- cacheFile.delete();
+ cacheFile = getMessageCacheFile(envelope.getSource(), now, envelope.getTimestamp());
+ Files.delete(cacheFile.toPath());
} catch (IOException e) {
- // Ignoring
- return;
+ System.out.println("Failed to delete cached message file “" + cacheFile + "”: " + e.getMessage());
}
}
}
}
}
if (syncMessage.getGroups().isPresent()) {
+ File tmpFile = null;
try {
- DeviceGroupsInputStream s = new DeviceGroupsInputStream(retrieveAttachmentAsStream(syncMessage.getGroups().get().asPointer()));
+ tmpFile = Util.createTempFile();
+ DeviceGroupsInputStream s = new DeviceGroupsInputStream(retrieveAttachmentAsStream(syncMessage.getGroups().get().asPointer(), tmpFile));
DeviceGroup g;
while ((g = s.read()) != null) {
GroupInfo syncGroup = groupStore.getGroup(g.getId());
}
} catch (Exception e) {
e.printStackTrace();
+ } finally {
+ if (tmpFile != null) {
+ try {
+ Files.delete(tmpFile.toPath());
+ } catch (IOException e) {
+ System.out.println("Failed to delete temp file “" + tmpFile + "”: " + e.getMessage());
+ }
+ }
}
if (syncMessage.getBlockedList().isPresent()) {
// TODO store list of blocked numbers
}
}
if (syncMessage.getContacts().isPresent()) {
+ File tmpFile = null;
try {
- DeviceContactsInputStream s = new DeviceContactsInputStream(retrieveAttachmentAsStream(syncMessage.getContacts().get().asPointer()));
+ tmpFile = Util.createTempFile();
+ DeviceContactsInputStream s = new DeviceContactsInputStream(retrieveAttachmentAsStream(syncMessage.getContacts().get().asPointer(), tmpFile));
DeviceContact c;
while ((c = s.read()) != null) {
ContactInfo contact = contactStore.getContact(c.getNumber());
}
} catch (Exception e) {
e.printStackTrace();
+ } finally {
+ if (tmpFile != null) {
+ try {
+ Files.delete(tmpFile.toPath());
+ } catch (IOException e) {
+ System.out.println("Failed to delete temp file “" + tmpFile + "”: " + e.getMessage());
+ }
+ }
}
}
}
final SignalServiceMessageReceiver messageReceiver = new SignalServiceMessageReceiver(URL, TRUST_STORE, username, password, deviceId, signalingKey, USER_AGENT);
- File tmpFile = File.createTempFile("ts_attach_" + pointer.getId(), ".tmp");
+ File tmpFile = Util.createTempFile();
InputStream input = messageReceiver.retrieveAttachment(pointer, tmpFile);
OutputStream output = null;
if (output != null) {
output.close();
}
- if (!tmpFile.delete()) {
- System.err.println("Failed to delete temp file: " + tmpFile);
+ input.close();
+ try {
+ Files.delete(tmpFile.toPath());
+ } catch (IOException e) {
+ System.out.println("Failed to delete temp file “" + tmpFile + "”: " + e.getMessage());
}
}
return outputFile;
}
- private InputStream retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer) throws IOException, InvalidMessageException {
+ private InputStream retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer, File tmpFile) throws IOException, InvalidMessageException {
final SignalServiceMessageReceiver messageReceiver = new SignalServiceMessageReceiver(URL, TRUST_STORE, username, password, deviceId, signalingKey, USER_AGENT);
- File file = File.createTempFile("ts_tmp", "tmp");
- file.deleteOnExit();
-
- return messageReceiver.retrieveAttachment(pointer, file);
+ return messageReceiver.retrieveAttachment(pointer, tmpFile);
}
private String canonicalizeNumber(String number) throws InvalidNumberException {
}
private void sendGroups() throws IOException, UntrustedIdentityException {
- File groupsFile = File.createTempFile("multidevice-group-update", ".tmp");
+ File groupsFile = Util.createTempFile();
try {
DeviceGroupsOutputStream out = new DeviceGroupsOutputStream(new FileOutputStream(groupsFile));
}
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));
+ try (FileInputStream groupsFileStream = new FileInputStream(groupsFile)) {
+ SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
+ .withStream(groupsFileStream)
+ .withContentType("application/octet-stream")
+ .withLength(groupsFile.length())
+ .build();
+
+ sendSyncMessage(SignalServiceSyncMessage.forGroups(attachmentStream));
+ }
}
} finally {
- groupsFile.delete();
+ try {
+ Files.delete(groupsFile.toPath());
+ } catch (IOException e) {
+ System.out.println("Failed to delete temp file “" + groupsFile + "”: " + e.getMessage());
+ }
}
}
private void sendContacts() throws IOException, UntrustedIdentityException {
- File contactsFile = File.createTempFile("multidevice-contact-update", ".tmp");
+ File contactsFile = Util.createTempFile();
try {
DeviceContactsOutputStream out = new DeviceContactsOutputStream(new FileOutputStream(contactsFile));
}
if (contactsFile.exists() && contactsFile.length() > 0) {
- FileInputStream contactsFileStream = new FileInputStream(contactsFile);
- SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
- .withStream(contactsFileStream)
- .withContentType("application/octet-stream")
- .withLength(contactsFile.length())
- .build();
-
- sendMessage(SignalServiceSyncMessage.forContacts(attachmentStream));
+ try (FileInputStream contactsFileStream = new FileInputStream(contactsFile)) {
+ SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
+ .withStream(contactsFileStream)
+ .withContentType("application/octet-stream")
+ .withLength(contactsFile.length())
+ .build();
+
+ sendSyncMessage(SignalServiceSyncMessage.forContacts(attachmentStream));
+ }
}
} finally {
- contactsFile.delete();
+ try {
+ Files.delete(contactsFile.toPath());
+ } catch (IOException e) {
+ System.out.println("Failed to delete temp file “" + contactsFile + "”: " + e.getMessage());
+ }
}
}