Add RecipientIdentifier as external Manager interface

This commit is contained in:
AsamK 2021-08-25 12:22:53 +02:00
parent cd7172ee57
commit 467a48bac5
25 changed files with 958 additions and 595 deletions

View file

@ -31,7 +31,7 @@ public interface Signal extends DBusInterface {
long sendGroupRemoteDeleteMessage(
long targetSentTimestamp, byte[] groupId
) throws Error.Failure, Error.GroupNotFound;
) throws Error.Failure, Error.GroupNotFound, Error.InvalidGroupId;
long sendMessageReaction(
String emoji, boolean remove, String targetAuthor, long targetSentTimestamp, String recipient
@ -49,11 +49,11 @@ public interface Signal extends DBusInterface {
long sendGroupMessage(
String message, List<String> attachments, byte[] groupId
) throws Error.GroupNotFound, Error.Failure, Error.AttachmentInvalid;
) throws Error.GroupNotFound, Error.Failure, Error.AttachmentInvalid, Error.InvalidGroupId;
long sendGroupMessageReaction(
String emoji, boolean remove, String targetAuthor, long targetSentTimestamp, byte[] groupId
) throws Error.GroupNotFound, Error.Failure, Error.InvalidNumber;
) throws Error.GroupNotFound, Error.Failure, Error.InvalidNumber, Error.InvalidGroupId;
String getContactName(String number) throws Error.InvalidNumber;
@ -61,17 +61,17 @@ public interface Signal extends DBusInterface {
void setContactBlocked(String number, boolean blocked) throws Error.InvalidNumber;
void setGroupBlocked(byte[] groupId, boolean blocked) throws Error.GroupNotFound;
void setGroupBlocked(byte[] groupId, boolean blocked) throws Error.GroupNotFound, Error.InvalidGroupId;
List<byte[]> getGroupIds();
String getGroupName(byte[] groupId);
String getGroupName(byte[] groupId) throws Error.InvalidGroupId;
List<String> getGroupMembers(byte[] groupId);
List<String> getGroupMembers(byte[] groupId) throws Error.InvalidGroupId;
byte[] updateGroup(
byte[] groupId, String name, List<String> members, String avatar
) throws Error.AttachmentInvalid, Error.Failure, Error.InvalidNumber, Error.GroupNotFound;
) throws Error.AttachmentInvalid, Error.Failure, Error.InvalidNumber, Error.GroupNotFound, Error.InvalidGroupId;
boolean isRegistered();
@ -85,15 +85,15 @@ public interface Signal extends DBusInterface {
List<String> getContactNumber(final String name) throws Error.Failure;
void quitGroup(final byte[] groupId) throws Error.GroupNotFound, Error.Failure;
void quitGroup(final byte[] groupId) throws Error.GroupNotFound, Error.Failure, Error.InvalidGroupId;
boolean isContactBlocked(final String number) throws Error.InvalidNumber;
boolean isGroupBlocked(final byte[] groupId);
boolean isGroupBlocked(final byte[] groupId) throws Error.InvalidGroupId;
boolean isMember(final byte[] groupId);
boolean isMember(final byte[] groupId) throws Error.InvalidGroupId;
void joinGroup(final String groupLink) throws Error.Failure;
byte[] joinGroup(final String groupLink) throws Error.Failure;
class MessageReceived extends DBusSignal {
@ -235,6 +235,13 @@ public interface Signal extends DBusInterface {
}
}
class InvalidGroupId extends DBusExecutionException {
public InvalidGroupId(final String message) {
super(message);
}
}
class InvalidNumber extends DBusExecutionException {
public InvalidNumber(final String message) {

View file

@ -1,6 +1,7 @@
package org.asamk.signal;
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.GroupUtils;
import org.asamk.signal.util.DateUtils;
@ -18,7 +19,6 @@ import org.whispersystems.signalservice.api.messages.calls.SignalServiceCallMess
import org.whispersystems.signalservice.api.messages.multidevice.SignalServiceSyncMessage;
import org.whispersystems.signalservice.api.messages.shared.SharedContact;
import org.whispersystems.signalservice.api.push.SignalServiceAddress;
import org.whispersystems.signalservice.api.util.InvalidNumberException;
import java.util.ArrayList;
import java.util.Base64;
@ -450,7 +450,7 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
final PlainTextWriter writer, final SignalServiceDataMessage.Reaction reaction
) {
writer.println("Emoji: {}", reaction.getEmoji());
writer.println("Target author: {}", formatContact(m.resolveSignalServiceAddress(reaction.getTargetAuthor())));
writer.println("Target author: {}", formatContact(reaction.getTargetAuthor()));
writer.println("Target timestamp: {}", DateUtils.formatTimestamp(reaction.getTargetSentTimestamp()));
writer.println("Is remove: {}", reaction.isRemove());
}
@ -459,7 +459,7 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
final PlainTextWriter writer, final SignalServiceDataMessage.Quote quote
) {
writer.println("Id: {}", quote.getId());
writer.println("Author: {}", getLegacyIdentifier(m.resolveSignalServiceAddress(quote.getAuthor())));
writer.println("Author: {}", formatContact(quote.getAuthor()));
writer.println("Text: {}", quote.getText());
if (quote.getMentions() != null && quote.getMentions().size() > 0) {
writer.println("Mentions:");
@ -678,12 +678,9 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
}
private String formatContact(SignalServiceAddress address) {
address = m.resolveSignalServiceAddress(address);
final var number = getLegacyIdentifier(address);
String name = null;
try {
name = m.getContactOrProfileName(number);
} catch (InvalidNumberException ignored) {
}
final var name = m.getContactOrProfileName(RecipientIdentifier.Single.fromAddress(address));
if (name == null || name.isEmpty()) {
return number;
} else {

View file

@ -8,12 +8,10 @@ import org.asamk.signal.commands.exceptions.CommandException;
import org.asamk.signal.commands.exceptions.UserErrorException;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.NotMasterDeviceException;
import org.asamk.signal.manager.groups.GroupIdFormatException;
import org.asamk.signal.manager.groups.GroupNotFoundException;
import org.asamk.signal.util.Util;
import org.asamk.signal.util.CommandUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.signalservice.api.util.InvalidNumberException;
public class BlockCommand implements JsonRpcLocalCommand {
@ -35,23 +33,22 @@ public class BlockCommand implements JsonRpcLocalCommand {
public void handleCommand(
final Namespace ns, final Manager m, final OutputWriter outputWriter
) throws CommandException {
for (var contactNumber : ns.<String>getList("contact")) {
final var contacts = ns.<String>getList("contact");
for (var contact : CommandUtil.getSingleRecipientIdentifiers(contacts, m.getUsername())) {
try {
m.setContactBlocked(contactNumber, true);
} catch (InvalidNumberException e) {
logger.warn("Invalid number {}: {}", contactNumber, e.getMessage());
m.setContactBlocked(contact, true);
} catch (NotMasterDeviceException e) {
throw new UserErrorException("This command doesn't work on linked devices.");
}
}
if (ns.<String>getList("group-id") != null) {
for (var groupIdString : ns.<String>getList("group-id")) {
final var groupIdStrings = ns.<String>getList("group-id");
if (groupIdStrings != null) {
for (var groupId : CommandUtil.getGroupIds(groupIdStrings)) {
try {
var groupId = Util.decodeGroupId(groupIdString);
m.setGroupBlocked(groupId, true);
} catch (GroupIdFormatException | GroupNotFoundException e) {
logger.warn("Invalid group id {}: {}", groupIdString, e.getMessage());
} catch (GroupNotFoundException e) {
logger.warn("Group not found {}: {}", groupId.toBase64(), e.getMessage());
}
}
}

View file

@ -70,7 +70,7 @@ public class JoinGroupCommand implements JsonRpcLocalCommand {
writer.println("Joined group \"{}\"", newGroupId.toBase64());
}
}
handleSendMessageResults(results.second());
handleSendMessageResults(results.second().getResults());
} catch (GroupPatchNotAcceptedException e) {
throw new UserErrorException("Failed to join group, maybe already a member");
} catch (IOException e) {

View file

@ -7,15 +7,14 @@ import org.asamk.signal.JsonWriter;
import org.asamk.signal.OutputWriter;
import org.asamk.signal.PlainTextWriter;
import org.asamk.signal.commands.exceptions.CommandException;
import org.asamk.signal.commands.exceptions.UserErrorException;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.storage.identities.IdentityInfo;
import org.asamk.signal.util.CommandUtil;
import org.asamk.signal.util.Hex;
import org.asamk.signal.util.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.signalservice.api.push.SignalServiceAddress;
import org.whispersystems.signalservice.api.util.InvalidNumberException;
import java.util.Base64;
import java.util.List;
@ -58,11 +57,7 @@ public class ListIdentitiesCommand implements JsonRpcLocalCommand {
if (number == null) {
identities = m.getIdentities();
} else {
try {
identities = m.getIdentities(number);
} catch (InvalidNumberException e) {
throw new UserErrorException("Invalid number: " + e.getMessage());
}
identities = m.getIdentities(CommandUtil.getSingleRecipientIdentifier(number, m.getUsername()));
}
if (outputWriter instanceof PlainTextWriter) {

View file

@ -11,20 +11,15 @@ import org.asamk.signal.commands.exceptions.CommandException;
import org.asamk.signal.commands.exceptions.IOErrorException;
import org.asamk.signal.commands.exceptions.UserErrorException;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.groups.GroupId;
import org.asamk.signal.manager.groups.GroupIdFormatException;
import org.asamk.signal.manager.groups.GroupNotFoundException;
import org.asamk.signal.manager.groups.LastGroupAdminException;
import org.asamk.signal.manager.groups.NotAGroupMemberException;
import org.asamk.signal.util.Util;
import org.asamk.signal.util.CommandUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.signalservice.api.util.InvalidNumberException;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static org.asamk.signal.util.ErrorUtils.handleSendMessageResults;
@ -53,22 +48,16 @@ public class QuitGroupCommand implements JsonRpcLocalCommand {
public void handleCommand(
final Namespace ns, final Manager m, final OutputWriter outputWriter
) throws CommandException {
final GroupId groupId;
try {
groupId = Util.decodeGroupId(ns.getString("group-id"));
} catch (GroupIdFormatException e) {
throw new UserErrorException("Invalid group id: " + e.getMessage());
}
final var groupId = CommandUtil.getGroupId(ns.getString("group-id"));
var groupAdmins = ns.<String>getList("admin");
var groupAdmins = CommandUtil.getSingleRecipientIdentifiers(ns.getList("admin"), m.getUsername());
try {
try {
final var results = m.sendQuitGroupMessage(groupId,
groupAdmins == null ? Set.of() : new HashSet<>(groupAdmins));
final var timestamp = results.first();
final var results = m.sendQuitGroupMessage(groupId, groupAdmins);
final var timestamp = results.getTimestamp();
outputResult(outputWriter, timestamp);
handleSendMessageResults(results.second());
handleSendMessageResults(results.getResults());
} catch (NotAGroupMemberException e) {
logger.info("User is not a group member");
}
@ -80,8 +69,6 @@ public class QuitGroupCommand implements JsonRpcLocalCommand {
throw new IOErrorException("Failed to send message: " + e.getMessage());
} catch (GroupNotFoundException e) {
throw new UserErrorException("Failed to send to group: " + e.getMessage());
} catch (InvalidNumberException e) {
throw new UserErrorException("Failed to parse admin number: " + e.getMessage());
} catch (LastGroupAdminException e) {
throw new UserErrorException("You need to specify a new admin with --admin: " + e.getMessage());
}

View file

@ -1,5 +1,6 @@
package org.asamk.signal.commands;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
@ -10,14 +11,15 @@ import org.asamk.signal.PlainTextWriter;
import org.asamk.signal.commands.exceptions.CommandException;
import org.asamk.signal.commands.exceptions.UnexpectedErrorException;
import org.asamk.signal.commands.exceptions.UserErrorException;
import org.asamk.signal.dbus.DbusSignalImpl;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.groups.GroupIdFormatException;
import org.asamk.signal.util.Util;
import org.asamk.signal.manager.groups.GroupNotFoundException;
import org.asamk.signal.manager.groups.NotAGroupMemberException;
import org.asamk.signal.util.CommandUtil;
import org.asamk.signal.util.ErrorUtils;
import org.freedesktop.dbus.errors.UnknownObject;
import org.freedesktop.dbus.exceptions.DBusExecutionException;
import java.util.List;
import java.io.IOException;
import java.util.Map;
public class RemoteDeleteCommand implements DbusCommand, JsonRpcLocalCommand {
@ -34,40 +36,62 @@ public class RemoteDeleteCommand implements DbusCommand, JsonRpcLocalCommand {
.required(true)
.type(long.class)
.help("Specify the timestamp of the message to delete.");
subparser.addArgument("-g", "--group-id", "--group").help("Specify the recipient group ID.");
subparser.addArgument("-g", "--group-id", "--group").help("Specify the recipient group ID.").nargs("*");
subparser.addArgument("recipient").help("Specify the recipients' phone number.").nargs("*");
subparser.addArgument("--note-to-self").action(Arguments.storeTrue());
}
@Override
public void handleCommand(
final Namespace ns, final Manager m, final OutputWriter outputWriter
) throws CommandException {
final var isNoteToSelf = ns.getBoolean("note-to-self");
final var recipientStrings = ns.<String>getList("recipient");
final var groupIdStrings = ns.<String>getList("group-id");
final var recipientIdentifiers = CommandUtil.getRecipientIdentifiers(m,
isNoteToSelf,
recipientStrings,
groupIdStrings);
final long targetTimestamp = ns.getLong("target-timestamp");
try {
final var results = m.sendRemoteDeleteMessage(targetTimestamp, recipientIdentifiers);
outputResult(outputWriter, results.getTimestamp());
ErrorUtils.handleSendMessageResults(results.getResults());
} catch (GroupNotFoundException | NotAGroupMemberException e) {
throw new UserErrorException(e.getMessage());
} catch (IOException e) {
throw new UnexpectedErrorException("Failed to send message: " + e.getMessage());
}
}
@Override
public void handleCommand(
final Namespace ns, final Signal signal, final OutputWriter outputWriter
) throws CommandException {
final List<String> recipients = ns.getList("recipient");
final var groupIdString = ns.getString("group-id");
final var recipients = ns.<String>getList("recipient");
final var groupIdStrings = ns.<String>getList("group-id");
final var noRecipients = recipients == null || recipients.isEmpty();
if (noRecipients && groupIdString == null) {
final var noGroups = groupIdStrings == null || groupIdStrings.isEmpty();
if (noRecipients && noGroups) {
throw new UserErrorException("No recipients given");
}
if (!noRecipients && groupIdString != null) {
if (!noRecipients && !noGroups) {
throw new UserErrorException("You cannot specify recipients by phone number and groups at the same time");
}
final long targetTimestamp = ns.getLong("target-timestamp");
byte[] groupId = null;
if (groupIdString != null) {
try {
groupId = Util.decodeGroupId(groupIdString).serialize();
} catch (GroupIdFormatException e) {
throw new UserErrorException("Invalid group id: " + e.getMessage());
}
}
try {
long timestamp;
if (groupId != null) {
timestamp = signal.sendGroupRemoteDeleteMessage(targetTimestamp, groupId);
long timestamp = 0;
if (!noGroups) {
final var groupIds = CommandUtil.getGroupIds(groupIdStrings);
for (final var groupId : groupIds) {
timestamp = signal.sendGroupRemoteDeleteMessage(targetTimestamp, groupId.serialize());
}
} else {
timestamp = signal.sendRemoteDeleteMessage(targetTimestamp, recipients);
}
@ -83,13 +107,6 @@ public class RemoteDeleteCommand implements DbusCommand, JsonRpcLocalCommand {
}
}
@Override
public void handleCommand(
final Namespace ns, final Manager m, final OutputWriter outputWriter
) throws CommandException {
handleCommand(ns, new DbusSignalImpl(m, null), outputWriter);
}
private void outputResult(final OutputWriter outputWriter, final long timestamp) {
if (outputWriter instanceof PlainTextWriter) {
final var writer = (PlainTextWriter) outputWriter;

View file

@ -12,11 +12,15 @@ import org.asamk.signal.commands.exceptions.CommandException;
import org.asamk.signal.commands.exceptions.UnexpectedErrorException;
import org.asamk.signal.commands.exceptions.UntrustedKeyErrorException;
import org.asamk.signal.commands.exceptions.UserErrorException;
import org.asamk.signal.dbus.DbusSignalImpl;
import org.asamk.signal.manager.AttachmentInvalidException;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.groups.GroupIdFormatException;
import org.asamk.signal.manager.api.Message;
import org.asamk.signal.manager.api.RecipientIdentifier;
import org.asamk.signal.manager.groups.GroupNotFoundException;
import org.asamk.signal.manager.groups.NotAGroupMemberException;
import org.asamk.signal.util.CommandUtil;
import org.asamk.signal.util.ErrorUtils;
import org.asamk.signal.util.IOUtils;
import org.asamk.signal.util.Util;
import org.freedesktop.dbus.errors.UnknownObject;
import org.freedesktop.dbus.exceptions.DBusExecutionException;
import org.slf4j.Logger;
@ -26,6 +30,7 @@ import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class SendCommand implements DbusCommand, JsonRpcLocalCommand {
@ -40,9 +45,8 @@ public class SendCommand implements DbusCommand, JsonRpcLocalCommand {
public void attachToSubparser(final Subparser subparser) {
subparser.help("Send a message to another user or group.");
subparser.addArgument("recipient").help("Specify the recipients' phone number.").nargs("*");
final var mutuallyExclusiveGroup = subparser.addMutuallyExclusiveGroup();
mutuallyExclusiveGroup.addArgument("-g", "--group-id", "--group").help("Specify the recipient group ID.");
mutuallyExclusiveGroup.addArgument("--note-to-self")
subparser.addArgument("-g", "--group-id", "--group").help("Specify the recipient group ID.").nargs("*");
subparser.addArgument("--note-to-self")
.help("Send the message to self without notification.")
.action(Arguments.storeTrue());
@ -53,20 +57,77 @@ public class SendCommand implements DbusCommand, JsonRpcLocalCommand {
.action(Arguments.storeTrue());
}
@Override
public void handleCommand(
final Namespace ns, final Manager m, final OutputWriter outputWriter
) throws CommandException {
final var isNoteToSelf = ns.getBoolean("note-to-self");
final var recipientStrings = ns.<String>getList("recipient");
final var groupIdStrings = ns.<String>getList("group-id");
final var recipientIdentifiers = CommandUtil.getRecipientIdentifiers(m,
isNoteToSelf,
recipientStrings,
groupIdStrings);
final var isEndSession = ns.getBoolean("end-session");
if (isEndSession) {
final var singleRecipients = recipientIdentifiers.stream()
.filter(r -> r instanceof RecipientIdentifier.Single)
.map(RecipientIdentifier.Single.class::cast)
.collect(Collectors.toSet());
if (singleRecipients.isEmpty()) {
throw new UserErrorException("No recipients given");
}
try {
m.sendEndSessionMessage(singleRecipients);
return;
} catch (IOException e) {
throw new UnexpectedErrorException("Failed to send message: " + e.getMessage());
}
}
var messageText = ns.getString("message");
if (messageText == null) {
try {
messageText = IOUtils.readAll(System.in, Charset.defaultCharset());
} catch (IOException e) {
throw new UserErrorException("Failed to read message from stdin: " + e.getMessage());
}
}
List<String> attachments = ns.getList("attachment");
if (attachments == null) {
attachments = List.of();
}
try {
var results = m.sendMessage(new Message(messageText, attachments), recipientIdentifiers);
outputResult(outputWriter, results.getTimestamp());
ErrorUtils.handleSendMessageResults(results.getResults());
} catch (AttachmentInvalidException | IOException e) {
throw new UnexpectedErrorException("Failed to send message: " + e.getMessage());
} catch (GroupNotFoundException | NotAGroupMemberException e) {
throw new UserErrorException(e.getMessage());
}
}
@Override
public void handleCommand(
final Namespace ns, final Signal signal, final OutputWriter outputWriter
) throws CommandException {
final List<String> recipients = ns.getList("recipient");
final var recipients = ns.<String>getList("recipient");
final var isEndSession = ns.getBoolean("end-session");
final var groupIdString = ns.getString("group-id");
final var groupIdStrings = ns.<String>getList("group-id");
final var isNoteToSelf = ns.getBoolean("note-to-self");
final var noRecipients = recipients == null || recipients.isEmpty();
if ((noRecipients && isEndSession) || (noRecipients && groupIdString == null && !isNoteToSelf)) {
final var noGroups = groupIdStrings == null || groupIdStrings.isEmpty();
if ((noRecipients && isEndSession) || (noRecipients && noGroups && !isNoteToSelf)) {
throw new UserErrorException("No recipients given");
}
if (!noRecipients && groupIdString != null) {
if (!noRecipients && !noGroups) {
throw new UserErrorException("You cannot specify recipients by phone number and groups at the same time");
}
if (!noRecipients && isNoteToSelf) {
@ -99,16 +160,14 @@ public class SendCommand implements DbusCommand, JsonRpcLocalCommand {
attachments = List.of();
}
if (groupIdString != null) {
byte[] groupId;
try {
groupId = Util.decodeGroupId(groupIdString).serialize();
} catch (GroupIdFormatException e) {
throw new UserErrorException("Invalid group id: " + e.getMessage());
}
if (!noGroups) {
final var groupIds = CommandUtil.getGroupIds(groupIdStrings);
try {
var timestamp = signal.sendGroupMessage(messageText, attachments, groupId);
long timestamp = 0;
for (final var groupId : groupIds) {
timestamp = signal.sendGroupMessage(messageText, attachments, groupId.serialize());
}
outputResult(outputWriter, timestamp);
return;
} catch (DBusExecutionException e) {
@ -149,11 +208,4 @@ public class SendCommand implements DbusCommand, JsonRpcLocalCommand {
writer.write(Map.of("timestamp", timestamp));
}
}
@Override
public void handleCommand(
final Namespace ns, final Manager m, final OutputWriter outputWriter
) throws CommandException {
handleCommand(ns, new DbusSignalImpl(m, null), outputWriter);
}
}

View file

@ -11,14 +11,15 @@ import org.asamk.signal.PlainTextWriter;
import org.asamk.signal.commands.exceptions.CommandException;
import org.asamk.signal.commands.exceptions.UnexpectedErrorException;
import org.asamk.signal.commands.exceptions.UserErrorException;
import org.asamk.signal.dbus.DbusSignalImpl;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.groups.GroupIdFormatException;
import org.asamk.signal.util.Util;
import org.asamk.signal.manager.groups.GroupNotFoundException;
import org.asamk.signal.manager.groups.NotAGroupMemberException;
import org.asamk.signal.util.CommandUtil;
import org.asamk.signal.util.ErrorUtils;
import org.freedesktop.dbus.errors.UnknownObject;
import org.freedesktop.dbus.exceptions.DBusExecutionException;
import java.util.List;
import java.io.IOException;
import java.util.Map;
public class SendReactionCommand implements DbusCommand, JsonRpcLocalCommand {
@ -31,8 +32,11 @@ public class SendReactionCommand implements DbusCommand, JsonRpcLocalCommand {
@Override
public void attachToSubparser(final Subparser subparser) {
subparser.help("Send reaction to a previously received or sent message.");
subparser.addArgument("-g", "--group-id", "--group").help("Specify the recipient group ID.");
subparser.addArgument("-g", "--group-id", "--group").help("Specify the recipient group ID.").nargs("*");
subparser.addArgument("recipient").help("Specify the recipients' phone number.").nargs("*");
subparser.addArgument("--note-to-self")
.help("Send the reaction to self without notification.")
.action(Arguments.storeTrue());
subparser.addArgument("-e", "--emoji")
.required(true)
.help("Specify the emoji, should be a single unicode grapheme cluster.");
@ -46,39 +50,71 @@ public class SendReactionCommand implements DbusCommand, JsonRpcLocalCommand {
subparser.addArgument("-r", "--remove").help("Remove a reaction.").action(Arguments.storeTrue());
}
@Override
public void handleCommand(
final Namespace ns, final Manager m, final OutputWriter outputWriter
) throws CommandException {
final var isNoteToSelf = ns.getBoolean("note-to-self");
final var recipientStrings = ns.<String>getList("recipient");
final var groupIdStrings = ns.<String>getList("group-id");
final var recipientIdentifiers = CommandUtil.getRecipientIdentifiers(m,
isNoteToSelf,
recipientStrings,
groupIdStrings);
final var emoji = ns.getString("emoji");
final var isRemove = ns.getBoolean("remove");
final var targetAuthor = ns.getString("target-author");
final var targetTimestamp = ns.getLong("target-timestamp");
try {
final var results = m.sendMessageReaction(emoji,
isRemove,
CommandUtil.getSingleRecipientIdentifier(targetAuthor, m.getUsername()),
targetTimestamp,
recipientIdentifiers);
outputResult(outputWriter, results.getTimestamp());
ErrorUtils.handleSendMessageResults(results.getResults());
} catch (GroupNotFoundException | NotAGroupMemberException e) {
throw new UserErrorException(e.getMessage());
} catch (IOException e) {
throw new UnexpectedErrorException("Failed to send message: " + e.getMessage());
}
}
@Override
public void handleCommand(
final Namespace ns, final Signal signal, final OutputWriter outputWriter
) throws CommandException {
final List<String> recipients = ns.getList("recipient");
final var groupIdString = ns.getString("group-id");
final var recipients = ns.<String>getList("recipient");
final var groupIdStrings = ns.<String>getList("group-id");
final var noRecipients = recipients == null || recipients.isEmpty();
if (noRecipients && groupIdString == null) {
final var noGroups = groupIdStrings == null || groupIdStrings.isEmpty();
if (noRecipients && noGroups) {
throw new UserErrorException("No recipients given");
}
if (!noRecipients && groupIdString != null) {
if (!noRecipients && !noGroups) {
throw new UserErrorException("You cannot specify recipients by phone number and groups at the same time");
}
final var emoji = ns.getString("emoji");
final boolean isRemove = ns.getBoolean("remove");
final var isRemove = ns.getBoolean("remove");
final var targetAuthor = ns.getString("target-author");
final long targetTimestamp = ns.getLong("target-timestamp");
byte[] groupId = null;
if (groupIdString != null) {
try {
groupId = Util.decodeGroupId(groupIdString).serialize();
} catch (GroupIdFormatException e) {
throw new UserErrorException("Invalid group id: " + e.getMessage());
}
}
final var targetTimestamp = ns.getLong("target-timestamp");
try {
long timestamp;
if (groupId != null) {
timestamp = signal.sendGroupMessageReaction(emoji, isRemove, targetAuthor, targetTimestamp, groupId);
long timestamp = 0;
if (!noGroups) {
final var groupIds = CommandUtil.getGroupIds(groupIdStrings);
for (final var groupId : groupIds) {
timestamp = signal.sendGroupMessageReaction(emoji,
isRemove,
targetAuthor,
targetTimestamp,
groupId.serialize());
}
} else {
timestamp = signal.sendMessageReaction(emoji, isRemove, targetAuthor, targetTimestamp, recipients);
}
@ -94,13 +130,6 @@ public class SendReactionCommand implements DbusCommand, JsonRpcLocalCommand {
}
}
@Override
public void handleCommand(
final Namespace ns, final Manager m, final OutputWriter outputWriter
) throws CommandException {
handleCommand(ns, new DbusSignalImpl(m, null), outputWriter);
}
private void outputResult(final OutputWriter outputWriter, final long timestamp) {
if (outputWriter instanceof PlainTextWriter) {
final var writer = (PlainTextWriter) outputWriter;

View file

@ -7,8 +7,8 @@ import org.asamk.signal.OutputWriter;
import org.asamk.signal.commands.exceptions.CommandException;
import org.asamk.signal.commands.exceptions.UserErrorException;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.util.CommandUtil;
import org.whispersystems.signalservice.api.crypto.UntrustedIdentityException;
import org.whispersystems.signalservice.api.util.InvalidNumberException;
import java.io.IOException;
@ -34,7 +34,8 @@ public class SendReceiptCommand implements JsonRpcLocalCommand {
public void handleCommand(
final Namespace ns, final Manager m, final OutputWriter outputWriter
) throws CommandException {
final var recipient = ns.getString("recipient");
final var recipientString = ns.getString("recipient");
final var recipient = CommandUtil.getSingleRecipientIdentifier(recipientString, m.getUsername());
final var targetTimestamps = ns.<Long>getList("target-timestamp");
final var type = ns.getString("type");
@ -49,8 +50,6 @@ public class SendReceiptCommand implements JsonRpcLocalCommand {
}
} catch (IOException | UntrustedIdentityException e) {
throw new UserErrorException("Failed to send message: " + e.getMessage());
} catch (InvalidNumberException e) {
throw new UserErrorException("Invalid number: " + e.getMessage());
}
}
}

View file

@ -8,14 +8,12 @@ import org.asamk.signal.OutputWriter;
import org.asamk.signal.commands.exceptions.CommandException;
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.api.TypingAction;
import org.asamk.signal.manager.groups.GroupId;
import org.asamk.signal.manager.groups.GroupIdFormatException;
import org.asamk.signal.manager.groups.GroupNotFoundException;
import org.asamk.signal.manager.groups.NotAGroupMemberException;
import org.asamk.signal.util.Util;
import org.asamk.signal.util.CommandUtil;
import org.whispersystems.signalservice.api.crypto.UntrustedIdentityException;
import org.whispersystems.signalservice.api.util.InvalidNumberException;
import java.io.IOException;
import java.util.HashSet;
@ -31,7 +29,7 @@ public class SendTypingCommand implements JsonRpcLocalCommand {
public void attachToSubparser(final Subparser subparser) {
subparser.help(
"Send typing message to trigger a typing indicator for the recipient. Indicator will be shown for 15seconds unless a typing STOP message is sent first.");
subparser.addArgument("-g", "--group-id", "--group").help("Specify the recipient group ID.");
subparser.addArgument("-g", "--group-id", "--group").help("Specify the recipient group ID.").nargs("*");
subparser.addArgument("recipient").help("Specify the recipients' phone number.").nargs("*");
subparser.addArgument("-s", "--stop").help("Send a typing STOP message.").action(Arguments.storeTrue());
}
@ -40,40 +38,29 @@ public class SendTypingCommand implements JsonRpcLocalCommand {
public void handleCommand(
final Namespace ns, final Manager m, final OutputWriter outputWriter
) throws CommandException {
final var recipients = ns.<String>getList("recipient");
final var groupIdString = ns.getString("group-id");
final var noRecipients = recipients == null || recipients.isEmpty();
if (noRecipients && groupIdString == null) {
throw new UserErrorException("No recipients given");
}
if (!noRecipients && groupIdString != null) {
throw new UserErrorException("You cannot specify recipients by phone number and groups at the same time");
}
final var recipientStrings = ns.<String>getList("recipient");
final var groupIdStrings = ns.<String>getList("group-id");
final var action = ns.getBoolean("stop") ? TypingAction.STOP : TypingAction.START;
GroupId groupId = null;
if (groupIdString != null) {
try {
groupId = Util.decodeGroupId(groupIdString);
} catch (GroupIdFormatException e) {
throw new UserErrorException("Invalid group id: " + e.getMessage());
}
final var recipientIdentifiers = new HashSet<RecipientIdentifier>();
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");
}
try {
if (groupId != null) {
m.sendGroupTypingMessage(action, groupId);
} else {
m.sendTypingMessage(action, new HashSet<>(recipients));
}
m.sendTypingMessage(action, recipientIdentifiers);
} catch (IOException | UntrustedIdentityException e) {
throw new UserErrorException("Failed to send message: " + e.getMessage());
} catch (GroupNotFoundException | NotAGroupMemberException e) {
throw new UserErrorException("Failed to send to group: " + e.getMessage());
} catch (InvalidNumberException e) {
throw new UserErrorException("Invalid number: " + e.getMessage());
}
}
}

View file

@ -8,8 +8,8 @@ import org.asamk.signal.OutputWriter;
import org.asamk.signal.commands.exceptions.CommandException;
import org.asamk.signal.commands.exceptions.UserErrorException;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.util.CommandUtil;
import org.asamk.signal.util.Hex;
import org.whispersystems.signalservice.api.util.InvalidNumberException;
import java.util.Base64;
import java.util.Locale;
@ -37,14 +37,10 @@ public class TrustCommand implements JsonRpcLocalCommand {
public void handleCommand(
final Namespace ns, final Manager m, final OutputWriter outputWriter
) throws CommandException {
var number = ns.getString("number");
var recipentString = ns.getString("number");
var recipient = CommandUtil.getSingleRecipientIdentifier(recipentString, m.getUsername());
if (ns.getBoolean("trust-all-known-keys")) {
boolean res;
try {
res = m.trustIdentityAllKeys(number);
} catch (InvalidNumberException e) {
throw new UserErrorException("Failed to parse recipient: " + e.getMessage());
}
boolean res = m.trustIdentityAllKeys(recipient);
if (!res) {
throw new UserErrorException("Failed to set the trust for this number, make sure the number is correct.");
}
@ -64,23 +60,13 @@ public class TrustCommand implements JsonRpcLocalCommand {
throw new UserErrorException(
"Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
}
boolean res;
try {
res = m.trustIdentityVerified(number, fingerprintBytes);
} catch (InvalidNumberException e) {
throw new UserErrorException("Failed to parse recipient: " + e.getMessage());
}
boolean res = m.trustIdentityVerified(recipient, fingerprintBytes);
if (!res) {
throw new UserErrorException(
"Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
}
} else if (safetyNumber.length() == 60) {
boolean res;
try {
res = m.trustIdentityVerifiedSafetyNumber(number, safetyNumber);
} catch (InvalidNumberException e) {
throw new UserErrorException("Failed to parse recipient: " + e.getMessage());
}
boolean res = m.trustIdentityVerifiedSafetyNumber(recipient, safetyNumber);
if (!res) {
throw new UserErrorException(
"Failed to set the trust for the safety number of this phone number, make sure the phone number and the safety number are correct.");
@ -93,12 +79,7 @@ public class TrustCommand implements JsonRpcLocalCommand {
throw new UserErrorException(
"Safety number has invalid format, either specify the old hex fingerprint or the new safety number");
}
boolean res;
try {
res = m.trustIdentityVerifiedSafetyNumber(number, scannableSafetyNumber);
} catch (InvalidNumberException e) {
throw new UserErrorException("Failed to parse recipient: " + e.getMessage());
}
boolean res = m.trustIdentityVerifiedSafetyNumber(recipient, scannableSafetyNumber);
if (!res) {
throw new UserErrorException(
"Failed to set the trust for the safety number of this phone number, make sure the phone number and the safety number are correct.");

View file

@ -8,12 +8,10 @@ import org.asamk.signal.commands.exceptions.CommandException;
import org.asamk.signal.commands.exceptions.UserErrorException;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.NotMasterDeviceException;
import org.asamk.signal.manager.groups.GroupIdFormatException;
import org.asamk.signal.manager.groups.GroupNotFoundException;
import org.asamk.signal.util.Util;
import org.asamk.signal.util.CommandUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.signalservice.api.util.InvalidNumberException;
public class UnblockCommand implements JsonRpcLocalCommand {
@ -35,26 +33,20 @@ public class UnblockCommand implements JsonRpcLocalCommand {
public void handleCommand(
final Namespace ns, final Manager m, final OutputWriter outputWriter
) throws CommandException {
for (var contactNumber : ns.<String>getList("contact")) {
for (var contactNumber : CommandUtil.getSingleRecipientIdentifiers(ns.getList("contact"), m.getUsername())) {
try {
m.setContactBlocked(contactNumber, false);
} catch (InvalidNumberException e) {
logger.warn("Invalid number: {}", contactNumber);
} catch (NotMasterDeviceException e) {
throw new UserErrorException("This command doesn't work on linked devices.");
}
}
if (ns.<String>getList("group-id") != null) {
for (var groupIdString : ns.<String>getList("group-id")) {
try {
var groupId = Util.decodeGroupId(groupIdString);
m.setGroupBlocked(groupId, false);
} catch (GroupIdFormatException e) {
logger.warn("Invalid group id: {}", groupIdString);
} catch (GroupNotFoundException e) {
logger.warn("Unknown group id: {}", groupIdString);
}
final var groupIdStrings = ns.<String>getList("group-id");
for (var groupId : CommandUtil.getGroupIds(groupIdStrings)) {
try {
m.setGroupBlocked(groupId, false);
} catch (GroupNotFoundException e) {
logger.warn("Unknown group id: {}", groupId);
}
}
}

View file

@ -9,7 +9,7 @@ import org.asamk.signal.commands.exceptions.IOErrorException;
import org.asamk.signal.commands.exceptions.UserErrorException;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.NotMasterDeviceException;
import org.whispersystems.signalservice.api.util.InvalidNumberException;
import org.asamk.signal.util.CommandUtil;
import java.io.IOException;
@ -32,20 +32,19 @@ public class UpdateContactCommand implements JsonRpcLocalCommand {
public void handleCommand(
final Namespace ns, final Manager m, final OutputWriter outputWriter
) throws CommandException {
var number = ns.getString("number");
var recipientString = ns.getString("number");
var recipient = CommandUtil.getSingleRecipientIdentifier(recipientString, m.getUsername());
try {
var expiration = ns.getInt("expiration");
if (expiration != null) {
m.setExpirationTimer(number, expiration);
m.setExpirationTimer(recipient, expiration);
}
var name = ns.getString("name");
if (name != null) {
m.setContactName(number, name);
m.setContactName(recipient, name);
}
} catch (InvalidNumberException e) {
throw new UserErrorException("Invalid contact number: " + e.getMessage());
} catch (IOException e) {
throw new IOErrorException("Update contact error: " + e.getMessage());
} catch (NotMasterDeviceException e) {

View file

@ -14,17 +14,15 @@ import org.asamk.signal.commands.exceptions.UserErrorException;
import org.asamk.signal.manager.AttachmentInvalidException;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.groups.GroupId;
import org.asamk.signal.manager.groups.GroupIdFormatException;
import org.asamk.signal.manager.groups.GroupLinkState;
import org.asamk.signal.manager.groups.GroupNotFoundException;
import org.asamk.signal.manager.groups.GroupPermission;
import org.asamk.signal.manager.groups.NotAGroupMemberException;
import org.asamk.signal.util.CommandUtil;
import org.asamk.signal.util.ErrorUtils;
import org.asamk.signal.util.Util;
import org.freedesktop.dbus.exceptions.DBusExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.signalservice.api.util.InvalidNumberException;
import java.io.File;
import java.io.IOException;
@ -114,22 +112,17 @@ public class UpdateGroupCommand implements DbusCommand, JsonRpcLocalCommand {
public void handleCommand(
final Namespace ns, final Manager m, final OutputWriter outputWriter
) throws CommandException {
GroupId groupId = null;
final var groupIdString = ns.getString("group-id");
if (groupIdString != null) {
try {
groupId = Util.decodeGroupId(groupIdString);
} catch (GroupIdFormatException e) {
throw new UserErrorException("Invalid group id: " + e.getMessage());
}
}
var groupId = CommandUtil.getGroupId(groupIdString);
final var localNumber = m.getUsername();
var groupName = ns.getString("name");
var groupDescription = ns.getString("description");
var groupMembers = ns.<String>getList("member");
var groupRemoveMembers = ns.<String>getList("remove-member");
var groupAdmins = ns.<String>getList("admin");
var groupRemoveAdmins = ns.<String>getList("remove-admin");
var groupMembers = CommandUtil.getSingleRecipientIdentifiers(ns.getList("member"), localNumber);
var groupRemoveMembers = CommandUtil.getSingleRecipientIdentifiers(ns.getList("remove-member"), localNumber);
var groupAdmins = CommandUtil.getSingleRecipientIdentifiers(ns.getList("admin"), localNumber);
var groupRemoveAdmins = CommandUtil.getSingleRecipientIdentifiers(ns.getList("remove-admin"), localNumber);
var groupAvatar = ns.getString("avatar");
var groupResetLink = ns.getBoolean("reset-link");
var groupLinkState = getGroupLinkState(ns.getString("link"));
@ -140,12 +133,14 @@ public class UpdateGroupCommand implements DbusCommand, JsonRpcLocalCommand {
try {
boolean isNewGroup = false;
Long timestamp = null;
if (groupId == null) {
isNewGroup = true;
var results = m.createGroup(groupName,
groupMembers,
groupAvatar == null ? null : new File(groupAvatar));
ErrorUtils.handleSendMessageResults(results.second());
timestamp = results.second().getTimestamp();
ErrorUtils.handleSendMessageResults(results.second().getResults());
groupId = results.first();
groupName = null;
groupMembers = null;
@ -168,20 +163,15 @@ public class UpdateGroupCommand implements DbusCommand, JsonRpcLocalCommand {
groupSendMessagesPermission == null
? null
: groupSendMessagesPermission == GroupPermission.ONLY_ADMINS);
Long timestamp = null;
if (results != null) {
timestamp = results.first();
ErrorUtils.handleSendMessageResults(results.second());
timestamp = results.getTimestamp();
ErrorUtils.handleSendMessageResults(results.getResults());
}
outputResult(outputWriter, timestamp, isNewGroup ? groupId : null);
} catch (AttachmentInvalidException e) {
throw new UserErrorException("Failed to add avatar attachment for group\": " + e.getMessage());
} catch (GroupNotFoundException e) {
logger.warn("Unknown group id: {}", groupIdString);
} catch (NotAGroupMemberException e) {
logger.warn("You're not a group member");
} catch (InvalidNumberException e) {
throw new UserErrorException("Failed to parse member number: " + e.getMessage());
} catch (GroupNotFoundException | NotAGroupMemberException e) {
throw new UserErrorException(e.getMessage());
} catch (IOException e) {
throw new UnexpectedErrorException("Failed to send message: " + e.getMessage());
}
@ -191,17 +181,7 @@ public class UpdateGroupCommand implements DbusCommand, JsonRpcLocalCommand {
public void handleCommand(
final Namespace ns, final Signal signal, final OutputWriter outputWriter
) throws CommandException {
byte[] groupId = null;
if (ns.getString("group-id") != null) {
try {
groupId = Util.decodeGroupId(ns.getString("group-id")).serialize();
} catch (GroupIdFormatException e) {
throw new UserErrorException("Invalid group id: " + e.getMessage());
}
}
if (groupId == null) {
groupId = new byte[0];
}
var groupId = CommandUtil.getGroupId(ns.getString("group-id"));
var groupName = ns.getString("name");
if (groupName == null) {
@ -219,8 +199,11 @@ public class UpdateGroupCommand implements DbusCommand, JsonRpcLocalCommand {
}
try {
var newGroupId = signal.updateGroup(groupId, groupName, groupMembers, groupAvatar);
if (groupId.length != newGroupId.length) {
var newGroupId = signal.updateGroup(groupId == null ? new byte[0] : groupId.serialize(),
groupName,
groupMembers,
groupAvatar);
if (groupId == null) {
outputResult(outputWriter, null, GroupId.unknownVersion(newGroupId));
}
} catch (Signal.Error.AttachmentInvalid e) {

View file

@ -6,6 +6,7 @@ import org.asamk.signal.manager.AttachmentInvalidException;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.NotMasterDeviceException;
import org.asamk.signal.manager.api.Message;
import org.asamk.signal.manager.api.RecipientIdentifier;
import org.asamk.signal.manager.groups.GroupId;
import org.asamk.signal.manager.groups.GroupInviteLinkUrl;
import org.asamk.signal.manager.groups.GroupNotFoundException;
@ -24,7 +25,10 @@ import org.whispersystems.signalservice.api.util.InvalidNumberException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
@ -59,57 +63,22 @@ public class DbusSignalImpl implements Signal {
return sendMessage(message, attachments, recipients);
}
private static void checkSendMessageResult(long timestamp, SendMessageResult result) throws DBusExecutionException {
var error = ErrorUtils.getErrorMessageFromSendMessageResult(result);
if (error == null) {
return;
}
final var message = timestamp + "\nFailed to send message:\n" + error + '\n';
if (result.getIdentityFailure() != null) {
throw new Error.UntrustedIdentity(message);
} else {
throw new Error.Failure(message);
}
}
private static void checkSendMessageResults(
long timestamp, List<SendMessageResult> results
) throws DBusExecutionException {
if (results.size() == 1) {
checkSendMessageResult(timestamp, results.get(0));
return;
}
var errors = ErrorUtils.getErrorMessagesFromSendMessageResults(results);
if (errors.size() == 0) {
return;
}
var message = new StringBuilder();
message.append(timestamp).append('\n');
message.append("Failed to send (some) messages:\n");
for (var error : errors) {
message.append(error).append('\n');
}
throw new Error.Failure(message.toString());
}
@Override
public long sendMessage(final String message, final List<String> attachments, final List<String> recipients) {
try {
final var results = m.sendMessage(new Message(message, attachments), recipients);
checkSendMessageResults(results.first(), results.second());
return results.first();
} catch (InvalidNumberException e) {
throw new Error.InvalidNumber(e.getMessage());
final var results = m.sendMessage(new Message(message, attachments),
getSingleRecipientIdentifiers(recipients, m.getUsername()).stream()
.map(RecipientIdentifier.class::cast)
.collect(Collectors.toSet()));
checkSendMessageResults(results.getTimestamp(), results.getResults());
return results.getTimestamp();
} catch (AttachmentInvalidException e) {
throw new Error.AttachmentInvalid(e.getMessage());
} catch (IOException e) {
throw new Error.Failure(e.getMessage());
} catch (GroupNotFoundException | NotAGroupMemberException e) {
throw new Error.GroupNotFound(e.getMessage());
}
}
@ -127,13 +96,16 @@ public class DbusSignalImpl implements Signal {
final long targetSentTimestamp, final List<String> recipients
) {
try {
final var results = m.sendRemoteDeleteMessage(targetSentTimestamp, recipients);
checkSendMessageResults(results.first(), results.second());
return results.first();
final var results = m.sendRemoteDeleteMessage(targetSentTimestamp,
getSingleRecipientIdentifiers(recipients, m.getUsername()).stream()
.map(RecipientIdentifier.class::cast)
.collect(Collectors.toSet()));
checkSendMessageResults(results.getTimestamp(), results.getResults());
return results.getTimestamp();
} catch (IOException e) {
throw new Error.Failure(e.getMessage());
} catch (InvalidNumberException e) {
throw new Error.InvalidNumber(e.getMessage());
} catch (GroupNotFoundException | NotAGroupMemberException e) {
throw new Error.GroupNotFound(e.getMessage());
}
}
@ -142,9 +114,10 @@ public class DbusSignalImpl implements Signal {
final long targetSentTimestamp, final byte[] groupId
) {
try {
final var results = m.sendGroupRemoteDeleteMessage(targetSentTimestamp, GroupId.unknownVersion(groupId));
checkSendMessageResults(results.first(), results.second());
return results.first();
final var results = m.sendRemoteDeleteMessage(targetSentTimestamp,
Set.of(new RecipientIdentifier.Group(getGroupId(groupId))));
checkSendMessageResults(results.getTimestamp(), results.getResults());
return results.getTimestamp();
} catch (IOException e) {
throw new Error.Failure(e.getMessage());
} catch (GroupNotFoundException | NotAGroupMemberException e) {
@ -174,13 +147,19 @@ public class DbusSignalImpl implements Signal {
final List<String> recipients
) {
try {
final var results = m.sendMessageReaction(emoji, remove, targetAuthor, targetSentTimestamp, recipients);
checkSendMessageResults(results.first(), results.second());
return results.first();
} catch (InvalidNumberException e) {
throw new Error.InvalidNumber(e.getMessage());
final var results = m.sendMessageReaction(emoji,
remove,
getSingleRecipientIdentifier(targetAuthor, m.getUsername()),
targetSentTimestamp,
getSingleRecipientIdentifiers(recipients, m.getUsername()).stream()
.map(RecipientIdentifier.class::cast)
.collect(Collectors.toSet()));
checkSendMessageResults(results.getTimestamp(), results.getResults());
return results.getTimestamp();
} catch (IOException e) {
throw new Error.Failure(e.getMessage());
} catch (GroupNotFoundException | NotAGroupMemberException e) {
throw new Error.GroupNotFound(e.getMessage());
}
}
@ -189,34 +168,36 @@ public class DbusSignalImpl implements Signal {
final String message, final List<String> attachments
) throws Error.AttachmentInvalid, Error.Failure, Error.UntrustedIdentity {
try {
final var results = m.sendSelfMessage(new Message(message, attachments));
checkSendMessageResult(results.first(), results.second());
return results.first();
final var results = m.sendMessage(new Message(message, attachments),
Set.of(new RecipientIdentifier.NoteToSelf()));
checkSendMessageResults(results.getTimestamp(), results.getResults());
return results.getTimestamp();
} catch (AttachmentInvalidException e) {
throw new Error.AttachmentInvalid(e.getMessage());
} catch (IOException e) {
throw new Error.Failure(e.getMessage());
} catch (GroupNotFoundException | NotAGroupMemberException e) {
throw new Error.GroupNotFound(e.getMessage());
}
}
@Override
public void sendEndSessionMessage(final List<String> recipients) {
try {
final var results = m.sendEndSessionMessage(recipients);
checkSendMessageResults(results.first(), results.second());
final var results = m.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients, m.getUsername()));
checkSendMessageResults(results.getTimestamp(), results.getResults());
} catch (IOException e) {
throw new Error.Failure(e.getMessage());
} catch (InvalidNumberException e) {
throw new Error.InvalidNumber(e.getMessage());
}
}
@Override
public long sendGroupMessage(final String message, final List<String> attachments, final byte[] groupId) {
try {
var results = m.sendGroupMessage(new Message(message, attachments), GroupId.unknownVersion(groupId));
checkSendMessageResults(results.first(), results.second());
return results.first();
var results = m.sendMessage(new Message(message, attachments),
Set.of(new RecipientIdentifier.Group(getGroupId(groupId))));
checkSendMessageResults(results.getTimestamp(), results.getResults());
return results.getTimestamp();
} catch (IOException e) {
throw new Error.Failure(e.getMessage());
} catch (GroupNotFoundException | NotAGroupMemberException e) {
@ -235,17 +216,15 @@ public class DbusSignalImpl implements Signal {
final byte[] groupId
) {
try {
final var results = m.sendGroupMessageReaction(emoji,
final var results = m.sendMessageReaction(emoji,
remove,
targetAuthor,
getSingleRecipientIdentifier(targetAuthor, m.getUsername()),
targetSentTimestamp,
GroupId.unknownVersion(groupId));
checkSendMessageResults(results.first(), results.second());
return results.first();
Set.of(new RecipientIdentifier.Group(getGroupId(groupId))));
checkSendMessageResults(results.getTimestamp(), results.getResults());
return results.getTimestamp();
} catch (IOException e) {
throw new Error.Failure(e.getMessage());
} catch (InvalidNumberException e) {
throw new Error.InvalidNumber(e.getMessage());
} catch (GroupNotFoundException | NotAGroupMemberException e) {
throw new Error.GroupNotFound(e.getMessage());
}
@ -255,19 +234,13 @@ public class DbusSignalImpl implements Signal {
// the profile name
@Override
public String getContactName(final String number) {
try {
return m.getContactOrProfileName(number);
} catch (InvalidNumberException e) {
throw new Error.InvalidNumber(e.getMessage());
}
return m.getContactOrProfileName(getSingleRecipientIdentifier(number, m.getUsername()));
}
@Override
public void setContactName(final String number, final String name) {
try {
m.setContactName(number, name);
} catch (InvalidNumberException e) {
throw new Error.InvalidNumber(e.getMessage());
m.setContactName(getSingleRecipientIdentifier(number, m.getUsername()), name);
} catch (NotMasterDeviceException e) {
throw new Error.Failure("This command doesn't work on linked devices.");
}
@ -276,9 +249,7 @@ public class DbusSignalImpl implements Signal {
@Override
public void setContactBlocked(final String number, final boolean blocked) {
try {
m.setContactBlocked(number, blocked);
} catch (InvalidNumberException e) {
throw new Error.InvalidNumber(e.getMessage());
m.setContactBlocked(getSingleRecipientIdentifier(number, m.getUsername()), blocked);
} catch (NotMasterDeviceException e) {
throw new Error.Failure("This command doesn't work on linked devices.");
}
@ -287,7 +258,7 @@ public class DbusSignalImpl implements Signal {
@Override
public void setGroupBlocked(final byte[] groupId, final boolean blocked) {
try {
m.setGroupBlocked(GroupId.unknownVersion(groupId), blocked);
m.setGroupBlocked(getGroupId(groupId), blocked);
} catch (GroupNotFoundException e) {
throw new Error.GroupNotFound(e.getMessage());
}
@ -305,7 +276,7 @@ public class DbusSignalImpl implements Signal {
@Override
public String getGroupName(final byte[] groupId) {
var group = m.getGroup(GroupId.unknownVersion(groupId));
var group = m.getGroup(getGroupId(groupId));
if (group == null) {
return "";
} else {
@ -315,7 +286,7 @@ public class DbusSignalImpl implements Signal {
@Override
public List<String> getGroupMembers(final byte[] groupId) {
var group = m.getGroup(GroupId.unknownVersion(groupId));
var group = m.getGroup(getGroupId(groupId));
if (group == null) {
return List.of();
} else {
@ -336,21 +307,19 @@ public class DbusSignalImpl implements Signal {
if (name.isEmpty()) {
name = null;
}
if (members.isEmpty()) {
members = null;
}
if (avatar.isEmpty()) {
avatar = null;
}
final var memberIdentifiers = getSingleRecipientIdentifiers(members, m.getUsername());
if (groupId == null) {
final var results = m.createGroup(name, members, avatar == null ? null : new File(avatar));
checkSendMessageResults(0, results.second());
final var results = m.createGroup(name, memberIdentifiers, avatar == null ? null : new File(avatar));
checkSendMessageResults(results.second().getTimestamp(), results.second().getResults());
return results.first().serialize();
} else {
final var results = m.updateGroup(GroupId.unknownVersion(groupId),
final var results = m.updateGroup(getGroupId(groupId),
name,
null,
members,
memberIdentifiers,
null,
null,
null,
@ -362,7 +331,7 @@ public class DbusSignalImpl implements Signal {
null,
null);
if (results != null) {
checkSendMessageResults(results.first(), results.second());
checkSendMessageResults(results.getTimestamp(), results.getResults());
}
return groupId;
}
@ -370,8 +339,6 @@ public class DbusSignalImpl implements Signal {
throw new Error.Failure(e.getMessage());
} catch (GroupNotFoundException | NotAGroupMemberException e) {
throw new Error.GroupNotFound(e.getMessage());
} catch (InvalidNumberException e) {
throw new Error.InvalidNumber(e.getMessage());
} catch (AttachmentInvalidException e) {
throw new Error.AttachmentInvalid(e.getMessage());
}
@ -450,26 +417,25 @@ public class DbusSignalImpl implements Signal {
@Override
public void quitGroup(final byte[] groupId) {
var group = GroupId.unknownVersion(groupId);
var group = getGroupId(groupId);
try {
m.sendQuitGroupMessage(group, Set.of());
} catch (GroupNotFoundException | NotAGroupMemberException e) {
throw new Error.GroupNotFound(e.getMessage());
} catch (IOException | LastGroupAdminException e) {
throw new Error.Failure(e.getMessage());
} catch (InvalidNumberException e) {
throw new Error.InvalidNumber(e.getMessage());
}
}
@Override
public void joinGroup(final String groupLink) {
public byte[] joinGroup(final String groupLink) {
try {
final var linkUrl = GroupInviteLinkUrl.fromUri(groupLink);
if (linkUrl == null) {
throw new Error.Failure("Group link is invalid:");
}
m.joinGroup(linkUrl);
final var result = m.joinGroup(linkUrl);
return result.first().serialize();
} catch (GroupInviteLinkUrl.InvalidGroupLinkException | GroupLinkNotActiveException e) {
throw new Error.Failure("Group link is invalid: " + e.getMessage());
} catch (GroupInviteLinkUrl.UnknownGroupLinkVersionException e) {
@ -481,16 +447,12 @@ public class DbusSignalImpl implements Signal {
@Override
public boolean isContactBlocked(final String number) {
try {
return m.isContactBlocked(number);
} catch (InvalidNumberException e) {
throw new Error.InvalidNumber(e.getMessage());
}
return m.isContactBlocked(getSingleRecipientIdentifier(number, m.getUsername()));
}
@Override
public boolean isGroupBlocked(final byte[] groupId) {
var group = m.getGroup(GroupId.unknownVersion(groupId));
var group = m.getGroup(getGroupId(groupId));
if (group == null) {
return false;
} else {
@ -500,11 +462,102 @@ public class DbusSignalImpl implements Signal {
@Override
public boolean isMember(final byte[] groupId) {
var group = m.getGroup(GroupId.unknownVersion(groupId));
var group = m.getGroup(getGroupId(groupId));
if (group == null) {
return false;
} else {
return group.isMember(m.getSelfRecipientId());
}
}
private static void checkSendMessageResult(long timestamp, SendMessageResult result) throws DBusExecutionException {
var error = ErrorUtils.getErrorMessageFromSendMessageResult(result);
if (error == null) {
return;
}
final var message = timestamp + "\nFailed to send message:\n" + error + '\n';
if (result.getIdentityFailure() != null) {
throw new Error.UntrustedIdentity(message);
} else {
throw new Error.Failure(message);
}
}
private static void checkSendMessageResults(
long timestamp, Map<RecipientIdentifier, List<SendMessageResult>> results
) throws DBusExecutionException {
final var sendMessageResults = results.values().stream().findFirst();
if (results.size() == 1 && sendMessageResults.get().size() == 1) {
checkSendMessageResult(timestamp, sendMessageResults.get().stream().findFirst().get());
return;
}
var errors = ErrorUtils.getErrorMessagesFromSendMessageResults(results);
if (errors.size() == 0) {
return;
}
var message = new StringBuilder();
message.append(timestamp).append('\n');
message.append("Failed to send (some) messages:\n");
for (var error : errors) {
message.append(error).append('\n');
}
throw new Error.Failure(message.toString());
}
private static void checkSendMessageResults(
long timestamp, Collection<SendMessageResult> results
) throws DBusExecutionException {
if (results.size() == 1) {
checkSendMessageResult(timestamp, results.stream().findFirst().get());
return;
}
var errors = ErrorUtils.getErrorMessagesFromSendMessageResults(results);
if (errors.size() == 0) {
return;
}
var message = new StringBuilder();
message.append(timestamp).append('\n');
message.append("Failed to send (some) messages:\n");
for (var error : errors) {
message.append(error).append('\n');
}
throw new Error.Failure(message.toString());
}
private static Set<RecipientIdentifier.Single> getSingleRecipientIdentifiers(
final Collection<String> recipientStrings, final String localNumber
) throws DBusExecutionException {
final var identifiers = new HashSet<RecipientIdentifier.Single>();
for (var recipientString : recipientStrings) {
identifiers.add(getSingleRecipientIdentifier(recipientString, localNumber));
}
return identifiers;
}
private static RecipientIdentifier.Single getSingleRecipientIdentifier(
final String recipientString, final String localNumber
) throws DBusExecutionException {
try {
return RecipientIdentifier.Single.fromString(recipientString, localNumber);
} catch (InvalidNumberException e) {
throw new Error.InvalidNumber(e.getMessage());
}
}
private static GroupId getGroupId(byte[] groupId) throws DBusExecutionException {
try {
return GroupId.unknownVersion(groupId);
} catch (Throwable e) {
throw new Error.InvalidGroupId("Invalid group id: " + e.getMessage());
}
}
}

View file

@ -5,6 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import org.asamk.Signal;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.api.RecipientIdentifier;
import org.signal.libsignal.metadata.ProtocolUntrustedIdentityException;
import org.whispersystems.signalservice.api.messages.SignalServiceContent;
import org.whispersystems.signalservice.api.messages.SignalServiceEnvelope;
@ -94,7 +95,7 @@ public class JsonMessageEnvelope {
}
String name;
try {
name = m.getContactOrProfileName(this.source);
name = m.getContactOrProfileName(RecipientIdentifier.Single.fromString(this.source, m.getUsername()));
} catch (InvalidNumberException | NullPointerException e) {
name = null;
}

View file

@ -0,0 +1,99 @@
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<RecipientIdentifier> getRecipientIdentifiers(
final Manager m,
final boolean isNoteToSelf,
final List<String> recipientStrings,
final List<String> groupIdStrings
) throws UserErrorException {
final var recipientIdentifiers = new HashSet<RecipientIdentifier>();
if (isNoteToSelf) {
recipientIdentifiers.add(new RecipientIdentifier.NoteToSelf());
}
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<RecipientIdentifier.Group> getGroupIdentifiers(Collection<String> groupIdStrings) throws UserErrorException {
if (groupIdStrings == null) {
return Set.of();
}
final var groupIds = new HashSet<RecipientIdentifier.Group>();
for (final var groupIdString : groupIdStrings) {
groupIds.add(new RecipientIdentifier.Group(getGroupId(groupIdString)));
}
return groupIds;
}
public static Set<GroupId> getGroupIds(Collection<String> groupIdStrings) throws UserErrorException {
if (groupIdStrings == null) {
return Set.of();
}
final var groupIds = new HashSet<GroupId>();
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<RecipientIdentifier.Single> getSingleRecipientIdentifiers(
final Collection<String> recipientStrings, final String localNumber
) throws UserErrorException {
if (recipientStrings == null) {
return Set.of();
}
final var identifiers = new HashSet<RecipientIdentifier.Single>();
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());
}
}
}

View file

@ -2,13 +2,16 @@ package org.asamk.signal.util;
import org.asamk.signal.commands.exceptions.CommandException;
import org.asamk.signal.commands.exceptions.IOErrorException;
import org.asamk.signal.manager.api.RecipientIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.signalservice.api.messages.SendMessageResult;
import org.whispersystems.signalservice.api.push.exceptions.ProofRequiredException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.asamk.signal.util.Util.getLegacyIdentifier;
@ -21,13 +24,27 @@ public class ErrorUtils {
}
public static void handleSendMessageResults(
List<SendMessageResult> results
Map<RecipientIdentifier, List<SendMessageResult>> mapResults
) throws CommandException {
List<String> errors = getErrorMessagesFromSendMessageResults(mapResults);
handleSendMessageResultErrors(errors);
}
public static void handleSendMessageResults(
Collection<SendMessageResult> results
) throws CommandException {
var errors = getErrorMessagesFromSendMessageResults(results);
handleSendMessageResultErrors(errors);
}
public static List<String> getErrorMessagesFromSendMessageResults(List<SendMessageResult> results) {
public static List<String> getErrorMessagesFromSendMessageResults(final Map<RecipientIdentifier, List<SendMessageResult>> mapResults) {
return mapResults.values()
.stream()
.flatMap(results -> getErrorMessagesFromSendMessageResults(results).stream())
.collect(Collectors.toList());
}
public static List<String> getErrorMessagesFromSendMessageResults(Collection<SendMessageResult> results) {
var errors = new ArrayList<String>();
for (var result : results) {
var error = getErrorMessageFromSendMessageResult(result);

View file

@ -5,8 +5,6 @@ import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.asamk.signal.manager.groups.GroupId;
import org.asamk.signal.manager.groups.GroupIdFormatException;
import org.whispersystems.libsignal.util.guava.Optional;
import org.whispersystems.signalservice.api.push.SignalServiceAddress;
@ -61,10 +59,6 @@ public class Util {
return f.toString();
}
public static GroupId decodeGroupId(String groupId) throws GroupIdFormatException {
return GroupId.fromBase64(groupId);
}
public static String getLegacyIdentifier(final SignalServiceAddress address) {
return address.getNumber().or(() -> address.getUuid().get().toString());
}