mirror of
https://github.com/AsamK/signal-cli
synced 2025-08-29 10:30:38 +00:00
Use pattern matching switch cases
This commit is contained in:
parent
80c1a6d2af
commit
8d55dfb66b
27 changed files with 395 additions and 380 deletions
|
@ -109,18 +109,13 @@ public class Main {
|
|||
}
|
||||
|
||||
private static int getStatusForError(final CommandException e) {
|
||||
if (e instanceof UserErrorException) {
|
||||
return 1;
|
||||
} else if (e instanceof UnexpectedErrorException) {
|
||||
return 2;
|
||||
} else if (e instanceof IOErrorException) {
|
||||
return 3;
|
||||
} else if (e instanceof UntrustedKeyErrorException) {
|
||||
return 4;
|
||||
} else if (e instanceof RateLimitErrorException) {
|
||||
return 5;
|
||||
} else {
|
||||
return 2;
|
||||
}
|
||||
return switch (e) {
|
||||
case UserErrorException userErrorException -> 1;
|
||||
case UnexpectedErrorException unexpectedErrorException -> 2;
|
||||
case IOErrorException ioErrorException -> 3;
|
||||
case UntrustedKeyErrorException untrustedKeyErrorException -> 4;
|
||||
case RateLimitErrorException rateLimitErrorException -> 5;
|
||||
case null, default -> 2;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
@ -72,8 +72,8 @@ public class Commands {
|
|||
|
||||
private static void addCommand(Command command) {
|
||||
commands.put(command.getName(), command);
|
||||
if (command instanceof CliCommand) {
|
||||
commandSubparserAttacher.put(command.getName(), ((CliCommand) command)::attachToSubparser);
|
||||
if (command instanceof CliCommand cliCommand) {
|
||||
commandSubparserAttacher.put(command.getName(), cliCommand::attachToSubparser);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -249,11 +249,11 @@ public class DaemonCommand implements MultiLocalCommand, LocalCommand {
|
|||
}
|
||||
|
||||
private void addDefaultReceiveHandler(Manager m, OutputWriter outputWriter, final boolean isWeakListener) {
|
||||
final var handler = outputWriter instanceof JsonWriter o
|
||||
? new JsonReceiveMessageHandler(m, o)
|
||||
: outputWriter instanceof PlainTextWriter o
|
||||
? new ReceiveMessageHandler(m, o)
|
||||
: Manager.ReceiveMessageHandler.EMPTY;
|
||||
final var handler = switch (outputWriter) {
|
||||
case PlainTextWriter writer -> new ReceiveMessageHandler(m, writer);
|
||||
case JsonWriter writer -> new JsonReceiveMessageHandler(m, writer);
|
||||
case null -> Manager.ReceiveMessageHandler.EMPTY;
|
||||
};
|
||||
m.addReceiveHandler(handler, isWeakListener);
|
||||
}
|
||||
|
||||
|
|
|
@ -42,10 +42,9 @@ public class GetAttachmentCommand implements JsonRpcLocalCommand {
|
|||
try (InputStream attachment = m.retrieveAttachment(id)) {
|
||||
final var bytes = attachment.readAllBytes();
|
||||
final var base64 = Base64.getEncoder().encodeToString(bytes);
|
||||
if (outputWriter instanceof PlainTextWriter writer) {
|
||||
writer.println(base64);
|
||||
} else if (outputWriter instanceof JsonWriter writer) {
|
||||
writer.write(new JsonAttachmentData(base64));
|
||||
switch (outputWriter) {
|
||||
case PlainTextWriter writer -> writer.println(base64);
|
||||
case JsonWriter writer -> writer.write(new JsonAttachmentData(base64));
|
||||
}
|
||||
} catch (FileNotFoundException ex) {
|
||||
throw new UserErrorException("Could not find attachment with ID: " + id, ex);
|
||||
|
|
|
@ -55,24 +55,26 @@ public class GetUserStatusCommand implements JsonRpcLocalCommand {
|
|||
}
|
||||
|
||||
// Output
|
||||
if (outputWriter instanceof JsonWriter jsonWriter) {
|
||||
|
||||
var jsonUserStatuses = registered.entrySet().stream().map(entry -> {
|
||||
final var number = entry.getValue().number();
|
||||
final var uuid = entry.getValue().uuid();
|
||||
return new JsonUserStatus(entry.getKey(), number, uuid == null ? null : uuid.toString(), uuid != null);
|
||||
}).toList();
|
||||
|
||||
jsonWriter.write(jsonUserStatuses);
|
||||
} else {
|
||||
final var writer = (PlainTextWriter) outputWriter;
|
||||
|
||||
for (var entry : registered.entrySet()) {
|
||||
final var userStatus = entry.getValue();
|
||||
writer.println("{}: {}{}",
|
||||
entry.getKey(),
|
||||
userStatus.uuid() != null,
|
||||
userStatus.unrestrictedUnidentifiedAccess() ? " (unrestricted sealed sender)" : "");
|
||||
switch (outputWriter) {
|
||||
case JsonWriter writer -> {
|
||||
var jsonUserStatuses = registered.entrySet().stream().map(entry -> {
|
||||
final var number = entry.getValue().number();
|
||||
final var uuid = entry.getValue().uuid();
|
||||
return new JsonUserStatus(entry.getKey(),
|
||||
number,
|
||||
uuid == null ? null : uuid.toString(),
|
||||
uuid != null);
|
||||
}).toList();
|
||||
writer.write(jsonUserStatuses);
|
||||
}
|
||||
case PlainTextWriter writer -> {
|
||||
for (var entry : registered.entrySet()) {
|
||||
final var userStatus = entry.getValue();
|
||||
writer.println("{}: {}{}",
|
||||
entry.getKey(),
|
||||
userStatus.uuid() != null,
|
||||
userStatus.unrestrictedUnidentifiedAccess() ? " (unrestricted sealed sender)" : "");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -54,35 +54,38 @@ public class JoinGroupCommand implements JsonRpcLocalCommand {
|
|||
try {
|
||||
final var results = m.joinGroup(linkUrl);
|
||||
var newGroupId = results.first();
|
||||
if (outputWriter instanceof JsonWriter writer) {
|
||||
var jsonResults = SendMessageResultUtils.getJsonSendMessageResults(results.second().results());
|
||||
if (!m.getGroup(newGroupId).isMember()) {
|
||||
writer.write(Map.of("timestamp",
|
||||
results.second().timestamp(),
|
||||
"results",
|
||||
jsonResults,
|
||||
"groupId",
|
||||
newGroupId.toBase64(),
|
||||
"onlyRequested",
|
||||
true));
|
||||
} else {
|
||||
writer.write(Map.of("timestamp",
|
||||
results.second().timestamp(),
|
||||
"results",
|
||||
jsonResults,
|
||||
"groupId",
|
||||
newGroupId.toBase64()));
|
||||
switch (outputWriter) {
|
||||
case JsonWriter writer -> {
|
||||
var jsonResults = SendMessageResultUtils.getJsonSendMessageResults(results.second().results());
|
||||
if (!m.getGroup(newGroupId).isMember()) {
|
||||
writer.write(Map.of("timestamp",
|
||||
results.second().timestamp(),
|
||||
"results",
|
||||
jsonResults,
|
||||
"groupId",
|
||||
newGroupId.toBase64(),
|
||||
"onlyRequested",
|
||||
true));
|
||||
} else {
|
||||
writer.write(Map.of("timestamp",
|
||||
results.second().timestamp(),
|
||||
"results",
|
||||
jsonResults,
|
||||
"groupId",
|
||||
newGroupId.toBase64()));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
final var writer = (PlainTextWriter) outputWriter;
|
||||
if (!m.getGroup(newGroupId).isMember()) {
|
||||
writer.println("Requested to join group \"{}\"", newGroupId.toBase64());
|
||||
} else {
|
||||
writer.println("Joined group \"{}\"", newGroupId.toBase64());
|
||||
case PlainTextWriter writer -> {
|
||||
if (!m.getGroup(newGroupId).isMember()) {
|
||||
writer.println("Requested to join group \"{}\"", newGroupId.toBase64());
|
||||
} else {
|
||||
writer.println("Joined group \"{}\"", newGroupId.toBase64());
|
||||
}
|
||||
var errors = SendMessageResultUtils.getErrorMessagesFromSendMessageResults(results.second()
|
||||
.results());
|
||||
SendMessageResultUtils.printSendMessageResultErrors(writer, errors);
|
||||
writer.println("{}", results.second().timestamp());
|
||||
}
|
||||
var errors = SendMessageResultUtils.getErrorMessagesFromSendMessageResults(results.second().results());
|
||||
SendMessageResultUtils.printSendMessageResultErrors(writer, errors);
|
||||
writer.println("{}", results.second().timestamp());
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new IOErrorException("Failed to send message: "
|
||||
|
|
|
@ -26,12 +26,15 @@ public class ListAccountsCommand implements JsonRpcMultiLocalCommand {
|
|||
final Namespace ns, final MultiAccountManager c, final OutputWriter outputWriter
|
||||
) throws CommandException {
|
||||
final var accountNumbers = c.getAccountNumbers();
|
||||
if (outputWriter instanceof JsonWriter jsonWriter) {
|
||||
final var jsonAccounts = accountNumbers.stream().map(JsonAccount::new).toList();
|
||||
jsonWriter.write(jsonAccounts);
|
||||
} else if (outputWriter instanceof PlainTextWriter plainTextWriter) {
|
||||
for (final var number : accountNumbers) {
|
||||
plainTextWriter.println("Number: {}", number);
|
||||
switch (outputWriter) {
|
||||
case JsonWriter jsonWriter -> {
|
||||
final var jsonAccounts = accountNumbers.stream().map(JsonAccount::new).toList();
|
||||
jsonWriter.write(jsonAccounts);
|
||||
}
|
||||
case PlainTextWriter plainTextWriter -> {
|
||||
for (final var number : accountNumbers) {
|
||||
plainTextWriter.println("Number: {}", number);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -51,48 +51,49 @@ public class ListContactsCommand implements JsonRpcLocalCommand {
|
|||
recipientIdentifiers,
|
||||
Optional.ofNullable(name));
|
||||
|
||||
if (outputWriter instanceof PlainTextWriter writer) {
|
||||
for (var r : recipients) {
|
||||
final var contact = r.getContact() == null ? Contact.newBuilder().build() : r.getContact();
|
||||
final var profile = r.getProfile() == null ? Profile.newBuilder().build() : r.getProfile();
|
||||
writer.println(
|
||||
"Number: {} Name: {} Profile name: {} Username: {} Color: {} Blocked: {} Message expiration: {}",
|
||||
r.getAddress().getLegacyIdentifier(),
|
||||
contact.getName(),
|
||||
profile.getDisplayName(),
|
||||
r.getAddress().username().orElse(""),
|
||||
contact.getColor(),
|
||||
contact.isBlocked(),
|
||||
contact.getMessageExpirationTime() == 0
|
||||
? "disabled"
|
||||
: contact.getMessageExpirationTime() + "s");
|
||||
switch (outputWriter) {
|
||||
case PlainTextWriter writer -> {
|
||||
for (var r : recipients) {
|
||||
final var contact = r.getContact() == null ? Contact.newBuilder().build() : r.getContact();
|
||||
final var profile = r.getProfile() == null ? Profile.newBuilder().build() : r.getProfile();
|
||||
writer.println(
|
||||
"Number: {} Name: {} Profile name: {} Username: {} Color: {} Blocked: {} Message expiration: {}",
|
||||
r.getAddress().getLegacyIdentifier(),
|
||||
contact.getName(),
|
||||
profile.getDisplayName(),
|
||||
r.getAddress().username().orElse(""),
|
||||
contact.getColor(),
|
||||
contact.isBlocked(),
|
||||
contact.getMessageExpirationTime() == 0
|
||||
? "disabled"
|
||||
: contact.getMessageExpirationTime() + "s");
|
||||
}
|
||||
}
|
||||
case JsonWriter writer -> {
|
||||
final var jsonContacts = recipients.stream().map(r -> {
|
||||
final var address = r.getAddress();
|
||||
final var contact = r.getContact() == null ? Contact.newBuilder().build() : r.getContact();
|
||||
return new JsonContact(address.number().orElse(null),
|
||||
address.uuid().map(UUID::toString).orElse(null),
|
||||
address.username().orElse(null),
|
||||
contact.getName(),
|
||||
contact.getColor(),
|
||||
contact.isBlocked(),
|
||||
contact.getMessageExpirationTime(),
|
||||
r.getProfile() == null
|
||||
? null
|
||||
: new JsonContact.JsonProfile(r.getProfile().getLastUpdateTimestamp(),
|
||||
r.getProfile().getGivenName(),
|
||||
r.getProfile().getFamilyName(),
|
||||
r.getProfile().getAbout(),
|
||||
r.getProfile().getAboutEmoji(),
|
||||
r.getProfile().getMobileCoinAddress() == null
|
||||
? null
|
||||
: Base64.getEncoder()
|
||||
.encodeToString(r.getProfile().getMobileCoinAddress())));
|
||||
}).toList();
|
||||
writer.write(jsonContacts);
|
||||
}
|
||||
} else {
|
||||
final var writer = (JsonWriter) outputWriter;
|
||||
final var jsonContacts = recipients.stream().map(r -> {
|
||||
final var address = r.getAddress();
|
||||
final var contact = r.getContact() == null ? Contact.newBuilder().build() : r.getContact();
|
||||
return new JsonContact(address.number().orElse(null),
|
||||
address.uuid().map(UUID::toString).orElse(null),
|
||||
address.username().orElse(null),
|
||||
contact.getName(),
|
||||
contact.getColor(),
|
||||
contact.isBlocked(),
|
||||
contact.getMessageExpirationTime(),
|
||||
r.getProfile() == null
|
||||
? null
|
||||
: new JsonContact.JsonProfile(r.getProfile().getLastUpdateTimestamp(),
|
||||
r.getProfile().getGivenName(),
|
||||
r.getProfile().getFamilyName(),
|
||||
r.getProfile().getAbout(),
|
||||
r.getProfile().getAboutEmoji(),
|
||||
r.getProfile().getMobileCoinAddress() == null
|
||||
? null
|
||||
: Base64.getEncoder()
|
||||
.encodeToString(r.getProfile().getMobileCoinAddress())));
|
||||
}).toList();
|
||||
|
||||
writer.write(jsonContacts);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -42,21 +42,23 @@ public class ListDevicesCommand implements JsonRpcLocalCommand {
|
|||
throw new IOErrorException("Failed to get linked devices: " + e.getMessage(), e);
|
||||
}
|
||||
|
||||
if (outputWriter instanceof PlainTextWriter writer) {
|
||||
for (var d : devices) {
|
||||
writer.println("- Device {}{}:", d.id(), (d.isThisDevice() ? " (this device)" : ""));
|
||||
writer.indent(w -> {
|
||||
w.println("Name: {}", d.name());
|
||||
w.println("Created: {}", DateUtils.formatTimestamp(d.created()));
|
||||
w.println("Last seen: {}", DateUtils.formatTimestamp(d.lastSeen()));
|
||||
});
|
||||
switch (outputWriter) {
|
||||
case PlainTextWriter writer -> {
|
||||
for (var d : devices) {
|
||||
writer.println("- Device {}{}:", d.id(), (d.isThisDevice() ? " (this device)" : ""));
|
||||
writer.indent(w -> {
|
||||
w.println("Name: {}", d.name());
|
||||
w.println("Created: {}", DateUtils.formatTimestamp(d.created()));
|
||||
w.println("Last seen: {}", DateUtils.formatTimestamp(d.lastSeen()));
|
||||
});
|
||||
}
|
||||
}
|
||||
case JsonWriter writer -> {
|
||||
final var jsonDevices = devices.stream()
|
||||
.map(d -> new JsonDevice(d.id(), d.name(), d.created(), d.lastSeen()))
|
||||
.toList();
|
||||
writer.write(jsonDevices);
|
||||
}
|
||||
} else {
|
||||
final var writer = (JsonWriter) outputWriter;
|
||||
final var jsonDevices = devices.stream()
|
||||
.map(d -> new JsonDevice(d.id(), d.name(), d.created(), d.lastSeen()))
|
||||
.toList();
|
||||
writer.write(jsonDevices);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -89,34 +89,34 @@ public class ListGroupsCommand implements JsonRpcLocalCommand {
|
|||
groups = groups.stream().filter(g -> groupIds.contains(g.groupId())).toList();
|
||||
}
|
||||
|
||||
if (outputWriter instanceof JsonWriter jsonWriter) {
|
||||
switch (outputWriter) {
|
||||
case JsonWriter jsonWriter -> {
|
||||
var jsonGroups = groups.stream().map(group -> {
|
||||
final var groupInviteLink = group.groupInviteLinkUrl();
|
||||
|
||||
var jsonGroups = groups.stream().map(group -> {
|
||||
final var groupInviteLink = group.groupInviteLinkUrl();
|
||||
|
||||
return new JsonGroup(group.groupId().toBase64(),
|
||||
group.title(),
|
||||
group.description(),
|
||||
group.isMember(),
|
||||
group.isBlocked(),
|
||||
group.messageExpirationTimer(),
|
||||
resolveJsonMembers(group.members()),
|
||||
resolveJsonMembers(group.pendingMembers()),
|
||||
resolveJsonMembers(group.requestingMembers()),
|
||||
resolveJsonMembers(group.adminMembers()),
|
||||
resolveJsonMembers(group.bannedMembers()),
|
||||
group.permissionAddMember().name(),
|
||||
group.permissionEditDetails().name(),
|
||||
group.permissionSendMessage().name(),
|
||||
groupInviteLink == null ? null : groupInviteLink.getUrl());
|
||||
}).toList();
|
||||
|
||||
jsonWriter.write(jsonGroups);
|
||||
} else {
|
||||
final var writer = (PlainTextWriter) outputWriter;
|
||||
boolean detailed = Boolean.TRUE.equals(ns.getBoolean("detailed"));
|
||||
for (var group : groups) {
|
||||
printGroupPlainText(writer, group, detailed);
|
||||
return new JsonGroup(group.groupId().toBase64(),
|
||||
group.title(),
|
||||
group.description(),
|
||||
group.isMember(),
|
||||
group.isBlocked(),
|
||||
group.messageExpirationTimer(),
|
||||
resolveJsonMembers(group.members()),
|
||||
resolveJsonMembers(group.pendingMembers()),
|
||||
resolveJsonMembers(group.requestingMembers()),
|
||||
resolveJsonMembers(group.adminMembers()),
|
||||
resolveJsonMembers(group.bannedMembers()),
|
||||
group.permissionAddMember().name(),
|
||||
group.permissionEditDetails().name(),
|
||||
group.permissionSendMessage().name(),
|
||||
groupInviteLink == null ? null : groupInviteLink.getUrl());
|
||||
}).toList();
|
||||
jsonWriter.write(jsonGroups);
|
||||
}
|
||||
case PlainTextWriter writer -> {
|
||||
boolean detailed = Boolean.TRUE.equals(ns.getBoolean("detailed"));
|
||||
for (var group : groups) {
|
||||
printGroupPlainText(writer, group, detailed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -57,28 +57,29 @@ public class ListIdentitiesCommand implements JsonRpcLocalCommand {
|
|||
identities = m.getIdentities(CommandUtil.getSingleRecipientIdentifier(number, m.getSelfNumber()));
|
||||
}
|
||||
|
||||
if (outputWriter instanceof PlainTextWriter writer) {
|
||||
for (var id : identities) {
|
||||
printIdentityFingerprint(writer, id);
|
||||
switch (outputWriter) {
|
||||
case PlainTextWriter writer -> {
|
||||
for (var id : identities) {
|
||||
printIdentityFingerprint(writer, id);
|
||||
}
|
||||
}
|
||||
case JsonWriter writer -> {
|
||||
final var jsonIdentities = identities.stream().map(id -> {
|
||||
final var address = id.recipient();
|
||||
var safetyNumber = Util.formatSafetyNumber(id.safetyNumber());
|
||||
var scannableSafetyNumber = id.scannableSafetyNumber();
|
||||
return new JsonIdentity(address.number().orElse(null),
|
||||
address.uuid().map(UUID::toString).orElse(null),
|
||||
Hex.toString(id.getFingerprint()),
|
||||
safetyNumber,
|
||||
scannableSafetyNumber == null
|
||||
? null
|
||||
: Base64.getEncoder().encodeToString(scannableSafetyNumber),
|
||||
id.trustLevel().name(),
|
||||
id.dateAddedTimestamp());
|
||||
}).toList();
|
||||
writer.write(jsonIdentities);
|
||||
}
|
||||
} else {
|
||||
final var writer = (JsonWriter) outputWriter;
|
||||
final var jsonIdentities = identities.stream().map(id -> {
|
||||
final var address = id.recipient();
|
||||
var safetyNumber = Util.formatSafetyNumber(id.safetyNumber());
|
||||
var scannableSafetyNumber = id.scannableSafetyNumber();
|
||||
return new JsonIdentity(address.number().orElse(null),
|
||||
address.uuid().map(UUID::toString).orElse(null),
|
||||
Hex.toString(id.getFingerprint()),
|
||||
safetyNumber,
|
||||
scannableSafetyNumber == null
|
||||
? null
|
||||
: Base64.getEncoder().encodeToString(scannableSafetyNumber),
|
||||
id.trustLevel().name(),
|
||||
id.dateAddedTimestamp());
|
||||
}).toList();
|
||||
|
||||
writer.write(jsonIdentities);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -30,17 +30,20 @@ public class ListStickerPacksCommand implements JsonRpcLocalCommand {
|
|||
final Namespace ns, final Manager c, final OutputWriter outputWriter
|
||||
) throws CommandException {
|
||||
final var stickerPacks = c.getStickerPacks();
|
||||
if (outputWriter instanceof JsonWriter jsonWriter) {
|
||||
final var jsonStickerPacks = stickerPacks.stream().map(JsonStickerPack::new).toList();
|
||||
jsonWriter.write(jsonStickerPacks);
|
||||
} else if (outputWriter instanceof PlainTextWriter plainTextWriter) {
|
||||
for (final var sticker : stickerPacks) {
|
||||
plainTextWriter.println("Pack {}: “{}” by “{}” has {} stickers. {}",
|
||||
Hex.toStringCondensed(sticker.packId().serialize()),
|
||||
sticker.title(),
|
||||
sticker.author(),
|
||||
sticker.stickers().size(),
|
||||
sticker.url().getUrl());
|
||||
switch (outputWriter) {
|
||||
case JsonWriter jsonWriter -> {
|
||||
final var jsonStickerPacks = stickerPacks.stream().map(JsonStickerPack::new).toList();
|
||||
jsonWriter.write(jsonStickerPacks);
|
||||
}
|
||||
case PlainTextWriter plainTextWriter -> {
|
||||
for (final var sticker : stickerPacks) {
|
||||
plainTextWriter.println("Pack {}: “{}” by “{}” has {} stickers. {}",
|
||||
Hex.toStringCondensed(sticker.packId().serialize()),
|
||||
sticker.title(),
|
||||
sticker.author(),
|
||||
sticker.stickers().size(),
|
||||
sticker.url().getUrl());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -74,8 +74,10 @@ public class ReceiveCommand implements LocalCommand, JsonRpcSingleCommand<Receiv
|
|||
final var sendReadReceipts = Boolean.TRUE.equals(ns.getBoolean("send-read-receipts"));
|
||||
m.setReceiveConfig(new ReceiveConfig(ignoreAttachments, ignoreStories, sendReadReceipts));
|
||||
try {
|
||||
final var handler = outputWriter instanceof JsonWriter ? new JsonReceiveMessageHandler(m,
|
||||
(JsonWriter) outputWriter) : new ReceiveMessageHandler(m, (PlainTextWriter) outputWriter);
|
||||
final var handler = switch (outputWriter) {
|
||||
case JsonWriter writer -> new JsonReceiveMessageHandler(m, writer);
|
||||
case PlainTextWriter writer -> new ReceiveMessageHandler(m, writer);
|
||||
};
|
||||
final var duration = timeout < 0 ? null : Duration.ofMillis((long) (timeout * 1000));
|
||||
final var maxMessages = maxMessagesRaw < 0 ? null : maxMessagesRaw;
|
||||
m.receiveMessages(Optional.ofNullable(duration), Optional.ofNullable(maxMessages), handler);
|
||||
|
|
|
@ -50,10 +50,9 @@ public class UpdateAccountCommand implements JsonRpcLocalCommand {
|
|||
if (username != null) {
|
||||
try {
|
||||
final var newUsername = m.setUsername(username);
|
||||
if (outputWriter instanceof PlainTextWriter w) {
|
||||
w.println("Your new username: {}", newUsername);
|
||||
} else if (outputWriter instanceof JsonWriter w) {
|
||||
w.write(new JsonAccountResponse(newUsername));
|
||||
switch (outputWriter) {
|
||||
case PlainTextWriter w -> w.println("Your new username: {}", newUsername);
|
||||
case JsonWriter w -> w.write(new JsonAccountResponse(newUsername));
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new IOErrorException("Failed to set username: " + e.getMessage(), e);
|
||||
|
|
|
@ -182,27 +182,29 @@ public class UpdateGroupCommand implements JsonRpcLocalCommand {
|
|||
private void outputResult(
|
||||
final OutputWriter outputWriter, final SendGroupMessageResults results, final GroupId groupId
|
||||
) {
|
||||
if (outputWriter instanceof PlainTextWriter writer) {
|
||||
if (groupId != null) {
|
||||
writer.println("Created new group: \"{}\"", groupId.toBase64());
|
||||
switch (outputWriter) {
|
||||
case PlainTextWriter writer -> {
|
||||
if (groupId != null) {
|
||||
writer.println("Created new group: \"{}\"", groupId.toBase64());
|
||||
}
|
||||
if (results != null) {
|
||||
var errors = SendMessageResultUtils.getErrorMessagesFromSendMessageResults(results.results());
|
||||
SendMessageResultUtils.printSendMessageResultErrors(writer, errors);
|
||||
writer.println("{}", results.timestamp());
|
||||
}
|
||||
}
|
||||
if (results != null) {
|
||||
var errors = SendMessageResultUtils.getErrorMessagesFromSendMessageResults(results.results());
|
||||
SendMessageResultUtils.printSendMessageResultErrors(writer, errors);
|
||||
writer.println("{}", results.timestamp());
|
||||
case JsonWriter writer -> {
|
||||
final var response = new HashMap<>();
|
||||
if (results != null) {
|
||||
response.put("timestamp", results.timestamp());
|
||||
var jsonResults = SendMessageResultUtils.getJsonSendMessageResults(results.results());
|
||||
response.put("results", jsonResults);
|
||||
}
|
||||
if (groupId != null) {
|
||||
response.put("groupId", groupId.toBase64());
|
||||
}
|
||||
writer.write(response);
|
||||
}
|
||||
} else {
|
||||
final var writer = (JsonWriter) outputWriter;
|
||||
final var response = new HashMap<>();
|
||||
if (results != null) {
|
||||
response.put("timestamp", results.timestamp());
|
||||
var jsonResults = SendMessageResultUtils.getJsonSendMessageResults(results.results());
|
||||
response.put("results", jsonResults);
|
||||
}
|
||||
if (groupId != null) {
|
||||
response.put("groupId", groupId.toBase64());
|
||||
}
|
||||
writer.write(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -42,11 +42,11 @@ public class UploadStickerPackCommand implements JsonRpcLocalCommand {
|
|||
|
||||
try {
|
||||
var url = m.uploadStickerPack(path);
|
||||
if (outputWriter instanceof PlainTextWriter writer) {
|
||||
writer.println("{}", url.getUrl());
|
||||
} else {
|
||||
final var writer = (JsonWriter) outputWriter;
|
||||
writer.write(Map.of("url", url.getUrl()));
|
||||
switch (outputWriter) {
|
||||
case PlainTextWriter writer -> writer.println("{}", url.getUrl());
|
||||
case JsonWriter writer -> {
|
||||
writer.write(Map.of("url", url.getUrl()));
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new IOErrorException("Upload error (maybe image size too large):" + e.getMessage(), e);
|
||||
|
|
|
@ -56,10 +56,9 @@ public class VersionCommand implements JsonRpcLocalCommand, JsonRpcMultiLocalCom
|
|||
final var projectName = BaseConfig.PROJECT_NAME == null ? "signal-cli" : BaseConfig.PROJECT_NAME;
|
||||
final var version = BaseConfig.PROJECT_VERSION == null ? "unknown" : BaseConfig.PROJECT_VERSION;
|
||||
|
||||
if (outputWriter instanceof JsonWriter jsonWriter) {
|
||||
jsonWriter.write(Map.of("version", version));
|
||||
} else if (outputWriter instanceof PlainTextWriter plainTextWriter) {
|
||||
plainTextWriter.println("{} {}", projectName, version);
|
||||
switch (outputWriter) {
|
||||
case JsonWriter jsonWriter -> jsonWriter.write(Map.of("version", version));
|
||||
case PlainTextWriter plainTextWriter -> plainTextWriter.println("{} {}", projectName, version);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -65,7 +65,7 @@ public abstract class DbusProperties implements Properties {
|
|||
.filter(p -> p.getGetter() != null)
|
||||
.collect(Collectors.toMap(DbusProperty::getName, p -> {
|
||||
final Object o = p.getGetter().get();
|
||||
return o instanceof Variant ? (Variant<Object>) o : new Variant<>(o);
|
||||
return o instanceof Variant<?> variant ? variant : new Variant<>(o);
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -82,53 +82,55 @@ public class JsonRpcReader {
|
|||
final RequestHandler requestHandler,
|
||||
final Consumer<JsonRpcResponse> responseHandler
|
||||
) {
|
||||
if (message instanceof final JsonRpcRequest jsonRpcRequest) {
|
||||
logger.debug("Received json rpc request, method: " + jsonRpcRequest.getMethod());
|
||||
final var response = handleRequest(requestHandler, jsonRpcRequest);
|
||||
if (response != null) {
|
||||
jsonRpcSender.sendResponse(response);
|
||||
switch (message) {
|
||||
case JsonRpcRequest jsonRpcRequest -> {
|
||||
logger.debug("Received json rpc request, method: " + jsonRpcRequest.getMethod());
|
||||
final var response = handleRequest(requestHandler, jsonRpcRequest);
|
||||
if (response != null) {
|
||||
jsonRpcSender.sendResponse(response);
|
||||
}
|
||||
}
|
||||
} else if (message instanceof JsonRpcResponse jsonRpcResponse) {
|
||||
responseHandler.accept(jsonRpcResponse);
|
||||
} else {
|
||||
final var messages = ((JsonRpcBatchMessage) message).getMessages();
|
||||
final var responseList = new ArrayList<JsonRpcResponse>(messages.size());
|
||||
final var executor = Executors.newFixedThreadPool(10);
|
||||
try {
|
||||
final var lock = new ReentrantLock();
|
||||
messages.forEach(jsonNode -> {
|
||||
final JsonRpcRequest request;
|
||||
try {
|
||||
request = parseJsonRpcRequest(jsonNode);
|
||||
} catch (JsonRpcException e) {
|
||||
final var response = JsonRpcResponse.forError(e.getError(), getId(jsonNode));
|
||||
lock.lock();
|
||||
case JsonRpcResponse jsonRpcResponse -> responseHandler.accept(jsonRpcResponse);
|
||||
case JsonRpcBatchMessage jsonRpcBatchMessage -> {
|
||||
final var messages = jsonRpcBatchMessage.getMessages();
|
||||
final var responseList = new ArrayList<JsonRpcResponse>(messages.size());
|
||||
final var executor = Executors.newFixedThreadPool(10);
|
||||
try {
|
||||
final var lock = new ReentrantLock();
|
||||
messages.forEach(jsonNode -> {
|
||||
final JsonRpcRequest request;
|
||||
try {
|
||||
responseList.add(response);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
executor.submit(() -> {
|
||||
final var response = handleRequest(requestHandler, request);
|
||||
if (response != null) {
|
||||
request = parseJsonRpcRequest(jsonNode);
|
||||
} catch (JsonRpcException e) {
|
||||
final var response = JsonRpcResponse.forError(e.getError(), getId(jsonNode));
|
||||
lock.lock();
|
||||
try {
|
||||
responseList.add(response);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
return;
|
||||
}
|
||||
});
|
||||
});
|
||||
} finally {
|
||||
Util.closeExecutorService(executor);
|
||||
}
|
||||
|
||||
if (!responseList.isEmpty()) {
|
||||
jsonRpcSender.sendBatchResponses(responseList);
|
||||
executor.submit(() -> {
|
||||
final var response = handleRequest(requestHandler, request);
|
||||
if (response != null) {
|
||||
lock.lock();
|
||||
try {
|
||||
responseList.add(response);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
} finally {
|
||||
Util.closeExecutorService(executor);
|
||||
}
|
||||
|
||||
if (!responseList.isEmpty()) {
|
||||
jsonRpcSender.sendBatchResponses(responseList);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -221,7 +223,7 @@ public class JsonRpcReader {
|
|||
|
||||
private ValueNode getId(JsonNode jsonNode) {
|
||||
final var id = jsonNode.get("id");
|
||||
return id instanceof ValueNode ? (ValueNode) id : null;
|
||||
return id instanceof ValueNode value ? value : null;
|
||||
}
|
||||
|
||||
private JsonRpcRequest parseJsonRpcRequest(final JsonNode input) throws JsonRpcException {
|
||||
|
|
|
@ -223,13 +223,11 @@ public class SignalJsonRpcDispatcherHandler {
|
|||
}
|
||||
|
||||
private Integer getSubscriptionId(final JsonNode request) {
|
||||
if (request instanceof ArrayNode req) {
|
||||
return req.get(0).asInt();
|
||||
} else if (request instanceof ObjectNode req) {
|
||||
return req.get("subscription").asInt();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
return switch (request) {
|
||||
case ArrayNode req -> req.get(0).asInt();
|
||||
case ObjectNode req -> req.get("subscription").asInt();
|
||||
case null, default -> null;
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
package org.asamk.signal.output;
|
||||
|
||||
public interface JsonWriter extends OutputWriter {
|
||||
public non-sealed interface JsonWriter extends OutputWriter {
|
||||
|
||||
void write(final Object object);
|
||||
}
|
||||
|
|
|
@ -1,5 +1,3 @@
|
|||
package org.asamk.signal.output;
|
||||
|
||||
public interface OutputWriter {
|
||||
|
||||
}
|
||||
public sealed interface OutputWriter permits JsonWriter, PlainTextWriter {}
|
||||
|
|
|
@ -2,7 +2,7 @@ package org.asamk.signal.output;
|
|||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public interface PlainTextWriter extends OutputWriter {
|
||||
public non-sealed interface PlainTextWriter extends OutputWriter {
|
||||
|
||||
void println(String format, Object... args);
|
||||
|
||||
|
|
|
@ -27,28 +27,32 @@ public class SendMessageResultUtils {
|
|||
}
|
||||
|
||||
public static void outputResult(final OutputWriter outputWriter, final SendGroupMessageResults sendMessageResults) {
|
||||
if (outputWriter instanceof PlainTextWriter writer) {
|
||||
var errors = getErrorMessagesFromSendMessageResults(sendMessageResults.results());
|
||||
printSendMessageResultErrors(writer, errors);
|
||||
writer.println("{}", sendMessageResults.timestamp());
|
||||
} else {
|
||||
final var writer = (JsonWriter) outputWriter;
|
||||
var results = getJsonSendMessageResults(sendMessageResults.results());
|
||||
writer.write(Map.of("timestamp", sendMessageResults.timestamp(), "results", results));
|
||||
switch (outputWriter) {
|
||||
case PlainTextWriter writer -> {
|
||||
var errors = getErrorMessagesFromSendMessageResults(sendMessageResults.results());
|
||||
printSendMessageResultErrors(writer, errors);
|
||||
writer.println("{}", sendMessageResults.timestamp());
|
||||
}
|
||||
case JsonWriter writer -> {
|
||||
var results = getJsonSendMessageResults(sendMessageResults.results());
|
||||
writer.write(Map.of("timestamp", sendMessageResults.timestamp(), "results", results));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void outputResult(
|
||||
final OutputWriter outputWriter, final SendMessageResults sendMessageResults
|
||||
) throws CommandException {
|
||||
if (outputWriter instanceof PlainTextWriter writer) {
|
||||
var errors = getErrorMessagesFromSendMessageResults(sendMessageResults.results());
|
||||
printSendMessageResultErrors(writer, errors);
|
||||
writer.println("{}", sendMessageResults.timestamp());
|
||||
} else {
|
||||
final var writer = (JsonWriter) outputWriter;
|
||||
var results = getJsonSendMessageResults(sendMessageResults.results());
|
||||
writer.write(Map.of("timestamp", sendMessageResults.timestamp(), "results", results));
|
||||
switch (outputWriter) {
|
||||
case PlainTextWriter writer -> {
|
||||
var errors = getErrorMessagesFromSendMessageResults(sendMessageResults.results());
|
||||
printSendMessageResultErrors(writer, errors);
|
||||
writer.println("{}", sendMessageResults.timestamp());
|
||||
}
|
||||
case JsonWriter writer -> {
|
||||
var results = getJsonSendMessageResults(sendMessageResults.results());
|
||||
writer.write(Map.of("timestamp", sendMessageResults.timestamp(), "results", results));
|
||||
}
|
||||
}
|
||||
if (!sendMessageResults.hasSuccess()) {
|
||||
if (sendMessageResults.hasOnlyUntrustedIdentity()) {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue