]> nmode's Git Repositories - signal-cli/blobdiff - lib/src/main/java/org/asamk/signal/manager/ManagerImpl.java
Add optional message limit for receive command
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / ManagerImpl.java
index 54a6b9179deaa25b5c81b85625b7d627bf37cdf9..95f5bde4e710d62bf9f9b538c2624f027bf5ec2f 100644 (file)
@@ -27,7 +27,9 @@ import org.asamk.signal.manager.api.InvalidStickerException;
 import org.asamk.signal.manager.api.Message;
 import org.asamk.signal.manager.api.NotPrimaryDeviceException;
 import org.asamk.signal.manager.api.Pair;
+import org.asamk.signal.manager.api.PendingAdminApprovalException;
 import org.asamk.signal.manager.api.ReceiveConfig;
+import org.asamk.signal.manager.api.Recipient;
 import org.asamk.signal.manager.api.RecipientIdentifier;
 import org.asamk.signal.manager.api.SendGroupMessageResults;
 import org.asamk.signal.manager.api.SendMessageResult;
@@ -53,13 +55,13 @@ import org.asamk.signal.manager.storage.SignalAccount;
 import org.asamk.signal.manager.storage.groups.GroupInfo;
 import org.asamk.signal.manager.storage.identities.IdentityInfo;
 import org.asamk.signal.manager.storage.recipients.Profile;
-import org.asamk.signal.manager.storage.recipients.Recipient;
 import org.asamk.signal.manager.storage.recipients.RecipientId;
 import org.asamk.signal.manager.storage.stickerPacks.JsonStickerPack;
 import org.asamk.signal.manager.storage.stickerPacks.StickerPackStore;
 import org.asamk.signal.manager.storage.stickers.StickerPack;
 import org.asamk.signal.manager.util.AttachmentUtils;
 import org.asamk.signal.manager.util.KeyUtils;
+import org.asamk.signal.manager.util.MimeUtils;
 import org.asamk.signal.manager.util.StickerUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -69,15 +71,19 @@ import org.whispersystems.signalservice.api.messages.SignalServicePreview;
 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.ServiceId;
 import org.whispersystems.signalservice.api.util.DeviceNameUtil;
 import org.whispersystems.signalservice.api.util.InvalidNumberException;
 import org.whispersystems.signalservice.api.util.PhoneNumberFormatter;
+import org.whispersystems.signalservice.api.util.StreamDetails;
 import org.whispersystems.signalservice.internal.util.Hex;
 import org.whispersystems.signalservice.internal.util.Util;
 
+import java.io.ByteArrayInputStream;
 import java.io.File;
 import java.io.IOException;
 import java.net.URI;
+import java.nio.charset.StandardCharsets;
 import java.time.Duration;
 import java.util.ArrayList;
 import java.util.Collection;
@@ -165,11 +171,12 @@ class ManagerImpl implements Manager {
                 this.notifyAll();
             }
         });
