package org.asamk.signal.util; import org.asamk.signal.commands.exceptions.UserErrorException; import org.asamk.signal.manager.Manager; import org.asamk.signal.manager.api.RecipientIdentifier; import org.asamk.signal.manager.groups.GroupId; import org.asamk.signal.manager.groups.GroupIdFormatException; import org.whispersystems.signalservice.api.util.InvalidNumberException; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; public class CommandUtil { private CommandUtil() { } public static Set getRecipientIdentifiers( final Manager m, final boolean isNoteToSelf, final List recipientStrings, final List groupIdStrings ) throws UserErrorException { final var recipientIdentifiers = new HashSet(); if (isNoteToSelf) { recipientIdentifiers.add(RecipientIdentifier.NoteToSelf.INSTANCE); } if (recipientStrings != null) { final var localNumber = m.getUsername(); recipientIdentifiers.addAll(CommandUtil.getSingleRecipientIdentifiers(recipientStrings, localNumber)); } if (groupIdStrings != null) { recipientIdentifiers.addAll(CommandUtil.getGroupIdentifiers(groupIdStrings)); } if (recipientIdentifiers.isEmpty()) { throw new UserErrorException("No recipients given"); } return recipientIdentifiers; } public static Set getGroupIdentifiers(Collection groupIdStrings) throws UserErrorException { if (groupIdStrings == null) { return Set.of(); } final var groupIds = new HashSet(); for (final var groupIdString : groupIdStrings) { groupIds.add(new RecipientIdentifier.Group(getGroupId(groupIdString))); } return groupIds; } public static Set getGroupIds(Collection groupIdStrings) throws UserErrorException { if (groupIdStrings == null) { return Set.of(); } final var groupIds = new HashSet(); for (final var groupIdString : groupIdStrings) { groupIds.add(getGroupId(groupIdString)); } return groupIds; } public static GroupId getGroupId(String groupId) throws UserErrorException { if (groupId == null) { return null; } try { return GroupId.fromBase64(groupId); } catch (GroupIdFormatException e) { throw new UserErrorException("Invalid group id: " + e.getMessage()); } } public static Set getSingleRecipientIdentifiers( final Collection recipientStrings, final String localNumber ) throws UserErrorException { if (recipientStrings == null) { return Set.of(); } final var identifiers = new HashSet(); for (var recipientString : recipientStrings) { identifiers.add(getSingleRecipientIdentifier(recipientString, localNumber)); } return identifiers; } public static RecipientIdentifier.Single getSingleRecipientIdentifier( final String recipientString, final String localNumber ) throws UserErrorException { try { return RecipientIdentifier.Single.fromString(recipientString, localNumber); } catch (InvalidNumberException e) { throw new UserErrorException("Invalid phone number '" + recipientString + "': " + e.getMessage()); } } }