Use PlainTextWriter for all cli stdout output

This commit is contained in:
AsamK 2021-02-22 19:16:51 +01:00
parent de273586b4
commit c6395b9f35
14 changed files with 220 additions and 99 deletions

View file

@ -6,6 +6,7 @@ import net.sourceforge.argparse4j.inf.Subparser;
import org.asamk.signal.JsonWriter; import org.asamk.signal.JsonWriter;
import org.asamk.signal.OutputType; import org.asamk.signal.OutputType;
import org.asamk.signal.PlainTextWriterImpl;
import org.asamk.signal.manager.Manager; import org.asamk.signal.manager.Manager;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -69,8 +70,15 @@ public class GetUserStatusCommand implements LocalCommand {
return 3; return 3;
} }
} else { } else {
for (var entry : registered.entrySet()) { final var writer = new PlainTextWriterImpl(System.out);
System.out.println(entry.getKey() + ": " + entry.getValue());
try {
for (var entry : registered.entrySet()) {
writer.println("{}: {}", entry.getKey(), entry.getValue());
}
} catch (IOException e) {
e.printStackTrace();
return 3;
} }
} }

View file

@ -3,9 +3,12 @@ package org.asamk.signal.commands;
import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser; import net.sourceforge.argparse4j.inf.Subparser;
import org.asamk.signal.PlainTextWriterImpl;
import org.asamk.signal.manager.Manager; import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.groups.GroupInviteLinkUrl; import org.asamk.signal.manager.groups.GroupInviteLinkUrl;
import org.freedesktop.dbus.exceptions.DBusExecutionException; import org.freedesktop.dbus.exceptions.DBusExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.signalservice.api.groupsv2.GroupLinkNotActiveException; import org.whispersystems.signalservice.api.groupsv2.GroupLinkNotActiveException;
import org.whispersystems.signalservice.internal.push.exceptions.GroupPatchNotAcceptedException; import org.whispersystems.signalservice.internal.push.exceptions.GroupPatchNotAcceptedException;
@ -17,6 +20,8 @@ import static org.asamk.signal.util.ErrorUtils.handleTimestampAndSendMessageResu
public class JoinGroupCommand implements LocalCommand { public class JoinGroupCommand implements LocalCommand {
private final static Logger logger = LoggerFactory.getLogger(JoinGroupCommand.class);
@Override @Override
public void attachToSubparser(final Subparser subparser) { public void attachToSubparser(final Subparser subparser) {
subparser.addArgument("--uri").required(true).help("Specify the uri with the group invitation link."); subparser.addArgument("--uri").required(true).help("Specify the uri with the group invitation link.");
@ -42,14 +47,16 @@ public class JoinGroupCommand implements LocalCommand {
} }
try { try {
final var writer = new PlainTextWriterImpl(System.out);
final var results = m.joinGroup(linkUrl); final var results = m.joinGroup(linkUrl);
var newGroupId = results.first(); var newGroupId = results.first();
if (!m.getGroup(newGroupId).isMember(m.getSelfAddress())) { if (!m.getGroup(newGroupId).isMember(m.getSelfAddress())) {
System.out.println("Requested to join group \"" + newGroupId.toBase64() + "\""); writer.println("Requested to join group \"{}\"", newGroupId.toBase64());
} else { } else {
System.out.println("Joined group \"" + newGroupId.toBase64() + "\""); writer.println("Joined group \"{}\"", newGroupId.toBase64());
} }
return handleTimestampAndSendMessageResults(0, results.second()); return handleTimestampAndSendMessageResults(writer, 0, results.second());
} catch (AssertionError e) { } catch (AssertionError e) {
handleAssertionError(e); handleAssertionError(e);
return 1; return 1;

View file

@ -3,8 +3,11 @@ package org.asamk.signal.commands;
import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser; import net.sourceforge.argparse4j.inf.Subparser;
import org.asamk.signal.PlainTextWriterImpl;
import org.asamk.signal.manager.ProvisioningManager; import org.asamk.signal.manager.ProvisioningManager;
import org.asamk.signal.manager.UserAlreadyExists; import org.asamk.signal.manager.UserAlreadyExists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.libsignal.InvalidKeyException; import org.whispersystems.libsignal.InvalidKeyException;
import java.io.IOException; import java.io.IOException;
@ -14,6 +17,8 @@ import static org.asamk.signal.util.ErrorUtils.handleAssertionError;
public class LinkCommand implements ProvisioningCommand { public class LinkCommand implements ProvisioningCommand {
private final static Logger logger = LoggerFactory.getLogger(LinkCommand.class);
@Override @Override
public void attachToSubparser(final Subparser subparser) { public void attachToSubparser(final Subparser subparser) {
subparser.addArgument("-n", "--name").help("Specify a name to describe this new device."); subparser.addArgument("-n", "--name").help("Specify a name to describe this new device.");
@ -21,14 +26,16 @@ public class LinkCommand implements ProvisioningCommand {
@Override @Override
public int handleCommand(final Namespace ns, final ProvisioningManager m) { public int handleCommand(final Namespace ns, final ProvisioningManager m) {
final var writer = new PlainTextWriterImpl(System.out);
var deviceName = ns.getString("name"); var deviceName = ns.getString("name");
if (deviceName == null) { if (deviceName == null) {
deviceName = "cli"; deviceName = "cli";
} }
try { try {
System.out.println(m.getDeviceLinkUri()); writer.println("{}", m.getDeviceLinkUri());
var username = m.finishDeviceLink(deviceName); var username = m.finishDeviceLink(deviceName);
System.out.println("Associated with: " + username); writer.println("Associated with: {}", username);
} catch (TimeoutException e) { } catch (TimeoutException e) {
System.err.println("Link request timed out, please try again."); System.err.println("Link request timed out, please try again.");
return 3; return 3;

View file

@ -3,8 +3,11 @@ package org.asamk.signal.commands;
import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser; import net.sourceforge.argparse4j.inf.Subparser;
import org.asamk.signal.PlainTextWriterImpl;
import org.asamk.signal.manager.Manager; import org.asamk.signal.manager.Manager;
import java.io.IOException;
public class ListContactsCommand implements LocalCommand { public class ListContactsCommand implements LocalCommand {
@Override @Override
@ -13,9 +16,16 @@ public class ListContactsCommand implements LocalCommand {
@Override @Override
public int handleCommand(final Namespace ns, final Manager m) { public int handleCommand(final Namespace ns, final Manager m) {
final var writer = new PlainTextWriterImpl(System.out);
var contacts = m.getContacts(); var contacts = m.getContacts();
for (var c : contacts) { try {
System.out.println(String.format("Number: %s Name: %s Blocked: %b", c.number, c.name, c.blocked)); for (var c : contacts) {
writer.println("Number: {} Name: {} Blocked: {}", c.number, c.name, c.blocked);
}
} catch (IOException e) {
e.printStackTrace();
return 3;
} }
return 0; return 0;
} }

View file

@ -3,6 +3,7 @@ package org.asamk.signal.commands;
import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser; import net.sourceforge.argparse4j.inf.Subparser;
import org.asamk.signal.PlainTextWriterImpl;
import org.asamk.signal.manager.Manager; import org.asamk.signal.manager.Manager;
import org.asamk.signal.util.DateUtils; import org.asamk.signal.util.DateUtils;
@ -16,16 +17,16 @@ public class ListDevicesCommand implements LocalCommand {
@Override @Override
public int handleCommand(final Namespace ns, final Manager m) { public int handleCommand(final Namespace ns, final Manager m) {
final var writer = new PlainTextWriterImpl(System.out);
try { try {
var devices = m.getLinkedDevices(); var devices = m.getLinkedDevices();
for (var d : devices) { for (var d : devices) {
System.out.println("Device " writer.println("- Device {}{}:", d.getId(), (d.getId() == m.getDeviceId() ? " (this device)" : ""));
+ d.getId() writer.indent(w -> {
+ (d.getId() == m.getDeviceId() ? " (this device)" : "") w.println("Name: {}", d.getName());
+ ":"); w.println("Created: {}", DateUtils.formatTimestamp(d.getCreated()));
System.out.println(" Name: " + d.getName()); w.println("Last seen: {}", DateUtils.formatTimestamp(d.getLastSeen()));
System.out.println(" Created: " + DateUtils.formatTimestamp(d.getCreated())); });
System.out.println(" Last seen: " + DateUtils.formatTimestamp(d.getLastSeen()));
} }
return 0; return 0;
} catch (IOException e) { } catch (IOException e) {

View file

@ -6,6 +6,8 @@ import net.sourceforge.argparse4j.inf.Subparser;
import org.asamk.signal.JsonWriter; import org.asamk.signal.JsonWriter;
import org.asamk.signal.OutputType; import org.asamk.signal.OutputType;
import org.asamk.signal.PlainTextWriter;
import org.asamk.signal.PlainTextWriterImpl;
import org.asamk.signal.manager.Manager; import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.storage.groups.GroupInfo; import org.asamk.signal.manager.storage.groups.GroupInfo;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -28,12 +30,14 @@ public class ListGroupsCommand implements LocalCommand {
.collect(Collectors.toSet()); .collect(Collectors.toSet());
} }
private static void printGroupPlainText(Manager m, GroupInfo group, boolean detailed) { private static void printGroupPlainText(
PlainTextWriter writer, Manager m, GroupInfo group, boolean detailed
) throws IOException {
if (detailed) { if (detailed) {
final var groupInviteLink = group.getGroupInviteLink(); final var groupInviteLink = group.getGroupInviteLink();
System.out.println(String.format( writer.println(
"Id: %s Name: %s Active: %s Blocked: %b Members: %s Pending members: %s Requesting members: %s Link: %s", "Id: {} Name: {} Active: {} Blocked: {} Members: {} Pending members: {} Requesting members: {} Link: {}",
group.getGroupId().toBase64(), group.getGroupId().toBase64(),
group.getTitle(), group.getTitle(),
group.isMember(m.getSelfAddress()), group.isMember(m.getSelfAddress()),
@ -41,13 +45,13 @@ public class ListGroupsCommand implements LocalCommand {
resolveMembers(m, group.getMembers()), resolveMembers(m, group.getMembers()),
resolveMembers(m, group.getPendingMembers()), resolveMembers(m, group.getPendingMembers()),
resolveMembers(m, group.getRequestingMembers()), resolveMembers(m, group.getRequestingMembers()),
groupInviteLink == null ? '-' : groupInviteLink.getUrl())); groupInviteLink == null ? '-' : groupInviteLink.getUrl());
} else { } else {
System.out.println(String.format("Id: %s Name: %s Active: %s Blocked: %b", writer.println("Id: {} Name: {} Active: {} Blocked: {}",
group.getGroupId().toBase64(), group.getGroupId().toBase64(),
group.getTitle(), group.getTitle(),
group.isMember(m.getSelfAddress()), group.isMember(m.getSelfAddress()),
group.isBlocked())); group.isBlocked());
} }
} }
@ -93,9 +97,15 @@ public class ListGroupsCommand implements LocalCommand {
return 0; return 0;
} else { } else {
final var writer = new PlainTextWriterImpl(System.out);
boolean detailed = ns.getBoolean("detailed"); boolean detailed = ns.getBoolean("detailed");
for (var group : m.getGroups()) { try {
printGroupPlainText(m, group, detailed); for (var group : m.getGroups()) {
printGroupPlainText(writer, m, group, detailed);
}
} catch (IOException e) {
e.printStackTrace();
return 3;
} }
} }

View file

@ -3,22 +3,34 @@ package org.asamk.signal.commands;
import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser; import net.sourceforge.argparse4j.inf.Subparser;
import org.asamk.signal.PlainTextWriter;
import org.asamk.signal.PlainTextWriterImpl;
import org.asamk.signal.manager.Manager; import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.storage.protocol.IdentityInfo; import org.asamk.signal.manager.storage.protocol.IdentityInfo;
import org.asamk.signal.util.Hex; import org.asamk.signal.util.Hex;
import org.asamk.signal.util.Util; import org.asamk.signal.util.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.signalservice.api.util.InvalidNumberException; import org.whispersystems.signalservice.api.util.InvalidNumberException;
import java.io.IOException;
public class ListIdentitiesCommand implements LocalCommand { public class ListIdentitiesCommand implements LocalCommand {
private static void printIdentityFingerprint(Manager m, IdentityInfo theirId) { private final static Logger logger = LoggerFactory.getLogger(ListIdentitiesCommand.class);
private static void printIdentityFingerprint(PlainTextWriter writer, Manager m, IdentityInfo theirId) {
var digits = Util.formatSafetyNumber(m.computeSafetyNumber(theirId.getAddress(), theirId.getIdentityKey())); var digits = Util.formatSafetyNumber(m.computeSafetyNumber(theirId.getAddress(), theirId.getIdentityKey()));
System.out.println(String.format("%s: %s Added: %s Fingerprint: %s Safety Number: %s", try {
theirId.getAddress().getNumber().orNull(), writer.println("{}: {} Added: {} Fingerprint: {} Safety Number: {}",
theirId.getTrustLevel(), theirId.getAddress().getNumber().orNull(),
theirId.getDateAdded(), theirId.getTrustLevel(),
Hex.toString(theirId.getFingerprint()), theirId.getDateAdded(),
digits)); Hex.toString(theirId.getFingerprint()),
digits);
} catch (IOException e) {
e.printStackTrace();
}
} }
@Override @Override
@ -28,16 +40,18 @@ public class ListIdentitiesCommand implements LocalCommand {
@Override @Override
public int handleCommand(final Namespace ns, final Manager m) { public int handleCommand(final Namespace ns, final Manager m) {
final var writer = new PlainTextWriterImpl(System.out);
if (ns.get("number") == null) { if (ns.get("number") == null) {
for (var identity : m.getIdentities()) { for (var identity : m.getIdentities()) {
printIdentityFingerprint(m, identity); printIdentityFingerprint(writer, m, identity);
} }
} else { } else {
var number = ns.getString("number"); var number = ns.getString("number");
try { try {
var identities = m.getIdentities(number); var identities = m.getIdentities(number);
for (var id : identities) { for (var id : identities) {
printIdentityFingerprint(m, id); printIdentityFingerprint(writer, m, id);
} }
} catch (InvalidNumberException e) { } catch (InvalidNumberException e) {
System.err.println("Invalid number: " + e.getMessage()); System.err.println("Invalid number: " + e.getMessage());

View file

@ -3,6 +3,7 @@ package org.asamk.signal.commands;
import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser; import net.sourceforge.argparse4j.inf.Subparser;
import org.asamk.signal.PlainTextWriterImpl;
import org.asamk.signal.manager.Manager; import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.groups.GroupIdFormatException; import org.asamk.signal.manager.groups.GroupIdFormatException;
import org.asamk.signal.manager.groups.GroupNotFoundException; import org.asamk.signal.manager.groups.GroupNotFoundException;
@ -28,9 +29,11 @@ public class QuitGroupCommand implements LocalCommand {
@Override @Override
public int handleCommand(final Namespace ns, final Manager m) { public int handleCommand(final Namespace ns, final Manager m) {
try { try {
final var writer = new PlainTextWriterImpl(System.out);
final var groupId = Util.decodeGroupId(ns.getString("group")); final var groupId = Util.decodeGroupId(ns.getString("group"));
final var results = m.sendQuitGroupMessage(groupId); final var results = m.sendQuitGroupMessage(groupId);
return handleTimestampAndSendMessageResults(results.first(), results.second()); return handleTimestampAndSendMessageResults(writer, results.first(), results.second());
} catch (IOException e) { } catch (IOException e) {
handleIOException(e); handleIOException(e);
return 3; return 3;

View file

@ -8,6 +8,7 @@ import org.asamk.Signal;
import org.asamk.signal.JsonReceiveMessageHandler; import org.asamk.signal.JsonReceiveMessageHandler;
import org.asamk.signal.JsonWriter; import org.asamk.signal.JsonWriter;
import org.asamk.signal.OutputType; import org.asamk.signal.OutputType;
import org.asamk.signal.PlainTextWriterImpl;
import org.asamk.signal.ReceiveMessageHandler; import org.asamk.signal.ReceiveMessageHandler;
import org.asamk.signal.json.JsonMessageEnvelope; import org.asamk.signal.json.JsonMessageEnvelope;
import org.asamk.signal.manager.Manager; import org.asamk.signal.manager.Manager;
@ -55,10 +56,11 @@ public class ReceiveCommand implements ExtendedDbusCommand, LocalCommand {
logger.warn("\"--json\" option has been deprecated, please use the global \"--output=json\" instead."); logger.warn("\"--json\" option has been deprecated, please use the global \"--output=json\" instead.");
} }
final var jsonWriter = inJson ? new JsonWriter(System.out) : null;
try { try {
dbusconnection.addSigHandler(Signal.MessageReceived.class, messageReceived -> { if (inJson) {
if (jsonWriter != null) { final var jsonWriter = new JsonWriter(System.out);
dbusconnection.addSigHandler(Signal.MessageReceived.class, messageReceived -> {
var envelope = new JsonMessageEnvelope(messageReceived); var envelope = new JsonMessageEnvelope(messageReceived);
final var object = Map.of("envelope", envelope); final var object = Map.of("envelope", envelope);
try { try {
@ -66,27 +68,9 @@ public class ReceiveCommand implements ExtendedDbusCommand, LocalCommand {
} catch (IOException e) { } catch (IOException e) {
logger.error("Failed to write json object: {}", e.getMessage()); logger.error("Failed to write json object: {}", e.getMessage());
} }
} else { });
System.out.print(String.format("Envelope from: %s\nTimestamp: %s\nBody: %s\n",
messageReceived.getSender(),
DateUtils.formatTimestamp(messageReceived.getTimestamp()),
messageReceived.getMessage()));
if (messageReceived.getGroupId().length > 0) {
System.out.println("Group info:");
System.out.println(" Id: " + Base64.getEncoder().encodeToString(messageReceived.getGroupId()));
}
if (messageReceived.getAttachments().size() > 0) {
System.out.println("Attachments: ");
for (var attachment : messageReceived.getAttachments()) {
System.out.println("- Stored plaintext in: " + attachment);
}
}
System.out.println();
}
});
dbusconnection.addSigHandler(Signal.ReceiptReceived.class, receiptReceived -> { dbusconnection.addSigHandler(Signal.ReceiptReceived.class, receiptReceived -> {
if (jsonWriter != null) {
var envelope = new JsonMessageEnvelope(receiptReceived); var envelope = new JsonMessageEnvelope(receiptReceived);
final var object = Map.of("envelope", envelope); final var object = Map.of("envelope", envelope);
try { try {
@ -94,15 +78,9 @@ public class ReceiveCommand implements ExtendedDbusCommand, LocalCommand {
} catch (IOException e) { } catch (IOException e) {
logger.error("Failed to write json object: {}", e.getMessage()); logger.error("Failed to write json object: {}", e.getMessage());
} }
} else { });
System.out.print(String.format("Receipt from: %s\nTimestamp: %s\n",
receiptReceived.getSender(),
DateUtils.formatTimestamp(receiptReceived.getTimestamp())));
}
});
dbusconnection.addSigHandler(Signal.SyncMessageReceived.class, syncReceived -> { dbusconnection.addSigHandler(Signal.SyncMessageReceived.class, syncReceived -> {
if (jsonWriter != null) {
var envelope = new JsonMessageEnvelope(syncReceived); var envelope = new JsonMessageEnvelope(syncReceived);
final var object = Map.of("envelope", envelope); final var object = Map.of("envelope", envelope);
try { try {
@ -110,25 +88,66 @@ public class ReceiveCommand implements ExtendedDbusCommand, LocalCommand {
} catch (IOException e) { } catch (IOException e) {
logger.error("Failed to write json object: {}", e.getMessage()); logger.error("Failed to write json object: {}", e.getMessage());
} }
} else { });
System.out.print(String.format("Sync Envelope from: %s to: %s\nTimestamp: %s\nBody: %s\n", } else {
syncReceived.getSource(), final var writer = new PlainTextWriterImpl(System.out);
syncReceived.getDestination(),
DateUtils.formatTimestamp(syncReceived.getTimestamp()), dbusconnection.addSigHandler(Signal.MessageReceived.class, messageReceived -> {
syncReceived.getMessage())); try {
if (syncReceived.getGroupId().length > 0) { writer.println("Envelope from: {}", messageReceived.getSender());
System.out.println("Group info:"); writer.println("Timestamp: {}", DateUtils.formatTimestamp(messageReceived.getTimestamp()));
System.out.println(" Id: " + Base64.getEncoder().encodeToString(syncReceived.getGroupId())); writer.println("Body: {}", messageReceived.getMessage());
} if (messageReceived.getGroupId().length > 0) {
if (syncReceived.getAttachments().size() > 0) { writer.println("Group info:");
System.out.println("Attachments: "); writer.indentedWriter()
for (var attachment : syncReceived.getAttachments()) { .println("Id: {}",
System.out.println("- Stored plaintext in: " + attachment); Base64.getEncoder().encodeToString(messageReceived.getGroupId()));
} }
if (messageReceived.getAttachments().size() > 0) {
writer.println("Attachments:");
for (var attachment : messageReceived.getAttachments()) {
writer.println("- Stored plaintext in: {}", attachment);
}
}
writer.println();
} catch (IOException e) {
e.printStackTrace();
} }
System.out.println(); });
}
}); dbusconnection.addSigHandler(Signal.ReceiptReceived.class, receiptReceived -> {
try {
writer.println("Receipt from: {}", receiptReceived.getSender());
writer.println("Timestamp: {}", DateUtils.formatTimestamp(receiptReceived.getTimestamp()));
} catch (IOException e) {
e.printStackTrace();
}
});
dbusconnection.addSigHandler(Signal.SyncMessageReceived.class, syncReceived -> {
try {
writer.println("Sync Envelope from: {} to: {}",
syncReceived.getSource(),
syncReceived.getDestination());
writer.println("Timestamp: {}", DateUtils.formatTimestamp(syncReceived.getTimestamp()));
writer.println("Body: {}", syncReceived.getMessage());
if (syncReceived.getGroupId().length > 0) {
writer.println("Group info:");
writer.indentedWriter()
.println("Id: {}", Base64.getEncoder().encodeToString(syncReceived.getGroupId()));
}
if (syncReceived.getAttachments().size() > 0) {
writer.println("Attachments:");
for (var attachment : syncReceived.getAttachments()) {
writer.println("- Stored plaintext in: {}", attachment);
}
}
writer.println();
} catch (IOException e) {
e.printStackTrace();
}
});
}
} catch (DBusException e) { } catch (DBusException e) {
e.printStackTrace(); e.printStackTrace();
return 2; return 2;

View file

@ -5,11 +5,14 @@ import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser; import net.sourceforge.argparse4j.inf.Subparser;
import org.asamk.Signal; import org.asamk.Signal;
import org.asamk.signal.PlainTextWriterImpl;
import org.asamk.signal.manager.groups.GroupIdFormatException; import org.asamk.signal.manager.groups.GroupIdFormatException;
import org.asamk.signal.util.IOUtils; import org.asamk.signal.util.IOUtils;
import org.asamk.signal.util.Util; import org.asamk.signal.util.Util;
import org.freedesktop.dbus.errors.UnknownObject; import org.freedesktop.dbus.errors.UnknownObject;
import org.freedesktop.dbus.exceptions.DBusExecutionException; import org.freedesktop.dbus.exceptions.DBusExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
@ -20,6 +23,8 @@ import static org.asamk.signal.util.ErrorUtils.handleGroupIdFormatException;
public class SendCommand implements DbusCommand { public class SendCommand implements DbusCommand {
private final static Logger logger = LoggerFactory.getLogger(SendCommand.class);
@Override @Override
public void attachToSubparser(final Subparser subparser) { public void attachToSubparser(final Subparser subparser) {
subparser.addArgument("recipient").help("Specify the recipients' phone number.").nargs("*"); subparser.addArgument("recipient").help("Specify the recipients' phone number.").nargs("*");
@ -90,18 +95,20 @@ public class SendCommand implements DbusCommand {
attachments = List.of(); attachments = List.of();
} }
if (groupIdString != null) { final var writer = new PlainTextWriterImpl(System.out);
try {
byte[] groupId;
try {
groupId = Util.decodeGroupId(groupIdString).serialize();
} catch (GroupIdFormatException e) {
handleGroupIdFormatException(e);
return 1;
}
if (groupIdString != null) {
byte[] groupId;
try {
groupId = Util.decodeGroupId(groupIdString).serialize();
} catch (GroupIdFormatException e) {
handleGroupIdFormatException(e);
return 1;
}
try {
var timestamp = signal.sendGroupMessage(messageText, attachments, groupId); var timestamp = signal.sendGroupMessage(messageText, attachments, groupId);
System.out.println(timestamp); writer.println("{}", timestamp);
return 0; return 0;
} catch (AssertionError e) { } catch (AssertionError e) {
handleAssertionError(e); handleAssertionError(e);
@ -109,13 +116,16 @@ public class SendCommand implements DbusCommand {
} catch (DBusExecutionException e) { } catch (DBusExecutionException e) {
System.err.println("Failed to send group message: " + e.getMessage()); System.err.println("Failed to send group message: " + e.getMessage());
return 2; return 2;
} catch (IOException e) {
e.printStackTrace();
return 3;
} }
} }
if (isNoteToSelf) { if (isNoteToSelf) {
try { try {
var timestamp = signal.sendNoteToSelfMessage(messageText, attachments); var timestamp = signal.sendNoteToSelfMessage(messageText, attachments);
System.out.println(timestamp); writer.println("{}", timestamp);
return 0; return 0;
} catch (AssertionError e) { } catch (AssertionError e) {
handleAssertionError(e); handleAssertionError(e);
@ -126,12 +136,15 @@ public class SendCommand implements DbusCommand {
} catch (DBusExecutionException e) { } catch (DBusExecutionException e) {
System.err.println("Failed to send note to self message: " + e.getMessage()); System.err.println("Failed to send note to self message: " + e.getMessage());
return 2; return 2;
} catch (IOException e) {
e.printStackTrace();
return 3;
} }
} }
try { try {
var timestamp = signal.sendMessage(messageText, attachments, recipients); var timestamp = signal.sendMessage(messageText, attachments, recipients);
System.out.println(timestamp); writer.println("{}", timestamp);
return 0; return 0;
} catch (AssertionError e) { } catch (AssertionError e) {
handleAssertionError(e); handleAssertionError(e);
@ -145,6 +158,9 @@ public class SendCommand implements DbusCommand {
} catch (DBusExecutionException e) { } catch (DBusExecutionException e) {
System.err.println("Failed to send message: " + e.getMessage()); System.err.println("Failed to send message: " + e.getMessage());
return 2; return 2;
} catch (IOException e) {
e.printStackTrace();
return 3;
} }
} }
} }

View file

@ -4,6 +4,7 @@ import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser; import net.sourceforge.argparse4j.inf.Subparser;
import org.asamk.signal.PlainTextWriterImpl;
import org.asamk.signal.manager.Manager; import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.groups.GroupIdFormatException; import org.asamk.signal.manager.groups.GroupIdFormatException;
import org.asamk.signal.manager.groups.GroupNotFoundException; import org.asamk.signal.manager.groups.GroupNotFoundException;
@ -66,6 +67,8 @@ public class SendReactionCommand implements LocalCommand {
final long targetTimestamp = ns.getLong("target_timestamp"); final long targetTimestamp = ns.getLong("target_timestamp");
try { try {
final var writer = new PlainTextWriterImpl(System.out);
final Pair<Long, List<SendMessageResult>> results; final Pair<Long, List<SendMessageResult>> results;
if (groupIdString != null) { if (groupIdString != null) {
var groupId = Util.decodeGroupId(groupIdString); var groupId = Util.decodeGroupId(groupIdString);
@ -73,7 +76,7 @@ public class SendReactionCommand implements LocalCommand {
} else { } else {
results = m.sendMessageReaction(emoji, isRemove, targetAuthor, targetTimestamp, recipients); results = m.sendMessageReaction(emoji, isRemove, targetAuthor, targetTimestamp, recipients);
} }
return handleTimestampAndSendMessageResults(results.first(), results.second()); return handleTimestampAndSendMessageResults(writer, results.first(), results.second());
} catch (IOException e) { } catch (IOException e) {
handleIOException(e); handleIOException(e);
return 3; return 3;

View file

@ -4,10 +4,14 @@ import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser; import net.sourceforge.argparse4j.inf.Subparser;
import org.asamk.Signal; import org.asamk.Signal;
import org.asamk.signal.PlainTextWriterImpl;
import org.asamk.signal.manager.groups.GroupIdFormatException; import org.asamk.signal.manager.groups.GroupIdFormatException;
import org.asamk.signal.util.Util; import org.asamk.signal.util.Util;
import org.freedesktop.dbus.exceptions.DBusExecutionException; import org.freedesktop.dbus.exceptions.DBusExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Base64; import java.util.Base64;
import java.util.List; import java.util.List;
@ -17,6 +21,8 @@ import static org.asamk.signal.util.ErrorUtils.handleGroupIdFormatException;
public class UpdateGroupCommand implements DbusCommand { public class UpdateGroupCommand implements DbusCommand {
private final static Logger logger = LoggerFactory.getLogger(UpdateGroupCommand.class);
@Override @Override
public void attachToSubparser(final Subparser subparser) { public void attachToSubparser(final Subparser subparser) {
subparser.addArgument("-g", "--group").help("Specify the recipient group ID."); subparser.addArgument("-g", "--group").help("Specify the recipient group ID.");
@ -27,6 +33,7 @@ public class UpdateGroupCommand implements DbusCommand {
@Override @Override
public int handleCommand(final Namespace ns, final Signal signal) { public int handleCommand(final Namespace ns, final Signal signal) {
final var writer = new PlainTextWriterImpl(System.out);
byte[] groupId = null; byte[] groupId = null;
if (ns.getString("group") != null) { if (ns.getString("group") != null) {
try { try {
@ -58,7 +65,12 @@ public class UpdateGroupCommand implements DbusCommand {
try { try {
var newGroupId = signal.updateGroup(groupId, groupName, groupMembers, groupAvatar); var newGroupId = signal.updateGroup(groupId, groupName, groupMembers, groupAvatar);
if (groupId.length != newGroupId.length) { if (groupId.length != newGroupId.length) {
System.out.println("Creating new group \"" + Base64.getEncoder().encodeToString(newGroupId) + "\""); try {
writer.println("Creating new group \"{}\"", Base64.getEncoder().encodeToString(newGroupId));
} catch (IOException e) {
e.printStackTrace();
return 3;
}
} }
return 0; return 0;
} catch (AssertionError e) { } catch (AssertionError e) {

View file

@ -3,14 +3,19 @@ package org.asamk.signal.commands;
import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser; import net.sourceforge.argparse4j.inf.Subparser;
import org.asamk.signal.PlainTextWriterImpl;
import org.asamk.signal.manager.Manager; import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.StickerPackInvalidException; import org.asamk.signal.manager.StickerPackInvalidException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
public class UploadStickerPackCommand implements LocalCommand { public class UploadStickerPackCommand implements LocalCommand {
private final static Logger logger = LoggerFactory.getLogger(UploadStickerPackCommand.class);
@Override @Override
public void attachToSubparser(final Subparser subparser) { public void attachToSubparser(final Subparser subparser) {
subparser.addArgument("path") subparser.addArgument("path")
@ -19,10 +24,11 @@ public class UploadStickerPackCommand implements LocalCommand {
@Override @Override
public int handleCommand(final Namespace ns, final Manager m) { public int handleCommand(final Namespace ns, final Manager m) {
final var writer = new PlainTextWriterImpl(System.out);
try { try {
var path = new File(ns.getString("path")); var path = new File(ns.getString("path"));
var url = m.uploadStickerPack(path); var url = m.uploadStickerPack(path);
System.out.println(url); writer.println("{}", url);
return 0; return 0;
} catch (IOException e) { } catch (IOException e) {
System.err.println("Upload error: " + e.getMessage()); System.err.println("Upload error: " + e.getMessage());

View file

@ -1,5 +1,6 @@
package org.asamk.signal.util; package org.asamk.signal.util;
import org.asamk.signal.PlainTextWriter;
import org.asamk.signal.manager.groups.GroupIdFormatException; import org.asamk.signal.manager.groups.GroupIdFormatException;
import org.asamk.signal.manager.groups.GroupNotFoundException; import org.asamk.signal.manager.groups.GroupNotFoundException;
import org.asamk.signal.manager.groups.NotAGroupMemberException; import org.asamk.signal.manager.groups.NotAGroupMemberException;
@ -22,9 +23,13 @@ public class ErrorUtils {
"If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README"); "If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
} }
public static int handleTimestampAndSendMessageResults(long timestamp, List<SendMessageResult> results) { public static int handleTimestampAndSendMessageResults(
PlainTextWriter writer,
long timestamp,
List<SendMessageResult> results
) throws IOException {
if (timestamp != 0) { if (timestamp != 0) {
System.out.println(timestamp); writer.println("{}", timestamp);
} }
var errors = getErrorMessagesFromSendMessageResults(results); var errors = getErrorMessagesFromSendMessageResults(results);
return handleSendMessageResultErrors(errors); return handleSendMessageResultErrors(errors);