-        disposable.add(account.getIdentityKeyStore().getIdentityChanges().subscribe(recipientId -> {
-            logger.trace("Archiving old sessions for {}", recipientId);
-            account.getAciSessionStore().archiveSessions(recipientId);
-            account.getPniSessionStore().archiveSessions(recipientId);
-            account.getSenderKeyStore().deleteSharedWith(recipientId);
+        disposable.add(account.getIdentityKeyStore().getIdentityChanges().subscribe(serviceId -> {
+            logger.trace("Archiving old sessions for {}", serviceId);
+            account.getAciSessionStore().archiveSessions(serviceId);
+            account.getPniSessionStore().archiveSessions(serviceId);
+            account.getSenderKeyStore().deleteSharedWith(serviceId);
+            final var recipientId = account.getRecipientResolver().resolveRecipient(serviceId);
             final var profile = account.getProfileStore().getProfile(recipientId);
             if (profile != null) {
                 account.getProfileStore()
@@ -214,13 +221,14 @@ class ManagerImpl implements Manager {
 
         return numbers.stream().collect(Collectors.toMap(n -> n, n -> {
             final var number = canonicalizedNumbers.get(n);
-            final var aci = registeredUsers.get(number);
-            final var profile = aci == null
+            final var user = registeredUsers.get(number);
+            final var serviceId = user == null ? null : user.getServiceId();
+            final var profile = serviceId == null
                     ? null
                     : context.getProfileHelper()
-                            .getRecipientProfile(account.getRecipientResolver().resolveRecipient(aci));
+                            .getRecipientProfile(account.getRecipientResolver().resolveRecipient(serviceId));
             return new UserStatus(number.isEmpty() ? null : number,
-                    aci == null ? null : aci.uuid(),
+                    serviceId == null ? null : serviceId.uuid(),
                     profile != null
                             && profile.getUnidentifiedAccessMode() == Profile.UnidentifiedAccessMode.UNRESTRICTED);
         }));
@@ -429,7 +437,7 @@ class ManagerImpl implements Manager {
     @Override
     public Pair<GroupId, SendGroupMessageResults> joinGroup(
             GroupInviteLinkUrl inviteLinkUrl
-    ) throws IOException, InactiveGroupLinkException {
+    ) throws IOException, InactiveGroupLinkException, PendingAdminApprovalException {
         return context.getGroupHelper().joinGroup(inviteLinkUrl);
     }
 
@@ -543,7 +551,7 @@ class ManagerImpl implements Manager {
         final var selfProfile = context.getProfileHelper().getSelfProfile();
         if (selfProfile == null || selfProfile.getDisplayName().isEmpty()) {
             logger.warn(
-                    "No profile name set. When sending a message it's recommended to set a profile name wit the updateProfile command. This may become mandatory in the future.");
+                    "No profile name set. When sending a message it's recommended to set a profile name with the updateProfile command. This may become mandatory in the future.");
         }
         final var messageBuilder = SignalServiceDataMessage.newBuilder();
         applyMessage(messageBuilder, message);
@@ -553,7 +561,15 @@ class ManagerImpl implements Manager {
     private void applyMessage(
             final SignalServiceDataMessage.Builder messageBuilder, final Message message
     ) throws AttachmentInvalidException, IOException, UnregisteredRecipientException, InvalidStickerException {
-        messageBuilder.withBody(message.messageText());
+        if (message.messageText().length() > 2000) {
+            final var messageBytes = message.messageText().getBytes(StandardCharsets.UTF_8);
+            final var textAttachment = AttachmentUtils.createAttachmentStream(new StreamDetails(new ByteArrayInputStream(
+                    messageBytes), MimeUtils.LONG_TEXT, messageBytes.length), Optional.empty());
+            messageBuilder.withBody(message.messageText().substring(0, 2000));
+            messageBuilder.withAttachment(textAttachment);
+        } else {
+            messageBuilder.withBody(message.messageText());
+        }
         if (message.attachments().size() > 0) {
             messageBuilder.withAttachments(context.getAttachmentHelper().uploadAttachments(message.attachments()));
         }
@@ -608,6 +624,14 @@ class ManagerImpl implements Manager {
             }
             messageBuilder.withPreviews(previews);
         }
+        if (message.storyReply().isPresent()) {
+            final var storyReply = message.storyReply().get();
+            final var authorServiceId = context.getRecipientHelper()
+                    .resolveSignalServiceAddress(context.getRecipientHelper().resolveRecipient(storyReply.author()))
+                    .getServiceId();
+            messageBuilder.withStoryContext(new SignalServiceDataMessage.StoryContext(authorServiceId,
+                    storyReply.timestamp()));
+        }
     }
 
     private ArrayList<SignalServiceDataMessage.Mention> resolveMentions(final List<Message.Mention> mentionList) throws UnregisteredRecipientException {
@@ -631,7 +655,11 @@ class ManagerImpl implements Manager {
             if (recipient instanceof RecipientIdentifier.Single r) {
                 try {
                     final var recipientId = context.getRecipientHelper().resolveRecipient(r);
-                    account.getMessageSendLogStore().deleteEntryForRecipientNonGroup(targetSentTimestamp, recipientId);
+                    account.getMessageSendLogStore()
+                            .deleteEntryForRecipientNonGroup(targetSentTimestamp,
+                                    account.getRecipientAddressResolver()
+                                            .resolveRecipientAddress(recipientId)
+                                            .getServiceId());
                 } catch (UnregisteredRecipientException ignored) {
                 }
             } else if (recipient instanceof RecipientIdentifier.Group r) {
@@ -647,14 +675,19 @@ class ManagerImpl implements Manager {
             boolean remove,
             RecipientIdentifier.Single targetAuthor,
             long targetSentTimestamp,
-            Set<RecipientIdentifier> recipients
+            Set<RecipientIdentifier> recipients,
+            final boolean isStory
     ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException, UnregisteredRecipientException {
         var targetAuthorRecipientId = context.getRecipientHelper().resolveRecipient(targetAuthor);
-        var reaction = new SignalServiceDataMessage.Reaction(emoji,
-                remove,
-                context.getRecipientHelper().resolveSignalServiceAddress(targetAuthorRecipientId).getServiceId(),
-                targetSentTimestamp);
+        final var authorServiceId = context.getRecipientHelper()
+                .resolveSignalServiceAddress(targetAuthorRecipientId)
+                .getServiceId();
+        var reaction = new SignalServiceDataMessage.Reaction(emoji, remove, authorServiceId, targetSentTimestamp);
         final var messageBuilder = SignalServiceDataMessage.newBuilder().withReaction(reaction);
+        if (isStory) {
+            messageBuilder.withStoryContext(new SignalServiceDataMessage.StoryContext(authorServiceId,
+                    targetSentTimestamp));
+        }
         return sendMessage(messageBuilder, recipients);
     }
 
@@ -689,20 +722,24 @@ class ManagerImpl implements Manager {
                 } catch (UnregisteredRecipientException e) {
                     continue;
                 }
-                account.getAciSessionStore().deleteAllSessions(recipientId);
+                final var serviceId = context.getAccount()
+                        .getRecipientAddressResolver()
+                        .resolveRecipientAddress(recipientId)
+                        .getServiceId();
+                account.getAciSessionStore().deleteAllSessions(serviceId);
             }
         }
     }
 
     @Override
     public void deleteRecipient(final RecipientIdentifier.Single recipient) {
-        account.removeRecipient(account.getRecipientResolver().resolveRecipient(recipient.toPartialRecipientAddress()));
+        account.removeRecipient(account.getRecipientResolver().resolveRecipient(recipient.getIdentifier()));
     }
 
     @Override
     public void deleteContact(final RecipientIdentifier.Single recipient) {
         account.getContactStore()
-                .deleteContact(account.getRecipientResolver().resolveRecipient(recipient.toPartialRecipientAddress()));
+                .deleteContact(account.getRecipientResolver().resolveRecipient(recipient.getIdentifier()));
     }
 
     @Override
@@ -924,17 +961,16 @@ class ManagerImpl implements Manager {
     }
 
     @Override
-    public void receiveMessages(Duration timeout, ReceiveMessageHandler handler) throws IOException {
-        receiveMessages(timeout, true, handler);
-    }
-
-    @Override
-    public void receiveMessages(ReceiveMessageHandler handler) throws IOException {
-        receiveMessages(Duration.ofMinutes(1), false, handler);
+    public void receiveMessages(
+            Optional<Duration> timeout,
+            Optional<Integer> maxMessages,
+            ReceiveMessageHandler handler
+    ) throws IOException {
+        receiveMessages(timeout.orElse(Duration.ofMinutes(1)), timeout.isPresent(), maxMessages.orElse(null), handler);
     }
 
     private void receiveMessages(
-            Duration timeout, boolean returnOnTimeout, ReceiveMessageHandler handler
+            Duration timeout, boolean returnOnTimeout, Integer maxMessages, ReceiveMessageHandler handler
     ) throws IOException {
         if (isReceiving()) {
             throw new IllegalStateException("Already receiving message.");
@@ -942,7 +978,7 @@ class ManagerImpl implements Manager {
         isReceivingSynchronous = true;
         receiveThread = Thread.currentThread();
         try {
-            context.getReceiveHelper().receiveMessages(timeout, returnOnTimeout, handler);
+            context.getReceiveHelper().receiveMessages(timeout, returnOnTimeout, maxMessages, handler);
         } finally {
             receiveThread = null;
             isReceivingSynchronous = false;
@@ -994,7 +1030,16 @@ class ManagerImpl implements Manager {
         }
         // refresh profiles of explicitly given recipients
         context.getProfileHelper().refreshRecipientProfiles(recipientIds);
-        return account.getRecipientStore().getRecipients(onlyContacts, blocked, recipientIds, name);
+        return account.getRecipientStore()
+                .getRecipients(onlyContacts, blocked, recipientIds, name)
+                .stream()
+                .map(s -> new Recipient(s.getRecipientId(),
+                        s.getAddress().toApiRecipientAddress(),
+                        s.getContact(),
+                        s.getProfileKey(),
+                        s.getExpiringProfileKeyCredential(),
+                        s.getProfile()))
+                .toList();
     }
 
     @Override
@@ -1035,27 +1080,29 @@ class ManagerImpl implements Manager {
         }
 
         final var address = account.getRecipientAddressResolver()
-                .resolveRecipientAddress(identityInfo.getRecipientId());
+                .resolveRecipientAddress(account.getRecipientResolver().resolveRecipient(identityInfo.getServiceId()));
         final var scannableFingerprint = context.getIdentityHelper()
-                .computeSafetyNumberForScanning(identityInfo.getRecipientId(), identityInfo.getIdentityKey());
-        return new Identity(address,
+                .computeSafetyNumberForScanning(identityInfo.getServiceId(), identityInfo.getIdentityKey());
+        return new Identity(address.toApiRecipientAddress(),
                 identityInfo.getIdentityKey(),
                 context.getIdentityHelper()
-                        .computeSafetyNumber(identityInfo.getRecipientId(), identityInfo.getIdentityKey()),
+                        .computeSafetyNumber(identityInfo.getServiceId(), identityInfo.getIdentityKey()),
                 scannableFingerprint == null ? null : scannableFingerprint.getSerialized(),
                 identityInfo.getTrustLevel(),
-                identityInfo.getDateAdded());
+                identityInfo.getDateAddedTimestamp());
     }
 
     @Override
     public List<Identity> getIdentities(RecipientIdentifier.Single recipient) {
-        IdentityInfo identity;
+        ServiceId serviceId;
         try {
-            identity = account.getIdentityKeyStore()
-                    .getIdentityInfo(context.getRecipientHelper().resolveRecipient(recipient));
+            serviceId = account.getRecipientAddressResolver()
+                    .resolveRecipientAddress(context.getRecipientHelper().resolveRecipient(recipient))
+                    .getServiceId();
         } catch (UnregisteredRecipientException e) {
-            identity = null;
+            return List.of();
         }
+        final var identity = account.getIdentityKeyStore().getIdentityInfo(serviceId);
         return identity == null ? List.of() : List.of(toIdentity(identity));
     }