<option name="BINARY_OPERATION_SIGN_ON_NEXT_LINE" value="true" />
<option name="TERNARY_OPERATION_WRAP" value="5" />
<option name="TERNARY_OPERATION_SIGNS_ON_NEXT_LINE" value="true" />
+ <option name="ENUM_CONSTANTS_WRAP" value="2" />
</codeStyleSettings>
<codeStyleSettings language="XML">
<arrangement>
*/
public interface Signal extends DBusInterface {
- long sendMessage(String message, List<String> attachments, String recipient) throws Error.AttachmentInvalid, Error.Failure, Error.InvalidNumber;
+ long sendMessage(
+ String message, List<String> attachments, String recipient
+ ) throws Error.AttachmentInvalid, Error.Failure, Error.InvalidNumber;
- long sendMessage(String message, List<String> attachments, List<String> recipients) throws Error.AttachmentInvalid, Error.Failure, Error.InvalidNumber, Error.UnregisteredUser, Error.UntrustedIdentity;
+ long sendMessage(
+ String message, List<String> attachments, List<String> recipients
+ ) throws Error.AttachmentInvalid, Error.Failure, Error.InvalidNumber, Error.UnregisteredUser, Error.UntrustedIdentity;
void sendEndSessionMessage(List<String> recipients) throws Error.Failure, Error.InvalidNumber, Error.UnregisteredUser, Error.UntrustedIdentity;
- long sendGroupMessage(String message, List<String> attachments, byte[] groupId) throws Error.GroupNotFound, Error.Failure, Error.AttachmentInvalid, Error.UnregisteredUser, Error.UntrustedIdentity;
+ long sendGroupMessage(
+ String message, List<String> attachments, byte[] groupId
+ ) throws Error.GroupNotFound, Error.Failure, Error.AttachmentInvalid, Error.UnregisteredUser, Error.UntrustedIdentity;
String getContactName(String number) throws Error.InvalidNumber;
List<String> getGroupMembers(byte[] groupId);
- byte[] updateGroup(byte[] groupId, String name, List<String> members, String avatar) throws Error.AttachmentInvalid, Error.Failure, Error.InvalidNumber, Error.GroupNotFound, Error.UnregisteredUser, Error.UntrustedIdentity;
+ byte[] updateGroup(
+ byte[] groupId, String name, List<String> members, String avatar
+ ) throws Error.AttachmentInvalid, Error.Failure, Error.InvalidNumber, Error.GroupNotFound, Error.UnregisteredUser, Error.UntrustedIdentity;
boolean isRegistered();
private final String message;
private final List<String> attachments;
- public MessageReceived(String objectpath, long timestamp, String sender, byte[] groupId, String message, List<String> attachments) throws DBusException {
+ public MessageReceived(
+ String objectpath,
+ long timestamp,
+ String sender,
+ byte[] groupId,
+ String message,
+ List<String> attachments
+ ) throws DBusException {
super(objectpath, timestamp, sender, groupId, message, attachments);
this.timestamp = timestamp;
this.sender = sender;
private final String message;
private final List<String> attachments;
- public SyncMessageReceived(String objectpath, long timestamp, String source, String destination, byte[] groupId, String message, List<String> attachments) throws DBusException {
+ public SyncMessageReceived(
+ String objectpath,
+ long timestamp,
+ String source,
+ String destination,
+ byte[] groupId,
+ String message,
+ List<String> attachments
+ ) throws DBusException {
super(objectpath, timestamp, source, destination, groupId, message, attachments);
this.timestamp = timestamp;
this.source = source;
this.objectPath = objectPath;
}
- static void sendReceivedMessageToDbus(SignalServiceEnvelope envelope, SignalServiceContent content, DBusConnection conn, final String objectPath, Manager m) {
+ static void sendReceivedMessageToDbus(
+ SignalServiceEnvelope envelope,
+ SignalServiceContent content,
+ DBusConnection conn,
+ final String objectPath,
+ Manager m
+ ) {
if (envelope.isReceipt()) {
try {
- conn.sendMessage(new Signal.ReceiptReceived(
- objectPath,
- envelope.getTimestamp(),
+ conn.sendMessage(new Signal.ReceiptReceived(objectPath, envelope.getTimestamp(),
// A receipt envelope always has a source address
- envelope.getSourceAddress().getLegacyIdentifier()
- ));
+ envelope.getSourceAddress().getLegacyIdentifier()));
} catch (DBusException e) {
e.printStackTrace();
}
} else if (content != null) {
- final SignalServiceAddress sender = !envelope.isUnidentifiedSender() && envelope.hasSource() ? envelope.getSourceAddress() : content.getSender();
+ final SignalServiceAddress sender = !envelope.isUnidentifiedSender() && envelope.hasSource()
+ ? envelope.getSourceAddress()
+ : content.getSender();
if (content.getReceiptMessage().isPresent()) {
final SignalServiceReceiptMessage receiptMessage = content.getReceiptMessage().get();
if (receiptMessage.isDeliveryReceipt()) {
for (long timestamp : receiptMessage.getTimestamps()) {
try {
- conn.sendMessage(new Signal.ReceiptReceived(
- objectPath,
+ conn.sendMessage(new Signal.ReceiptReceived(objectPath,
timestamp,
- sender.getLegacyIdentifier()
- ));
+ sender.getLegacyIdentifier()));
} catch (DBusException e) {
e.printStackTrace();
}
SignalServiceDataMessage message = content.getDataMessage().get();
byte[] groupId = getGroupId(m, message);
- if (!message.isEndSession() &&
- (groupId == null
+ if (!message.isEndSession() && (
+ groupId == null
|| message.getGroupContext().get().getGroupV1Type() == null
- || message.getGroupContext().get().getGroupV1Type() == SignalServiceGroup.Type.DELIVER)) {
+ || message.getGroupContext().get().getGroupV1Type() == SignalServiceGroup.Type.DELIVER
+ )) {
try {
- conn.sendMessage(new Signal.MessageReceived(
- objectPath,
+ conn.sendMessage(new Signal.MessageReceived(objectPath,
message.getTimestamp(),
sender.getLegacyIdentifier(),
groupId != null ? groupId : new byte[0],
if (sync_message.getSent().isPresent()) {
SentTranscriptMessage transcript = sync_message.getSent().get();
- if (transcript.getDestination().isPresent() || transcript.getMessage().getGroupContext().isPresent()) {
+ if (transcript.getDestination().isPresent() || transcript.getMessage()
+ .getGroupContext()
+ .isPresent()) {
SignalServiceDataMessage message = transcript.getMessage();
byte[] groupId = getGroupId(m, message);
try {
- conn.sendMessage(new Signal.SyncMessageReceived(
- objectPath,
+ conn.sendMessage(new Signal.SyncMessageReceived(objectPath,
transcript.getTimestamp(),
sender.getLegacyIdentifier(),
- transcript.getDestination().isPresent() ? transcript.getDestination().get().getLegacyIdentifier() : "",
+ transcript.getDestination().isPresent() ? transcript.getDestination()
+ .get()
+ .getLegacyIdentifier() : "",
groupId != null ? groupId : new byte[0],
message.getBody().isPresent() ? message.getBody().get() : "",
JsonDbusReceiveMessageHandler.getAttachments(message, m)));
busType = DBusConnection.DBusBusType.SESSION;
}
try (DBusConnection dBusConn = DBusConnection.getConnection(busType)) {
- Signal ts = dBusConn.getRemoteObject(
- DbusConfig.SIGNAL_BUSNAME, DbusConfig.SIGNAL_OBJECTPATH,
+ Signal ts = dBusConn.getRemoteObject(DbusConfig.SIGNAL_BUSNAME,
+ DbusConfig.SIGNAL_OBJECTPATH,
Signal.class);
return handleCommands(ns, ts, dBusConn);
dataPath = getDefaultDataPath();
}
- final SignalServiceConfiguration serviceConfiguration = ServiceConfig.createDefaultServiceConfiguration(BaseConfig.USER_AGENT);
+ final SignalServiceConfiguration serviceConfiguration = ServiceConfig.createDefaultServiceConfiguration(
+ BaseConfig.USER_AGENT);
if (username == null) {
ProvisioningManager pm = new ProvisioningManager(dataPath, serviceConfiguration, BaseConfig.USER_AGENT);
.description("Commandline interface for Signal.")
.version(BaseConfig.PROJECT_NAME + " " + BaseConfig.PROJECT_VERSION);
- parser.addArgument("-v", "--version")
- .help("Show package version.")
- .action(Arguments.version());
+ parser.addArgument("-v", "--version").help("Show package version.").action(Arguments.version());
parser.addArgument("--config")
.help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");
MutuallyExclusiveGroup mut = parser.addMutuallyExclusiveGroup();
- mut.addArgument("-u", "--username")
- .help("Specify your phone number, that will be used for verification.");
- mut.addArgument("--dbus")
- .help("Make request via user dbus.")
- .action(Arguments.storeTrue());
- mut.addArgument("--dbus-system")
- .help("Make request via system dbus.")
- .action(Arguments.storeTrue());
+ mut.addArgument("-u", "--username").help("Specify your phone number, that will be used for verification.");
+ mut.addArgument("--dbus").help("Make request via user dbus.").action(Arguments.storeTrue());
+ mut.addArgument("--dbus-system").help("Make request via system dbus.").action(Arguments.storeTrue());
Subparsers subparsers = parser.addSubparsers()
.title("subcommands")
if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
SignalServiceAddress source = envelope.getSourceAddress();
ContactInfo sourceContact = m.getContact(source.getLegacyIdentifier());
- System.out.println(String.format("Envelope from: %s (device: %d)", (sourceContact == null ? "" : "“" + sourceContact.name + "” ") + source.getLegacyIdentifier(), envelope.getSourceDevice()));
+ System.out.println(String.format("Envelope from: %s (device: %d)",
+ (sourceContact == null ? "" : "“" + sourceContact.name + "” ") + source.getLegacyIdentifier(),
+ envelope.getSourceDevice()));
if (source.getRelay().isPresent()) {
System.out.println("Relayed by: " + source.getRelay().get());
}
if (exception != null) {
if (exception instanceof org.whispersystems.libsignal.UntrustedIdentityException) {
org.whispersystems.libsignal.UntrustedIdentityException e = (org.whispersystems.libsignal.UntrustedIdentityException) exception;
- System.out.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
- System.out.println("Use 'signal-cli -u " + m.getUsername() + " listIdentities -n " + e.getName() + "', verify the key and run 'signal-cli -u " + m.getUsername() + " trust -v \"FINGER_PRINT\" " + e.getName() + "' to mark it as trusted");
- System.out.println("If you don't care about security, use 'signal-cli -u " + m.getUsername() + " trust -a " + e.getName() + "' to trust it without verification");
+ System.out.println(
+ "The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
+ System.out.println("Use 'signal-cli -u "
+ + m.getUsername()
+ + " listIdentities -n "
+ + e.getName()
+ + "', verify the key and run 'signal-cli -u "
+ + m.getUsername()
+ + " trust -v \"FINGER_PRINT\" "
+ + e.getName()
+ + "' to mark it as trusted");
+ System.out.println("If you don't care about security, use 'signal-cli -u "
+ + m.getUsername()
+ + " trust -a "
+ + e.getName()
+ + "' to trust it without verification");
} else {
- System.out.println("Exception: " + exception.getMessage() + " (" + exception.getClass().getSimpleName() + ")");
+ System.out.println("Exception: " + exception.getMessage() + " (" + exception.getClass()
+ .getSimpleName() + ")");
}
}
if (content == null) {
System.out.println("Failed to decrypt message.");
} else {
ContactInfo sourceContact = m.getContact(content.getSender().getLegacyIdentifier());
- System.out.println(String.format("Sender: %s (device: %d)", (sourceContact == null ? "" : "“" + sourceContact.name + "” ") + content.getSender().getLegacyIdentifier(), content.getSenderDevice()));
+ System.out.println(String.format("Sender: %s (device: %d)",
+ (sourceContact == null ? "" : "“" + sourceContact.name + "” ") + content.getSender()
+ .getLegacyIdentifier(),
+ content.getSenderDevice()));
if (content.getDataMessage().isPresent()) {
SignalServiceDataMessage message = content.getDataMessage().get();
handleSignalServiceDataMessage(message);
System.out.println("Received sync read messages list");
for (ReadMessage rm : syncMessage.getRead().get()) {
ContactInfo fromContact = m.getContact(rm.getSender().getLegacyIdentifier());
- System.out.println("From: " + (fromContact == null ? "" : "“" + fromContact.name + "” ") + rm.getSender().getLegacyIdentifier() + " Message timestamp: " + DateUtils.formatTimestamp(rm.getTimestamp()));
+ System.out.println("From: "
+ + (fromContact == null ? "" : "“" + fromContact.name + "” ")
+ + rm.getSender().getLegacyIdentifier()
+ + " Message timestamp: "
+ + DateUtils.formatTimestamp(rm.getTimestamp()));
}
}
if (syncMessage.getRequest().isPresent()) {
StringBuilder toBuilder = new StringBuilder();
for (SignalServiceAddress dest : sentTranscriptMessage.getRecipients()) {
ContactInfo destContact = m.getContact(dest.getLegacyIdentifier());
- toBuilder.append(destContact == null ? "" : "“" + destContact.name + "” ").append(dest.getLegacyIdentifier()).append(" ");
+ toBuilder.append(destContact == null ? "" : "“" + destContact.name + "” ")
+ .append(dest.getLegacyIdentifier())
+ .append(" ");
}
to = toBuilder.toString();
} else {
to = "Unknown";
}
- System.out.println("To: " + to + " , Message timestamp: " + DateUtils.formatTimestamp(sentTranscriptMessage.getTimestamp()));
+ System.out.println("To: " + to + " , Message timestamp: " + DateUtils.formatTimestamp(
+ sentTranscriptMessage.getTimestamp()));
if (sentTranscriptMessage.getExpirationStartTimestamp() > 0) {
- System.out.println("Expiration started at: " + DateUtils.formatTimestamp(sentTranscriptMessage.getExpirationStartTimestamp()));
+ System.out.println("Expiration started at: " + DateUtils.formatTimestamp(
+ sentTranscriptMessage.getExpirationStartTimestamp()));
}
SignalServiceDataMessage message = sentTranscriptMessage.getMessage();
handleSignalServiceDataMessage(message);
if (syncMessage.getVerified().isPresent()) {
System.out.println("Received sync message with verified identities:");
final VerifiedMessage verifiedMessage = syncMessage.getVerified().get();
- System.out.println(" - " + verifiedMessage.getDestination() + ": " + verifiedMessage.getVerified());
- String safetyNumber = Util.formatSafetyNumber(m.computeSafetyNumber(verifiedMessage.getDestination(), verifiedMessage.getIdentityKey()));
+ System.out.println(" - "
+ + verifiedMessage.getDestination()
+ + ": "
+ + verifiedMessage.getVerified());
+ String safetyNumber = Util.formatSafetyNumber(m.computeSafetyNumber(verifiedMessage.getDestination(),
+ verifiedMessage.getIdentityKey()));
System.out.println(" " + safetyNumber);
}
if (syncMessage.getConfiguration().isPresent()) {
System.out.println("Received sync message with configuration:");
final ConfigurationMessage configurationMessage = syncMessage.getConfiguration().get();
if (configurationMessage.getReadReceipts().isPresent()) {
- System.out.println(" - Read receipts: " + (configurationMessage.getReadReceipts().get() ? "enabled" : "disabled"));
+ System.out.println(" - Read receipts: " + (
+ configurationMessage.getReadReceipts().get() ? "enabled" : "disabled"
+ ));
}
if (configurationMessage.getLinkPreviews().isPresent()) {
- System.out.println(" - Link previews: " + (configurationMessage.getLinkPreviews().get() ? "enabled" : "disabled"));
+ System.out.println(" - Link previews: " + (
+ configurationMessage.getLinkPreviews().get() ? "enabled" : "disabled"
+ ));
}
if (configurationMessage.getTypingIndicators().isPresent()) {
- System.out.println(" - Typing indicators: " + (configurationMessage.getTypingIndicators().get() ? "enabled" : "disabled"));
+ System.out.println(" - Typing indicators: " + (
+ configurationMessage.getTypingIndicators().get() ? "enabled" : "disabled"
+ ));
}
if (configurationMessage.getUnidentifiedDeliveryIndicators().isPresent()) {
- System.out.println(" - Unidentified Delivery Indicators: " + (configurationMessage.getUnidentifiedDeliveryIndicators().get() ? "enabled" : "disabled"));
+ System.out.println(" - Unidentified Delivery Indicators: " + (
+ configurationMessage.getUnidentifiedDeliveryIndicators().get()
+ ? "enabled"
+ : "disabled"
+ ));
}
}
if (syncMessage.getFetchType().isPresent()) {
System.out.println(" - Timestamp:" + viewOnceOpenMessage.getTimestamp());
}
if (syncMessage.getStickerPackOperations().isPresent()) {
- final List<StickerPackOperationMessage> stickerPackOperationMessages = syncMessage.getStickerPackOperations().get();
+ final List<StickerPackOperationMessage> stickerPackOperationMessages = syncMessage.getStickerPackOperations()
+ .get();
System.out.println("Received sync message with sticker pack operations:");
for (StickerPackOperationMessage m : stickerPackOperationMessages) {
System.out.println(" - " + m.getType().toString());
}
}
if (syncMessage.getMessageRequestResponse().isPresent()) {
- final MessageRequestResponseMessage requestResponseMessage = syncMessage.getMessageRequestResponse().get();
+ final MessageRequestResponseMessage requestResponseMessage = syncMessage.getMessageRequestResponse()
+ .get();
System.out.println("Received message request response:");
System.out.println(" Type: " + requestResponseMessage.getType());
if (requestResponseMessage.getGroupId().isPresent()) {
- System.out.println(" Group id: " + Base64.encodeBytes(requestResponseMessage.getGroupId().get()));
+ System.out.println(" Group id: " + Base64.encodeBytes(requestResponseMessage.getGroupId()
+ .get()));
}
if (requestResponseMessage.getPerson().isPresent()) {
- System.out.println(" Person: " + requestResponseMessage.getPerson().get().getLegacyIdentifier());
+ System.out.println(" Person: " + requestResponseMessage.getPerson()
+ .get()
+ .getLegacyIdentifier());
}
}
if (syncMessage.getKeys().isPresent()) {
final KeysMessage keysMessage = syncMessage.getKeys().get();
System.out.println("Received sync message with keys:");
if (keysMessage.getStorageService().isPresent()) {
- System.out.println(" With storage key length: " + keysMessage.getStorageService().get().serialize().length);
+ System.out.println(" With storage key length: " + keysMessage.getStorageService()
+ .get()
+ .serialize().length);
} else {
System.out.println(" With empty storage key");
}
if (callMessage.getIceUpdateMessages().isPresent()) {
List<IceUpdateMessage> iceUpdateMessages = callMessage.getIceUpdateMessages().get();
for (IceUpdateMessage iceUpdateMessage : iceUpdateMessages) {
- System.out.println("Ice update message: " + iceUpdateMessage.getId() + ", sdp: " + iceUpdateMessage.getSdp());
+ System.out.println("Ice update message: "
+ + iceUpdateMessage.getId()
+ + ", sdp: "
+ + iceUpdateMessage.getSdp());
}
}
if (callMessage.getOfferMessage().isPresent()) {
final SignalServiceDataMessage.Reaction reaction = message.getReaction().get();
System.out.println("Reaction:");
System.out.println(" - Emoji: " + reaction.getEmoji());
- System.out.println(" - Target author: " + m.resolveSignalServiceAddress(reaction.getTargetAuthor()).getLegacyIdentifier());
+ System.out.println(" - Target author: " + m.resolveSignalServiceAddress(reaction.getTargetAuthor())
+ .getLegacyIdentifier());
System.out.println(" - Target timestamp: " + reaction.getTargetSentTimestamp());
System.out.println(" - Is remove: " + reaction.isRemove());
}
final List<SignalServiceDataMessage.Mention> mentions = message.getMentions().get();
System.out.println("Mentions: ");
for (SignalServiceDataMessage.Mention mention : mentions) {
- System.out.println("- " + mention.getUuid() + ": " + mention.getStart() + " (length: " + mention.getLength() + ")");
+ System.out.println("- "
+ + mention.getUuid()
+ + ": "
+ + mention.getStart()
+ + " (length: "
+ + mention.getLength()
+ + ")");
}
}
}
private void printAttachment(SignalServiceAttachment attachment) {
- System.out.println("- " + attachment.getContentType() + " (" + (attachment.isPointer() ? "Pointer" : "") + (attachment.isStream() ? "Stream" : "") + ")");
+ System.out.println("- " + attachment.getContentType() + " (" + (attachment.isPointer() ? "Pointer" : "") + (
+ attachment.isStream() ? "Stream" : ""
+ ) + ")");
if (attachment.isPointer()) {
final SignalServiceAttachmentPointer pointer = attachment.asPointer();
System.out.println(" Id: " + pointer.getRemoteId() + " Key length: " + pointer.getKey().length);
- System.out.println(" Filename: " + (pointer.getFileName().isPresent() ? pointer.getFileName().get() : "-"));
- System.out.println(" Size: " + (pointer.getSize().isPresent() ? pointer.getSize().get() + " bytes" : "<unavailable>") + (pointer.getPreview().isPresent() ? " (Preview is available: " + pointer.getPreview().get().length + " bytes)" : ""));
+ System.out.println(" Filename: " + (
+ pointer.getFileName().isPresent() ? pointer.getFileName().get() : "-"
+ ));
+ System.out.println(" Size: " + (
+ pointer.getSize().isPresent() ? pointer.getSize().get() + " bytes" : "<unavailable>"
+ ) + (
+ pointer.getPreview().isPresent() ? " (Preview is available: "
+ + pointer.getPreview().get().length
+ + " bytes)" : ""
+ ));
System.out.println(" Voice note: " + (pointer.getVoiceNote() ? "yes" : "no"));
System.out.println(" Dimensions: " + pointer.getWidth() + "x" + pointer.getHeight());
File file = m.getAttachmentFile(pointer.getRemoteId());
@Override
public void attachToSubparser(final Subparser subparser) {
- subparser.addArgument("contact")
- .help("Contact number")
- .nargs("*");
- subparser.addArgument("-g", "--group")
- .help("Group ID")
- .nargs("*");
+ subparser.addArgument("contact").help("Contact number").nargs("*");
+ subparser.addArgument("-g", "--group").help("Group ID").nargs("*");
subparser.help("Block the given contacts or groups (no messages will be received)");
}
}
boolean ignoreAttachments = ns.getBoolean("ignore_attachments");
try {
- m.receiveMessages(1, TimeUnit.HOURS, false, ignoreAttachments, ns.getBoolean("json") ? new JsonDbusReceiveMessageHandler(m, conn, SIGNAL_OBJECTPATH) : new DbusReceiveMessageHandler(m, conn, SIGNAL_OBJECTPATH));
+ m.receiveMessages(1,
+ TimeUnit.HOURS,
+ false,
+ ignoreAttachments,
+ ns.getBoolean("json")
+ ? new JsonDbusReceiveMessageHandler(m, conn, SIGNAL_OBJECTPATH)
+ : new DbusReceiveMessageHandler(m, conn, SIGNAL_OBJECTPATH));
return 0;
} catch (IOException e) {
System.err.println("Error while receiving messages: " + e.getMessage());
@Override
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.");
}
@Override
e.printStackTrace();
return 2;
} catch (UserAlreadyExists e) {
- System.err.println("The user " + e.getUsername() + " already exists\nDelete \"" + e.getFileName() + "\" before trying again.");
+ System.err.println("The user "
+ + e.getUsername()
+ + " already exists\nDelete \""
+ + e.getFileName()
+ + "\" before trying again.");
return 1;
}
return 0;
try {
List<DeviceInfo> devices = m.getLinkedDevices();
for (DeviceInfo d : devices) {
- System.out.println("Device " + d.getId() + (d.getId() == m.getDeviceId() ? " (this device)" : "") + ":");
+ System.out.println("Device "
+ + d.getId()
+ + (d.getId() == m.getDeviceId() ? " (this device)" : "")
+ + ":");
System.out.println(" Name: " + d.getName());
System.out.println(" Created: " + DateUtils.formatTimestamp(d.getCreated()));
System.out.println(" Last seen: " + DateUtils.formatTimestamp(d.getLastSeen()));
.map(SignalServiceAddress::getLegacyIdentifier)
.collect(Collectors.toSet());
- System.out.println(String.format("Id: %s Name: %s Active: %s Blocked: %b Members: %s Pending members: %s Requesting members: %s",
- Base64.encodeBytes(group.groupId), group.getTitle(), group.isMember(m.getSelfAddress()), group.isBlocked(), members, pendingMembers, requestingMembers));
+ System.out.println(String.format(
+ "Id: %s Name: %s Active: %s Blocked: %b Members: %s Pending members: %s Requesting members: %s",
+ Base64.encodeBytes(group.groupId),
+ group.getTitle(),
+ group.isMember(m.getSelfAddress()),
+ group.isBlocked(),
+ members,
+ pendingMembers,
+ requestingMembers));
} else {
System.out.println(String.format("Id: %s Name: %s Active: %s Blocked: %b",
- Base64.encodeBytes(group.groupId), group.getTitle(), group.isMember(m.getSelfAddress()), group.isBlocked()));
+ Base64.encodeBytes(group.groupId),
+ group.getTitle(),
+ group.isMember(m.getSelfAddress()),
+ group.isBlocked()));
}
}
@Override
public void attachToSubparser(final Subparser subparser) {
- subparser.addArgument("-d", "--detailed").action(Arguments.storeTrue())
- .help("List members of each group");
+ subparser.addArgument("-d", "--detailed").action(Arguments.storeTrue()).help("List members of each group");
subparser.help("List group name and ids");
}
private static void printIdentityFingerprint(Manager m, JsonIdentityKeyStore.Identity theirId) {
String digits = Util.formatSafetyNumber(m.computeSafetyNumber(theirId.getAddress(), theirId.getIdentityKey()));
- System.out.println(String.format("%s: %s Added: %s Fingerprint: %s Safety Number: %s", theirId.getAddress().getNumber().orNull(),
- theirId.getTrustLevel(), theirId.getDateAdded(), Hex.toString(theirId.getFingerprint()), digits));
+ System.out.println(String.format("%s: %s Added: %s Fingerprint: %s Safety Number: %s",
+ theirId.getAddress().getNumber().orNull(),
+ theirId.getTrustLevel(),
+ theirId.getDateAdded(),
+ Hex.toString(theirId.getFingerprint()),
+ digits));
}
@Override
public void attachToSubparser(final Subparser subparser) {
- subparser.addArgument("-n", "--number")
- .help("Only show identity keys for the given phone number.");
+ subparser.addArgument("-n", "--number").help("Only show identity keys for the given phone number.");
}
@Override
@Override
public void attachToSubparser(final Subparser subparser) {
- subparser.addArgument("-g", "--group")
- .required(true)
- .help("Specify the recipient group ID.");
+ subparser.addArgument("-g", "--group").required(true).help("Specify the recipient group ID.");
}
@Override
}
try {
- final Pair<Long, List<SendMessageResult>> results = m.sendQuitGroupMessage(Util.decodeGroupId(ns.getString("group")));
+ final byte[] groupId = Util.decodeGroupId(ns.getString("group"));
+ final Pair<Long, List<SendMessageResult>> results = m.sendQuitGroupMessage(groupId);
return handleTimestampAndSendMessageResults(results.first(), results.second());
} catch (IOException e) {
handleIOException(e);
}
} else {
System.out.print(String.format("Envelope from: %s\nTimestamp: %s\nBody: %s\n",
- messageReceived.getSender(), DateUtils.formatTimestamp(messageReceived.getTimestamp()), messageReceived.getMessage()));
+ messageReceived.getSender(),
+ DateUtils.formatTimestamp(messageReceived.getTimestamp()),
+ messageReceived.getMessage()));
if (messageReceived.getGroupId().length > 0) {
System.out.println("Group info:");
System.out.println(" Id: " + Base64.encodeBytes(messageReceived.getGroupId()));
}
});
- dbusconnection.addSigHandler(Signal.ReceiptReceived.class,
- receiptReceived -> {
- if (jsonProcessor != null) {
- JsonMessageEnvelope envelope = new JsonMessageEnvelope(receiptReceived);
- ObjectNode result = jsonProcessor.createObjectNode();
- result.putPOJO("envelope", envelope);
- try {
- jsonProcessor.writeValue(System.out, result);
- System.out.println();
- } catch (IOException e) {
- e.printStackTrace();
- }
- } else {
- System.out.print(String.format("Receipt from: %s\nTimestamp: %s\n",
- receiptReceived.getSender(), DateUtils.formatTimestamp(receiptReceived.getTimestamp())));
- }
- });
+ dbusconnection.addSigHandler(Signal.ReceiptReceived.class, receiptReceived -> {
+ if (jsonProcessor != null) {
+ JsonMessageEnvelope envelope = new JsonMessageEnvelope(receiptReceived);
+ ObjectNode result = jsonProcessor.createObjectNode();
+ result.putPOJO("envelope", envelope);
+ try {
+ jsonProcessor.writeValue(System.out, result);
+ System.out.println();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ } else {
+ System.out.print(String.format("Receipt from: %s\nTimestamp: %s\n",
+ receiptReceived.getSender(),
+ DateUtils.formatTimestamp(receiptReceived.getTimestamp())));
+ }
+ });
dbusconnection.addSigHandler(Signal.SyncMessageReceived.class, syncReceived -> {
if (jsonProcessor != null) {
}
} else {
System.out.print(String.format("Sync Envelope from: %s to: %s\nTimestamp: %s\nBody: %s\n",
- syncReceived.getSource(), syncReceived.getDestination(), DateUtils.formatTimestamp(syncReceived.getTimestamp()), syncReceived.getMessage()));
+ syncReceived.getSource(),
+ syncReceived.getDestination(),
+ DateUtils.formatTimestamp(syncReceived.getTimestamp()),
+ syncReceived.getMessage()));
if (syncReceived.getGroupId().length > 0) {
System.out.println("Group info:");
System.out.println(" Id: " + Base64.encodeBytes(syncReceived.getGroupId()));
}
boolean ignoreAttachments = ns.getBoolean("ignore_attachments");
try {
- final Manager.ReceiveMessageHandler handler = ns.getBoolean("json") ? new JsonReceiveMessageHandler(m) : new ReceiveMessageHandler(m);
- m.receiveMessages((long) (timeout * 1000), TimeUnit.MILLISECONDS, returnOnTimeout, ignoreAttachments, handler);
+ final Manager.ReceiveMessageHandler handler = ns.getBoolean("json")
+ ? new JsonReceiveMessageHandler(m)
+ : new ReceiveMessageHandler(m);
+ m.receiveMessages((long) (timeout * 1000),
+ TimeUnit.MILLISECONDS,
+ returnOnTimeout,
+ ignoreAttachments,
+ handler);
return 0;
} catch (IOException e) {
System.err.println("Error while receiving messages: " + e.getMessage());
@Override
public void attachToSubparser(final Subparser subparser) {
- subparser.addArgument("-g", "--group")
- .help("Specify the recipient group ID.");
- subparser.addArgument("recipient")
- .help("Specify the recipients' phone number.")
- .nargs("*");
- subparser.addArgument("-m", "--message")
- .help("Specify the message, if missing standard input is used.");
- subparser.addArgument("-a", "--attachment")
- .nargs("*")
- .help("Add file as attachment");
+ subparser.addArgument("-g", "--group").help("Specify the recipient group ID.");
+ subparser.addArgument("recipient").help("Specify the recipients' phone number.").nargs("*");
+ subparser.addArgument("-m", "--message").help("Specify the message, if missing standard input is used.");
+ subparser.addArgument("-a", "--attachment").nargs("*").help("Add file as attachment");
subparser.addArgument("-e", "--endsession")
.help("Clear session state and send end session message.")
.action(Arguments.storeTrue());
return 1;
}
- if ((ns.getList("recipient") == null || ns.getList("recipient").size() == 0) && (ns.getBoolean("endsession") || ns.getString("group") == null)) {
+ if ((ns.getList("recipient") == null || ns.getList("recipient").size() == 0) && (
+ ns.getBoolean("endsession") || ns.getString("group") == null
+ )) {
System.err.println("No recipients given");
System.err.println("Aborting sending.");
return 1;
@Override
public void attachToSubparser(final Subparser subparser) {
subparser.help("Send reaction to a previously received or sent message.");
- subparser.addArgument("-g", "--group")
- .help("Specify the recipient group ID.");
- subparser.addArgument("recipient")
- .help("Specify the recipients' phone number.")
- .nargs("*");
+ subparser.addArgument("-g", "--group").help("Specify the recipient group ID.");
+ subparser.addArgument("recipient").help("Specify the recipients' phone number.").nargs("*");
subparser.addArgument("-e", "--emoji")
.required(true)
.help("Specify the emoji, should be a single unicode grapheme cluster.");
.required(true)
.type(long.class)
.help("Specify the timestamp of the message to which to react.");
- subparser.addArgument("-r", "--remove")
- .help("Remove a reaction.")
- .action(Arguments.storeTrue());
+ subparser.addArgument("-r", "--remove").help("Remove a reaction.").action(Arguments.storeTrue());
}
@Override
byte[] groupId = Util.decodeGroupId(ns.getString("group"));
results = m.sendGroupMessageReaction(emoji, isRemove, targetAuthor, targetTimestamp, groupId);
} else {
- results = m.sendMessageReaction(emoji, isRemove, targetAuthor, targetTimestamp, ns.getList("recipient"));
+ results = m.sendMessageReaction(emoji,
+ isRemove,
+ targetAuthor,
+ targetTimestamp,
+ ns.getList("recipient"));
}
handleTimestampAndSendMessageResults(results.first(), results.second());
return 0;
@Override
public void attachToSubparser(final Subparser subparser) {
- subparser.addArgument("number")
- .help("Specify the phone number, for which to set the trust.")
- .required(true);
+ subparser.addArgument("number").help("Specify the phone number, for which to set the trust.").required(true);
MutuallyExclusiveGroup mutTrust = subparser.addMutuallyExclusiveGroup();
mutTrust.addArgument("-a", "--trust-all-known-keys")
.help("Trust all known keys of this user, only use this for testing.")
try {
fingerprintBytes = Hex.toByteArray(safetyNumber.toLowerCase(Locale.ROOT));
} catch (Exception e) {
- System.err.println("Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
+ System.err.println(
+ "Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
return 1;
}
boolean res;
return 1;
}
if (!res) {
- System.err.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
+ System.err.println(
+ "Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
return 1;
}
} else if (safetyNumber.length() == 60) {
return 1;
}
if (!res) {
- System.err.println("Failed to set the trust for the safety number of this phone number, make sure the phone number and the safety number are correct.");
+ System.err.println(
+ "Failed to set the trust for the safety number of this phone number, make sure the phone number and the safety number are correct.");
return 1;
}
} else {
- System.err.println("Safety number has invalid format, either specify the old hex fingerprint or the new safety number");
+ System.err.println(
+ "Safety number has invalid format, either specify the old hex fingerprint or the new safety number");
return 1;
}
} else {
- System.err.println("You need to specify the fingerprint/safety number you have verified with -v SAFETY_NUMBER");
+ System.err.println(
+ "You need to specify the fingerprint/safety number you have verified with -v SAFETY_NUMBER");
return 1;
}
}
@Override
public void attachToSubparser(final Subparser subparser) {
- subparser.addArgument("contact")
- .help("Contact number")
- .nargs("*");
- subparser.addArgument("-g", "--group")
- .help("Group ID")
- .nargs("*");
+ subparser.addArgument("contact").help("Contact number").nargs("*");
+ subparser.addArgument("-g", "--group").help("Group ID").nargs("*");
subparser.help("Unblock the given contacts or groups (messages will be received again)");
}
@Override
public void attachToSubparser(final Subparser subparser) {
- subparser.addArgument("number")
- .help("Contact number");
- subparser.addArgument("-n", "--name")
- .required(true)
- .help("New contact name");
+ subparser.addArgument("number").help("Contact number");
+ subparser.addArgument("-n", "--name").required(true).help("New contact name");
subparser.addArgument("-e", "--expiration")
.required(false)
.type(int.class)
@Override
public void attachToSubparser(final Subparser subparser) {
- subparser.addArgument("-g", "--group")
- .help("Specify the recipient group ID.");
- subparser.addArgument("-n", "--name")
- .help("Specify the new group name.");
- subparser.addArgument("-a", "--avatar")
- .help("Specify a new group avatar image file");
- subparser.addArgument("-m", "--member")
- .nargs("*")
- .help("Specify one or more members to add to the group");
+ subparser.addArgument("-g", "--group").help("Specify the recipient group ID.");
+ subparser.addArgument("-n", "--name").help("Specify the new group name.");
+ subparser.addArgument("-a", "--avatar").help("Specify a new group avatar image file");
+ subparser.addArgument("-m", "--member").nargs("*").help("Specify one or more members to add to the group");
}
@Override
@Override
public void attachToSubparser(final Subparser subparser) {
- final MutuallyExclusiveGroup avatarOptions = subparser.addMutuallyExclusiveGroup()
- .required(true);
- avatarOptions.addArgument("--avatar")
- .help("Path to new profile avatar");
- avatarOptions.addArgument("--remove-avatar")
- .action(Arguments.storeTrue());
-
- subparser.addArgument("--name")
- .required(true)
- .help("New profile name");
+ final MutuallyExclusiveGroup avatarOptions = subparser.addMutuallyExclusiveGroup().required(true);
+ avatarOptions.addArgument("--avatar").help("Path to new profile avatar");
+ avatarOptions.addArgument("--remove-avatar").action(Arguments.storeTrue());
+
+ subparser.addArgument("--name").required(true).help("New profile name");
subparser.help("Set a name and avatar image for the user profile");
}
@Override
public void attachToSubparser(final Subparser subparser) {
- subparser.addArgument("verificationCode")
- .help("The verification code you received via sms or voice call.");
- subparser.addArgument("-p", "--pin")
- .help("The registration lock PIN, that was set by the user (Optional)");
+ subparser.addArgument("verificationCode").help("The verification code you received via sms or voice call.");
+ subparser.addArgument("-p", "--pin").help("The registration lock PIN, that was set by the user (Optional)");
}
@Override
m.verifyAccount(verificationCode, pin);
return 0;
} catch (LockedException e) {
- System.err.println("Verification failed! This number is locked with a pin. Hours remaining until reset: " + (e.getTimeRemaining() / 1000 / 60 / 60));
+ System.err.println("Verification failed! This number is locked with a pin. Hours remaining until reset: "
+ + (e.getTimeRemaining() / 1000 / 60 / 60));
System.err.println("Use '--pin PIN_CODE' to specify the registration lock PIN");
return 3;
} catch (IOException e) {
}
private static void checkSendMessageResults(
- long timestamp,
- List<SendMessageResult> results
+ long timestamp, List<SendMessageResult> results
) throws DBusExecutionException {
List<String> errors = ErrorUtils.getErrorMessagesFromSendMessageResults(results);
if (errors.size() == 0) {
timestamp = messageReceived.getTimestamp();
message = messageReceived.getMessage();
groupInfo = new JsonGroupInfo(messageReceived.getGroupId());
- attachments = messageReceived.getAttachments()
- .stream()
- .map(JsonAttachment::new)
- .collect(Collectors.toList());
+ attachments = messageReceived.getAttachments().stream().map(JsonAttachment::new).collect(Collectors.toList());
}
public JsonDataMessage(Signal.SyncMessageReceived messageReceived) {
timestamp = messageReceived.getTimestamp();
message = messageReceived.getMessage();
groupInfo = new JsonGroupInfo(messageReceived.getGroupId());
- attachments = messageReceived.getAttachments()
- .stream()
- .map(JsonAttachment::new)
- .collect(Collectors.toList());
+ attachments = messageReceived.getAttachments().stream().map(JsonAttachment::new).collect(Collectors.toList());
}
}
this.timestamps = receiptMessage.getTimestamps();
}
- private JsonReceiptMessage(final long when, final boolean isDelivery, final boolean isRead, final List<Long> timestamps) {
+ private JsonReceiptMessage(
+ final long when, final boolean isDelivery, final boolean isRead, final List<Long> timestamps
+ ) {
this.when = when;
this.isDelivery = isDelivery;
this.isRead = isRead;
--- /dev/null
+package org.asamk.signal.manager;
+
+import org.asamk.signal.storage.groups.GroupInfo;
+import org.asamk.signal.storage.groups.GroupInfoV1;
+import org.asamk.signal.storage.groups.GroupInfoV2;
+import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage;
+import org.whispersystems.signalservice.api.messages.SignalServiceGroup;
+import org.whispersystems.signalservice.api.messages.SignalServiceGroupV2;
+
+public class GroupUtils {
+
+ public static void setGroupContext(
+ final SignalServiceDataMessage.Builder messageBuilder, final GroupInfo groupInfo
+ ) {
+ if (groupInfo instanceof GroupInfoV1) {
+ SignalServiceGroup group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.DELIVER)
+ .withId(groupInfo.groupId)
+ .build();
+ messageBuilder.asGroupMessage(group);
+ } else {
+ final GroupInfoV2 groupInfoV2 = (GroupInfoV2) groupInfo;
+ SignalServiceGroupV2 group = SignalServiceGroupV2.newBuilder(groupInfoV2.getMasterKey())
+ .withRevision(groupInfoV2.getGroup() == null ? 0 : groupInfoV2.getGroup().getRevision())
+ .build();
+ messageBuilder.asGroupMessage(group);
+ }
+ }
+}
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final SendReceiptAction that = (SendReceiptAction) o;
- return timestamp == that.timestamp &&
- address.equals(that.address);
+ return timestamp == that.timestamp && address.equals(that.address);
}
@Override
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final SendGroupInfoRequestAction that = (SendGroupInfoRequestAction) o;
- return address.equals(that.address) &&
- Arrays.equals(groupId, that.groupId);
+ return address.equals(that.address) && Arrays.equals(groupId, that.groupId);
}
@Override
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final SendGroupUpdateAction that = (SendGroupUpdateAction) o;
- return address.equals(that.address) &&
- Arrays.equals(groupId, that.groupId);
+ return address.equals(that.address) && Arrays.equals(groupId, that.groupId);
}
@Override
) throws IOException, GroupNotFoundException, NotAGroupMemberException {
final GroupInfo g = getGroupForSending(groupId);
- GroupHelper.setGroupContext(messageBuilder, g);
+ GroupUtils.setGroupContext(messageBuilder, g);
messageBuilder.withExpiration(g.getMessageExpirationTime());
return sendMessage(messageBuilder, g.getMembersWithout(account.getSelfAddress()));
private final String avatarsPath;
public static PathConfig createDefault(final String settingsPath) {
- return new PathConfig(
- settingsPath + "/data",
- settingsPath + "/attachments",
- settingsPath + "/avatars"
- );
+ return new PathConfig(settingsPath + "/data", settingsPath + "/attachments", settingsPath + "/avatars");
}
private PathConfig(final String dataPath, final String attachmentsPath, final String avatarsPath) {
public String getDeviceLinkUri() throws TimeoutException, IOException {
String deviceUuid = accountManager.getNewDeviceUuid();
- return Utils.createDeviceLinkUri(new Utils.DeviceLinkInfo(deviceUuid, identityKey.getPublicKey().getPublicKey()));
+ return Utils.createDeviceLinkUri(new Utils.DeviceLinkInfo(deviceUuid,
+ identityKey.getPublicKey().getPublicKey()));
}
public String finishDeviceLink(String deviceName) throws IOException, InvalidKeyException, TimeoutException, UserAlreadyExists {
String signalingKey = KeyUtils.createSignalingKey();
- SignalServiceAccountManager.NewDeviceRegistrationReturn ret = accountManager.finishNewDeviceRegistration(identityKey, signalingKey, false, true, registrationId, deviceName);
+ SignalServiceAccountManager.NewDeviceRegistrationReturn ret = accountManager.finishNewDeviceRegistration(
+ identityKey,
+ signalingKey,
+ false,
+ true,
+ registrationId,
+ deviceName);
String username = ret.getNumber();
// TODO do this check before actually registering
}
}
- try (SignalAccount account = SignalAccount.createLinkedAccount(pathConfig.getDataPath(), username, ret.getUuid(), password, ret.getDeviceId(), ret.getIdentity(), registrationId, signalingKey, profileKey)) {
+ try (SignalAccount account = SignalAccount.createLinkedAccount(pathConfig.getDataPath(),
+ username,
+ ret.getUuid(),
+ password,
+ ret.getDeviceId(),
+ ret.getIdentity(),
+ registrationId,
+ signalingKey,
+ profileKey)) {
account.save();
try (Manager m = new Manager(account, pathConfig, serviceConfiguration, userAgent)) {
}
public static SignalServiceConfiguration createDefaultServiceConfiguration(String userAgent) {
- final Interceptor userAgentInterceptor = chain ->
- chain.proceed(chain.request().newBuilder()
- .header("User-Agent", userAgent)
- .build());
+ final Interceptor userAgentInterceptor = chain -> chain.proceed(chain.request()
+ .newBuilder()
+ .header("User-Agent", userAgent)
+ .build());
final List<Interceptor> interceptors = Collections.singletonList(userAgentInterceptor);
- return new SignalServiceConfiguration(
- new SignalServiceUrl[]{new SignalServiceUrl(URL, TRUST_STORE)},
- makeSignalCdnUrlMapFor(new SignalCdnUrl[]{new SignalCdnUrl(CDN_URL, TRUST_STORE)}, new SignalCdnUrl[]{new SignalCdnUrl(CDN2_URL, TRUST_STORE)}),
+ return new SignalServiceConfiguration(new SignalServiceUrl[]{new SignalServiceUrl(URL, TRUST_STORE)},
+ makeSignalCdnUrlMapFor(new SignalCdnUrl[]{new SignalCdnUrl(CDN_URL, TRUST_STORE)},
+ new SignalCdnUrl[]{new SignalCdnUrl(CDN2_URL, TRUST_STORE)}),
new SignalContactDiscoveryUrl[0],
new SignalKeyBackupServiceUrl[]{new SignalKeyBackupServiceUrl(SIGNAL_KEY_BACKUP_URL, TRUST_STORE)},
new SignalStorageUrl[]{new SignalStorageUrl(STORAGE_URL, TRUST_STORE)},
interceptors,
dns,
- zkGroupServerPublicParams
- );
+ zkGroupServerPublicParams);
}
- private static Map<Integer, SignalCdnUrl[]> makeSignalCdnUrlMapFor(SignalCdnUrl[] cdn0Urls, SignalCdnUrl[] cdn2Urls) {
+ private static Map<Integer, SignalCdnUrl[]> makeSignalCdnUrlMapFor(
+ SignalCdnUrl[] cdn0Urls, SignalCdnUrl[] cdn2Urls
+ ) {
return Map.of(0, cdn0Urls, 2, cdn2Urls);
}
Optional<String> caption = Optional.absent();
Optional<String> blurHash = Optional.absent();
final Optional<ResumableUploadSpec> resumableUploadSpec = Optional.absent();
- return new SignalServiceAttachmentStream(attachmentStream, mime, attachmentSize, Optional.of(attachmentFile.getName()), false, false, preview, 0, 0, uploadTimestamp, caption, blurHash, null, null, resumableUploadSpec);
+ return new SignalServiceAttachmentStream(attachmentStream,
+ mime,
+ attachmentSize,
+ Optional.of(attachmentFile.getName()),
+ false,
+ false,
+ preview,
+ 0,
+ 0,
+ uploadTimestamp,
+ caption,
+ blurHash,
+ null,
+ null,
+ resumableUploadSpec);
}
static StreamDetails createStreamDetailsFromFile(File file) throws IOException {
static CertificateValidator getCertificateValidator() {
try {
- ECPublicKey unidentifiedSenderTrustRoot = Curve.decodePoint(Base64.decode(ServiceConfig.UNIDENTIFIED_SENDER_TRUST_ROOT), 0);
+ ECPublicKey unidentifiedSenderTrustRoot = Curve.decodePoint(Base64.decode(ServiceConfig.UNIDENTIFIED_SENDER_TRUST_ROOT),
+ 0);
return new CertificateValidator(unidentifiedSenderTrustRoot);
} catch (InvalidKeyException | IOException e) {
throw new AssertionError(e);
}
static String createDeviceLinkUri(DeviceLinkInfo info) {
- return "tsdevice:/?uuid=" + URLEncoder.encode(info.deviceIdentifier, StandardCharsets.UTF_8) + "&pub_key=" + URLEncoder.encode(Base64.encodeBytesWithoutPadding(info.deviceKey.serialize()), StandardCharsets.UTF_8);
+ return "tsdevice:/?uuid="
+ + URLEncoder.encode(info.deviceIdentifier, StandardCharsets.UTF_8)
+ + "&pub_key="
+ + URLEncoder.encode(Base64.encodeBytesWithoutPadding(info.deviceKey.serialize()),
+ StandardCharsets.UTF_8);
}
static DeviceLinkInfo parseDeviceLinkUri(URI linkUri) throws IOException, InvalidKeyException {
Optional<SignalServiceAddress> addressOptional = sourceUuid == null && source.isEmpty()
? Optional.absent()
: Optional.of(new SignalServiceAddress(sourceUuid, source));
- return new SignalServiceEnvelope(type, addressOptional, sourceDevice, timestamp, legacyMessage, content, serverReceivedTimestamp, serverDeliveredTimestamp, uuid);
+ return new SignalServiceEnvelope(type,
+ addressOptional,
+ sourceDevice,
+ timestamp,
+ legacyMessage,
+ content,
+ serverReceivedTimestamp,
+ serverDeliveredTimestamp,
+ uuid);
}
}
return outputFile;
}
- static String computeSafetyNumber(SignalServiceAddress ownAddress, IdentityKey ownIdentityKey, SignalServiceAddress theirAddress, IdentityKey theirIdentityKey) {
+ static String computeSafetyNumber(
+ SignalServiceAddress ownAddress,
+ IdentityKey ownIdentityKey,
+ SignalServiceAddress theirAddress,
+ IdentityKey theirIdentityKey
+ ) {
int version;
byte[] ownId;
byte[] theirId;
- if (ServiceConfig.capabilities.isUuid()
- && ownAddress.getUuid().isPresent() && theirAddress.getUuid().isPresent()) {
+ if (ServiceConfig.capabilities.isUuid() && ownAddress.getUuid().isPresent() && theirAddress.getUuid()
+ .isPresent()) {
// Version 2: UUID user
version = 2;
ownId = UuidUtil.toByteArray(ownAddress.getUuid().get());
theirId = theirAddress.getNumber().get().getBytes();
}
- Fingerprint fingerprint = new NumericFingerprintGenerator(5200).createFor(version, ownId, ownIdentityKey, theirId, theirIdentityKey);
+ Fingerprint fingerprint = new NumericFingerprintGenerator(5200).createFor(version,
+ ownId,
+ ownIdentityKey,
+ theirId,
+ theirIdentityKey);
return fingerprint.getDisplayableFingerprint().getDisplayText();
}
package org.asamk.signal.manager.helper;
-import org.asamk.signal.storage.groups.GroupInfo;
-import org.asamk.signal.storage.groups.GroupInfoV1;
-import org.asamk.signal.storage.groups.GroupInfoV2;
import org.signal.storageservice.protos.groups.Member;
import org.signal.zkgroup.groups.GroupSecretParams;
import org.signal.zkgroup.profiles.ProfileKeyCredential;
import org.whispersystems.libsignal.util.guava.Optional;
import org.whispersystems.signalservice.api.groupsv2.GroupCandidate;
import org.whispersystems.signalservice.api.groupsv2.GroupsV2Operations;
-import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage;
-import org.whispersystems.signalservice.api.messages.SignalServiceGroup;
-import org.whispersystems.signalservice.api.messages.SignalServiceGroupV2;
import org.whispersystems.signalservice.api.push.SignalServiceAddress;
import java.util.Collection;
this.groupsV2Operations = groupsV2Operations;
}
- public static void setGroupContext(
- final SignalServiceDataMessage.Builder messageBuilder, final GroupInfo groupInfo
- ) {
- if (groupInfo instanceof GroupInfoV1) {
- SignalServiceGroup group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.DELIVER)
- .withId(groupInfo.groupId)
- .build();
- messageBuilder.asGroupMessage(group);
- } else {
- final GroupInfoV2 groupInfoV2 = (GroupInfoV2) groupInfo;
- SignalServiceGroupV2 group = SignalServiceGroupV2.newBuilder(groupInfoV2.getMasterKey())
- .withRevision(groupInfoV2.getGroup() == null ? 0 : groupInfoV2.getGroup().getRevision())
- .build();
- messageBuilder.asGroupMessage(group);
- }
- }
-
public GroupsV2Operations.NewGroup createGroupV2(
String name, Collection<SignalServiceAddress> members, byte[] avatar
) {
}
public ProfileAndCredential retrieveProfileSync(
- SignalServiceAddress recipient,
- SignalServiceProfile.RequestType requestType
+ SignalServiceAddress recipient, SignalServiceProfile.RequestType requestType
) throws IOException {
try {
return retrieveProfile(recipient, requestType).get(10, TimeUnit.SECONDS);
}
public ListenableFuture<ProfileAndCredential> retrieveProfile(
- SignalServiceAddress address,
- SignalServiceProfile.RequestType requestType
+ SignalServiceAddress address, SignalServiceProfile.RequestType requestType
) {
Optional<UnidentifiedAccess> unidentifiedAccess = getUnidentifiedAccess(address);
Optional<ProfileKey> profileKey = Optional.fromNullable(profileKeyProvider.getProfileKey(address));
if (unidentifiedAccess.isPresent()) {
- return new CascadingFuture<>(Arrays.asList(() -> getPipeRetrievalFuture(address, profileKey, unidentifiedAccess, requestType),
+ return new CascadingFuture<>(Arrays.asList(() -> getPipeRetrievalFuture(address,
+ profileKey,
+ unidentifiedAccess,
+ requestType),
() -> getSocketRetrievalFuture(address, profileKey, unidentifiedAccess, requestType),
() -> getPipeRetrievalFuture(address, profileKey, Optional.absent(), requestType),
() -> getSocketRetrievalFuture(address, profileKey, Optional.absent(), requestType)),
e -> !(e instanceof NotFoundException));
} else {
- return new CascadingFuture<>(Arrays.asList(() -> getPipeRetrievalFuture(address, profileKey, Optional.absent(), requestType),
- () -> getSocketRetrievalFuture(address, profileKey, Optional.absent(), requestType)),
+ return new CascadingFuture<>(Arrays.asList(() -> getPipeRetrievalFuture(address,
+ profileKey,
+ Optional.absent(),
+ requestType), () -> getSocketRetrievalFuture(address, profileKey, Optional.absent(), requestType)),
e -> !(e instanceof NotFoundException));
}
}
public String decryptName(
- ProfileKey profileKey,
- String encryptedName
+ ProfileKey profileKey, String encryptedName
) throws InvalidCiphertextException, IOException {
if (encryptedName == null) {
return null;
private final UnidentifiedAccessSenderCertificateProvider senderCertificateProvider;
- public UnidentifiedAccessHelper(final SelfProfileKeyProvider selfProfileKeyProvider, final ProfileKeyProvider profileKeyProvider, final ProfileProvider profileProvider, final UnidentifiedAccessSenderCertificateProvider senderCertificateProvider) {
+ public UnidentifiedAccessHelper(
+ final SelfProfileKeyProvider selfProfileKeyProvider,
+ final ProfileKeyProvider profileKeyProvider,
+ final ProfileProvider profileProvider,
+ final UnidentifiedAccessSenderCertificateProvider senderCertificateProvider
+ ) {
this.selfProfileKeyProvider = selfProfileKeyProvider;
this.profileKeyProvider = profileKeyProvider;
this.profileProvider = profileProvider;
}
try {
- return Optional.of(new UnidentifiedAccessPair(
- new UnidentifiedAccess(selfUnidentifiedAccessKey, selfUnidentifiedAccessCertificate),
- new UnidentifiedAccess(selfUnidentifiedAccessKey, selfUnidentifiedAccessCertificate)
- ));
+ return Optional.of(new UnidentifiedAccessPair(new UnidentifiedAccess(selfUnidentifiedAccessKey,
+ selfUnidentifiedAccessCertificate),
+ new UnidentifiedAccess(selfUnidentifiedAccessKey, selfUnidentifiedAccessCertificate)));
} catch (InvalidCertificateException e) {
return Optional.absent();
}
}
public List<Optional<UnidentifiedAccessPair>> getAccessFor(Collection<SignalServiceAddress> recipients) {
- return recipients.stream()
- .map(this::getAccessFor)
- .collect(Collectors.toList());
+ return recipients.stream().map(this::getAccessFor).collect(Collectors.toList());
}
public Optional<UnidentifiedAccessPair> getAccessFor(SignalServiceAddress recipient) {
byte[] selfUnidentifiedAccessKey = getSelfUnidentifiedAccessKey();
byte[] selfUnidentifiedAccessCertificate = senderCertificateProvider.getSenderCertificate();
- if (recipientUnidentifiedAccessKey == null || selfUnidentifiedAccessKey == null || selfUnidentifiedAccessCertificate == null) {
+ if (recipientUnidentifiedAccessKey == null
+ || selfUnidentifiedAccessKey == null
+ || selfUnidentifiedAccessCertificate == null) {
return Optional.absent();
}
try {
- return Optional.of(new UnidentifiedAccessPair(
- new UnidentifiedAccess(recipientUnidentifiedAccessKey, selfUnidentifiedAccessCertificate),
- new UnidentifiedAccess(selfUnidentifiedAccessKey, selfUnidentifiedAccessCertificate)
- ));
+ return Optional.of(new UnidentifiedAccessPair(new UnidentifiedAccess(recipientUnidentifiedAccessKey,
+ selfUnidentifiedAccessCertificate),
+ new UnidentifiedAccess(selfUnidentifiedAccessKey, selfUnidentifiedAccessCertificate)));
} catch (InvalidCertificateException e) {
return Optional.absent();
}
}
}
- public static SignalAccount create(String dataPath, String username, IdentityKeyPair identityKey, int registrationId, ProfileKey profileKey) throws IOException {
+ public static SignalAccount create(
+ String dataPath, String username, IdentityKeyPair identityKey, int registrationId, ProfileKey profileKey
+ ) throws IOException {
IOUtils.createPrivateDirectories(dataPath);
String fileName = getFileName(dataPath, username);
if (!new File(fileName).exists()) {
return account;
}
- public static SignalAccount createLinkedAccount(String dataPath, String username, UUID uuid, String password, int deviceId, IdentityKeyPair identityKey, int registrationId, String signalingKey, ProfileKey profileKey) throws IOException {
+ public static SignalAccount createLinkedAccount(
+ String dataPath,
+ String username,
+ UUID uuid,
+ String password,
+ int deviceId,
+ IdentityKeyPair identityKey,
+ int registrationId,
+ String signalingKey,
+ ProfileKey profileKey
+ ) throws IOException {
IOUtils.createPrivateDirectories(dataPath);
String fileName = getFileName(dataPath, username);
if (!new File(fileName).exists()) {
try {
profileKey = new ProfileKey(Base64.decode(Util.getNotNullNode(rootNode, "profileKey").asText()));
} catch (InvalidInputException e) {
- throw new IOException("Config file contains an invalid profileKey, needs to be base64 encoded array of 32 bytes", e);
+ throw new IOException(
+ "Config file contains an invalid profileKey, needs to be base64 encoded array of 32 bytes",
+ e);
}
}
- signalProtocolStore = jsonProcessor.convertValue(Util.getNotNullNode(rootNode, "axolotlStore"), JsonSignalProtocolStore.class);
+ signalProtocolStore = jsonProcessor.convertValue(Util.getNotNullNode(rootNode, "axolotlStore"),
+ JsonSignalProtocolStore.class);
registered = Util.getNotNullNode(rootNode, "registered").asBoolean();
JsonNode groupStoreNode = rootNode.get("groupStore");
if (groupStoreNode != null) {
JsonNode threadStoreNode = rootNode.get("threadStore");
if (threadStoreNode != null) {
- LegacyJsonThreadStore threadStore = jsonProcessor.convertValue(threadStoreNode, LegacyJsonThreadStore.class);
+ LegacyJsonThreadStore threadStore = jsonProcessor.convertValue(threadStoreNode,
+ LegacyJsonThreadStore.class);
// Migrate thread info to group and contact store
for (ThreadInfo thread : threadStore.getThreads()) {
if (thread.id == null || thread.id.isEmpty()) {
.putPOJO("contactStore", contactStore)
.putPOJO("recipientStore", recipientStore)
.putPOJO("profileStore", profileStore)
- .putPOJO("stickerStore", stickerStore)
- ;
+ .putPOJO("stickerStore", stickerStore);
try {
try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
// Write to memory first to prevent corrupting the file in case of serialization errors
return name;
}
- public GroupInfoV1(@JsonProperty("groupId") byte[] groupId, @JsonProperty("name") String name, @JsonProperty("members") Collection<SignalServiceAddress> members, @JsonProperty("avatarId") long _ignored_avatarId, @JsonProperty("color") String color, @JsonProperty("blocked") boolean blocked, @JsonProperty("inboxPosition") Integer inboxPosition, @JsonProperty("archived") boolean archived, @JsonProperty("messageExpirationTime") int messageExpirationTime, @JsonProperty("active") boolean _ignored_active) {
+ public GroupInfoV1(
+ @JsonProperty("groupId") byte[] groupId,
+ @JsonProperty("name") String name,
+ @JsonProperty("members") Collection<SignalServiceAddress> members,
+ @JsonProperty("avatarId") long _ignored_avatarId,
+ @JsonProperty("color") String color,
+ @JsonProperty("blocked") boolean blocked,
+ @JsonProperty("inboxPosition") Integer inboxPosition,
+ @JsonProperty("archived") boolean archived,
+ @JsonProperty("messageExpirationTime") int messageExpirationTime,
+ @JsonProperty("active") boolean _ignored_active
+ ) {
super(groupId);
this.name = name;
this.members.addAll(members);
private static class MembersSerializer extends JsonSerializer<Set<SignalServiceAddress>> {
@Override
- public void serialize(final Set<SignalServiceAddress> value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException {
+ public void serialize(
+ final Set<SignalServiceAddress> value, final JsonGenerator jgen, final SerializerProvider provider
+ ) throws IOException {
jgen.writeStartArray(value.size());
for (SignalServiceAddress address : value) {
if (address.getUuid().isPresent()) {
private static class MembersDeserializer extends JsonDeserializer<Set<SignalServiceAddress>> {
@Override
- public Set<SignalServiceAddress> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
+ public Set<SignalServiceAddress> deserialize(
+ JsonParser jsonParser, DeserializationContext deserializationContext
+ ) throws IOException {
Set<SignalServiceAddress> addresses = new HashSet<>();
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
for (JsonNode n : node) {
if (this.group == null) {
return Collections.emptySet();
}
- return group.getMembersList().stream()
+ return group.getMembersList()
+ .stream()
.map(m -> new SignalServiceAddress(UuidUtil.parseOrThrow(m.getUuid().toByteArray()), null))
.collect(Collectors.toSet());
}
if (this.group == null) {
return Collections.emptySet();
}
- return group.getPendingMembersList().stream()
+ return group.getPendingMembersList()
+ .stream()
.map(m -> new SignalServiceAddress(UuidUtil.parseOrThrow(m.getUuid().toByteArray()), null))
.collect(Collectors.toSet());
}
if (this.group == null) {
return Collections.emptySet();
}
- return group.getRequestingMembersList().stream()
+ return group.getRequestingMembersList()
+ .stream()
.map(m -> new SignalServiceAddress(UuidUtil.parseOrThrow(m.getUuid().toByteArray()), null))
.collect(Collectors.toSet());
}
@Override
public void serialize(
- final Map<String, GroupInfo> value,
- final JsonGenerator jgen,
- final SerializerProvider provider
+ final Map<String, GroupInfo> value, final JsonGenerator jgen, final SerializerProvider provider
) throws IOException {
final Collection<GroupInfo> groups = value.values();
jgen.writeStartArray(groups.size());
@Override
public Map<String, GroupInfo> deserialize(
- JsonParser jsonParser,
- DeserializationContext deserializationContext
+ JsonParser jsonParser, DeserializationContext deserializationContext
) throws IOException {
Map<String, GroupInfo> groups = new HashMap<>();
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
@JsonProperty
private final Capabilities capabilities;
- public SignalProfile(final String identityKey, final String name, final File avatarFile, final String unidentifiedAccess, final boolean unrestrictedUnidentifiedAccess, final SignalServiceProfile.Capabilities capabilities) {
+ public SignalProfile(
+ final String identityKey,
+ final String name,
+ final File avatarFile,
+ final String unidentifiedAccess,
+ final boolean unrestrictedUnidentifiedAccess,
+ final SignalServiceProfile.Capabilities capabilities
+ ) {
this.identityKey = identityKey;
this.name = name;
this.avatarFile = avatarFile;
this.capabilities.gv2 = capabilities.isGv2();
}
- public SignalProfile(@JsonProperty("identityKey") final String identityKey, @JsonProperty("name") final String name, @JsonProperty("unidentifiedAccess") final String unidentifiedAccess, @JsonProperty("unrestrictedUnidentifiedAccess") final boolean unrestrictedUnidentifiedAccess, @JsonProperty("capabilities") final Capabilities capabilities) {
+ public SignalProfile(
+ @JsonProperty("identityKey") final String identityKey,
+ @JsonProperty("name") final String name,
+ @JsonProperty("unidentifiedAccess") final String unidentifiedAccess,
+ @JsonProperty("unrestrictedUnidentifiedAccess") final boolean unrestrictedUnidentifiedAccess,
+ @JsonProperty("capabilities") final Capabilities capabilities
+ ) {
this.identityKey = identityKey;
this.name = name;
this.avatarFile = null;
@Override
public String toString() {
- return "SignalProfile{" +
- "identityKey='" + identityKey + '\'' +
- ", name='" + name + '\'' +
- ", avatarFile=" + avatarFile +
- ", unidentifiedAccess='" + unidentifiedAccess + '\'' +
- ", unrestrictedUnidentifiedAccess=" + unrestrictedUnidentifiedAccess +
- ", capabilities=" + capabilities +
- '}';
+ return "SignalProfile{"
+ + "identityKey='"
+ + identityKey
+ + '\''
+ + ", name='"
+ + name
+ + '\''
+ + ", avatarFile="
+ + avatarFile
+ + ", unidentifiedAccess='"
+ + unidentifiedAccess
+ + '\''
+ + ", unrestrictedUnidentifiedAccess="
+ + unrestrictedUnidentifiedAccess
+ + ", capabilities="
+ + capabilities
+ + '}';
}
public static class Capabilities {
@Override
public boolean saveIdentity(SignalProtocolAddress address, IdentityKey identityKey) {
- return saveIdentity(resolveSignalServiceAddress(address.getName()), identityKey, TrustLevel.TRUSTED_UNVERIFIED, null);
+ return saveIdentity(resolveSignalServiceAddress(address.getName()),
+ identityKey,
+ TrustLevel.TRUSTED_UNVERIFIED,
+ null);
}
/**
* @param trustLevel Level of trust: untrusted, trusted, trusted and verified
* @param added Added timestamp, if null and the key is newly added, the current time is used.
*/
- public boolean saveIdentity(SignalServiceAddress serviceAddress, IdentityKey identityKey, TrustLevel trustLevel, Date added) {
+ public boolean saveIdentity(
+ SignalServiceAddress serviceAddress, IdentityKey identityKey, TrustLevel trustLevel, Date added
+ ) {
for (Identity id : identities) {
if (!id.address.matches(serviceAddress) || !id.identityKey.equals(identityKey)) {
continue;
* @param identityKey The user's public key
* @param trustLevel Level of trust: untrusted, trusted, trusted and verified
*/
- public void setIdentityTrustLevel(SignalServiceAddress serviceAddress, IdentityKey identityKey, TrustLevel trustLevel) {
+ public void setIdentityTrustLevel(
+ SignalServiceAddress serviceAddress, IdentityKey identityKey, TrustLevel trustLevel
+ ) {
for (Identity id : identities) {
if (!id.address.matches(serviceAddress) || !id.identityKey.equals(identityKey)) {
continue;
public static class JsonIdentityKeyStoreDeserializer extends JsonDeserializer<JsonIdentityKeyStore> {
@Override
- public JsonIdentityKeyStore deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
+ public JsonIdentityKeyStore deserialize(
+ JsonParser jsonParser, DeserializationContext deserializationContext
+ ) throws IOException {
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
try {
JsonNode trustedKeysNode = node.get("trustedKeys");
if (trustedKeysNode.isArray()) {
for (JsonNode trustedKey : trustedKeysNode) {
- String trustedKeyName = trustedKey.hasNonNull("name")
- ? trustedKey.get("name").asText()
- : null;
+ String trustedKeyName = trustedKey.hasNonNull("name") ? trustedKey.get("name").asText() : null;
if (UuidUtil.isUuid(trustedKeyName)) {
// Ignore identities that were incorrectly created with UUIDs as name
continue;
}
- UUID uuid = trustedKey.hasNonNull("uuid")
- ? UuidUtil.parseOrNull(trustedKey.get("uuid").asText())
- : null;
+ UUID uuid = trustedKey.hasNonNull("uuid") ? UuidUtil.parseOrNull(trustedKey.get("uuid")
+ .asText()) : null;
final SignalServiceAddress serviceAddress = uuid == null
? Util.getSignalServiceAddressFromIdentifier(trustedKeyName)
: new SignalServiceAddress(uuid, trustedKeyName);
try {
IdentityKey id = new IdentityKey(Base64.decode(trustedKey.get("identityKey").asText()), 0);
- TrustLevel trustLevel = trustedKey.has("trustLevel") ? TrustLevel.fromInt(trustedKey.get("trustLevel").asInt()) : TrustLevel.TRUSTED_UNVERIFIED;
- Date added = trustedKey.has("addedTimestamp") ? new Date(trustedKey.get("addedTimestamp").asLong()) : new Date();
+ TrustLevel trustLevel = trustedKey.has("trustLevel") ? TrustLevel.fromInt(trustedKey.get(
+ "trustLevel").asInt()) : TrustLevel.TRUSTED_UNVERIFIED;
+ Date added = trustedKey.has("addedTimestamp") ? new Date(trustedKey.get("addedTimestamp")
+ .asLong()) : new Date();
keyStore.saveIdentity(serviceAddress, id, trustLevel, added);
} catch (InvalidKeyException | IOException e) {
System.out.println(String.format("Error while decoding key for: %s", trustedKeyName));
public static class JsonIdentityKeyStoreSerializer extends JsonSerializer<JsonIdentityKeyStore> {
@Override
- public void serialize(JsonIdentityKeyStore jsonIdentityKeyStore, JsonGenerator json, SerializerProvider serializerProvider) throws IOException {
+ public void serialize(
+ JsonIdentityKeyStore jsonIdentityKeyStore, JsonGenerator json, SerializerProvider serializerProvider
+ ) throws IOException {
json.writeStartObject();
json.writeNumberField("registrationId", jsonIdentityKeyStore.getLocalRegistrationId());
- json.writeStringField("identityKey", Base64.encodeBytes(jsonIdentityKeyStore.getIdentityKeyPair().serialize()));
+ json.writeStringField("identityKey",
+ Base64.encodeBytes(jsonIdentityKeyStore.getIdentityKeyPair().serialize()));
json.writeArrayFieldStart("trustedKeys");
for (Identity trustedKey : jsonIdentityKeyStore.identities) {
json.writeStartObject();
}
boolean isTrusted() {
- return trustLevel == TrustLevel.TRUSTED_UNVERIFIED ||
- trustLevel == TrustLevel.TRUSTED_VERIFIED;
+ return trustLevel == TrustLevel.TRUSTED_UNVERIFIED || trustLevel == TrustLevel.TRUSTED_VERIFIED;
}
public IdentityKey getIdentityKey() {
public static class JsonPreKeyStoreDeserializer extends JsonDeserializer<JsonPreKeyStore> {
@Override
- public JsonPreKeyStore deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
+ public JsonPreKeyStore deserialize(
+ JsonParser jsonParser, DeserializationContext deserializationContext
+ ) throws IOException {
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
Map<Integer, byte[]> preKeyMap = new HashMap<>();
public static class JsonPreKeyStoreSerializer extends JsonSerializer<JsonPreKeyStore> {
@Override
- public void serialize(JsonPreKeyStore jsonPreKeyStore, JsonGenerator json, SerializerProvider serializerProvider) throws IOException {
+ public void serialize(
+ JsonPreKeyStore jsonPreKeyStore, JsonGenerator json, SerializerProvider serializerProvider
+ ) throws IOException {
json.writeStartArray();
for (Map.Entry<Integer, byte[]> preKey : jsonPreKeyStore.store.entrySet()) {
json.writeStartObject();
public static class JsonSessionStoreDeserializer extends JsonDeserializer<JsonSessionStore> {
@Override
- public JsonSessionStore deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
+ public JsonSessionStore deserialize(
+ JsonParser jsonParser, DeserializationContext deserializationContext
+ ) throws IOException {
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
JsonSessionStore sessionStore = new JsonSessionStore();
if (node.isArray()) {
for (JsonNode session : node) {
- String sessionName = session.hasNonNull("name")
- ? session.get("name").asText()
- : null;
+ String sessionName = session.hasNonNull("name") ? session.get("name").asText() : null;
if (UuidUtil.isUuid(sessionName)) {
// Ignore sessions that were incorrectly created with UUIDs as name
continue;
}
- UUID uuid = session.hasNonNull("uuid")
- ? UuidUtil.parseOrNull(session.get("uuid").asText())
- : null;
+ UUID uuid = session.hasNonNull("uuid") ? UuidUtil.parseOrNull(session.get("uuid").asText()) : null;
final SignalServiceAddress serviceAddress = uuid == null
? Util.getSignalServiceAddressFromIdentifier(sessionName)
: new SignalServiceAddress(uuid, sessionName);
public static class JsonSessionStoreSerializer extends JsonSerializer<JsonSessionStore> {
@Override
- public void serialize(JsonSessionStore jsonSessionStore, JsonGenerator json, SerializerProvider serializerProvider) throws IOException {
+ public void serialize(
+ JsonSessionStore jsonSessionStore, JsonGenerator json, SerializerProvider serializerProvider
+ ) throws IOException {
json.writeStartArray();
for (SessionInfo sessionInfo : jsonSessionStore.sessions) {
json.writeStartObject();
public JsonSignalProtocolStore() {
}
- public JsonSignalProtocolStore(JsonPreKeyStore preKeyStore, JsonSessionStore sessionStore, JsonSignedPreKeyStore signedPreKeyStore, JsonIdentityKeyStore identityKeyStore) {
+ public JsonSignalProtocolStore(
+ JsonPreKeyStore preKeyStore,
+ JsonSessionStore sessionStore,
+ JsonSignedPreKeyStore signedPreKeyStore,
+ JsonIdentityKeyStore identityKeyStore
+ ) {
this.preKeyStore = preKeyStore;
this.sessionStore = sessionStore;
this.signedPreKeyStore = signedPreKeyStore;
identityKeyStore.saveIdentity(serviceAddress, identityKey, trustLevel, null);
}
- public void setIdentityTrustLevel(SignalServiceAddress serviceAddress, IdentityKey identityKey, TrustLevel trustLevel) {
+ public void setIdentityTrustLevel(
+ SignalServiceAddress serviceAddress, IdentityKey identityKey, TrustLevel trustLevel
+ ) {
identityKeyStore.setIdentityTrustLevel(serviceAddress, identityKey, trustLevel);
}
public static class JsonSignedPreKeyStoreDeserializer extends JsonDeserializer<JsonSignedPreKeyStore> {
@Override
- public JsonSignedPreKeyStore deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
+ public JsonSignedPreKeyStore deserialize(
+ JsonParser jsonParser, DeserializationContext deserializationContext
+ ) throws IOException {
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
Map<Integer, byte[]> preKeyMap = new HashMap<>();
public static class JsonSignedPreKeyStoreSerializer extends JsonSerializer<JsonSignedPreKeyStore> {
@Override
- public void serialize(JsonSignedPreKeyStore jsonPreKeyStore, JsonGenerator json, SerializerProvider serializerProvider) throws IOException {
+ public void serialize(
+ JsonSignedPreKeyStore jsonPreKeyStore, JsonGenerator json, SerializerProvider serializerProvider
+ ) throws IOException {
json.writeStartArray();
for (Map.Entry<Integer, byte[]> signedPreKey : jsonPreKeyStore.store.entrySet()) {
json.writeStartObject();
public static class RecipientStoreDeserializer extends JsonDeserializer<Set<SignalServiceAddress>> {
@Override
- public Set<SignalServiceAddress> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
+ public Set<SignalServiceAddress> deserialize(
+ JsonParser jsonParser, DeserializationContext deserializationContext
+ ) throws IOException {
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
Set<SignalServiceAddress> addresses = new HashSet<>();
public static class RecipientStoreSerializer extends JsonSerializer<Set<SignalServiceAddress>> {
@Override
- public void serialize(Set<SignalServiceAddress> addresses, JsonGenerator json, SerializerProvider serializerProvider) throws IOException {
+ public void serialize(
+ Set<SignalServiceAddress> addresses, JsonGenerator json, SerializerProvider serializerProvider
+ ) throws IOException {
json.writeStartArray();
for (SignalServiceAddress address : addresses) {
json.writeStartObject();
private static class StickersSerializer extends JsonSerializer<Map<byte[], Sticker>> {
@Override
- public void serialize(final Map<byte[], Sticker> value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException {
+ public void serialize(
+ final Map<byte[], Sticker> value, final JsonGenerator jgen, final SerializerProvider provider
+ ) throws IOException {
final Collection<Sticker> stickers = value.values();
jgen.writeStartArray(stickers.size());
for (Sticker sticker : stickers) {
private static class StickersDeserializer extends JsonDeserializer<Map<byte[], Sticker>> {
@Override
- public Map<byte[], Sticker> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
+ public Map<byte[], Sticker> deserialize(
+ JsonParser jsonParser, DeserializationContext deserializationContext
+ ) throws IOException {
Map<byte[], Sticker> stickers = new HashMap<>();
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
for (JsonNode n : node) {
private static class MapToListSerializer extends JsonSerializer<Map<?, ?>> {
@Override
- public void serialize(final Map<?, ?> value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException {
+ public void serialize(
+ final Map<?, ?> value, final JsonGenerator jgen, final SerializerProvider provider
+ ) throws IOException {
jgen.writeObject(value.values());
}
}
private static class ThreadsDeserializer extends JsonDeserializer<Map<String, ThreadInfo>> {
@Override
- public Map<String, ThreadInfo> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
+ public Map<String, ThreadInfo> deserialize(
+ JsonParser jsonParser, DeserializationContext deserializationContext
+ ) throws IOException {
Map<String, ThreadInfo> threads = new HashMap<>();
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
for (JsonNode n : node) {
public static void handleAssertionError(AssertionError e) {
System.err.println("Failed to send/receive message (Assertion): " + e.getMessage());
e.printStackTrace();
- System.err.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
+ System.err.println(
+ "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 class Hex {
- private final static char[] HEX_DIGITS = {
- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
- };
+ private final static char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
private Hex() {
}
// Workaround for BKS truststore
put("KeyStore.BKS", org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi.Std.class.getCanonicalName());
- put("KeyStore.BKS-V1", org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi.Version1.class.getCanonicalName());
- put("KeyStore.BouncyCastle", org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi.BouncyCastleStore.class.getCanonicalName());
+ put("KeyStore.BKS-V1",
+ org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi.Version1.class.getCanonicalName());
+ put("KeyStore.BouncyCastle",
+ org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi.BouncyCastleStore.class.getCanonicalName());
put("KeyFactory.X.509", org.bouncycastle.jcajce.provider.asymmetric.x509.KeyFactory.class.getCanonicalName());
- put("CertificateFactory.X.509", org.bouncycastle.jcajce.provider.asymmetric.x509.CertificateFactory.class.getCanonicalName());
+ put("CertificateFactory.X.509",
+ org.bouncycastle.jcajce.provider.asymmetric.x509.CertificateFactory.class.getCanonicalName());
}
public static class DefaultRandom extends SecureRandomSpi {
public static JsonNode getNotNullNode(JsonNode parent, String name) throws InvalidObjectException {
JsonNode node = parent.get(name);
if (node == null) {
- throw new InvalidObjectException(String.format("Incorrect file format: expected parameter %s not found ", name));
+ throw new InvalidObjectException(String.format("Incorrect file format: expected parameter %s not found ",
+ name));
}
return node;