Use var instead of explicit types

This commit is contained in:
AsamK 2021-02-21 15:01:41 +01:00
parent 03c30519b1
commit de273586b4
77 changed files with 850 additions and 1017 deletions

View file

@ -29,7 +29,7 @@ public class AvatarStore {
}
public StreamDetails retrieveGroupAvatar(GroupId groupId) throws IOException {
final File groupAvatarFile = getGroupAvatarFile(groupId);
final var groupAvatarFile = getGroupAvatarFile(groupId);
return retrieveAvatar(groupAvatarFile);
}

View file

@ -20,14 +20,14 @@ public class DeviceLinkInfo {
final ECPublicKey deviceKey;
public static DeviceLinkInfo parseDeviceLinkUri(URI linkUri) throws InvalidKeyException {
final String rawQuery = linkUri.getRawQuery();
final var rawQuery = linkUri.getRawQuery();
if (isEmpty(rawQuery)) {
throw new RuntimeException("Invalid device link uri");
}
Map<String, String> query = getQueryMap(rawQuery);
String deviceIdentifier = query.get("uuid");
String publicKeyEncoded = query.get("pub_key");
var query = getQueryMap(rawQuery);
var deviceIdentifier = query.get("uuid");
var publicKeyEncoded = query.get("pub_key");
if (isEmpty(deviceIdentifier) || isEmpty(publicKeyEncoded)) {
throw new RuntimeException("Invalid device link uri");
@ -39,18 +39,18 @@ public class DeviceLinkInfo {
} catch (IllegalArgumentException e) {
throw new RuntimeException("Invalid device link uri", e);
}
ECPublicKey deviceKey = Curve.decodePoint(publicKeyBytes, 0);
var deviceKey = Curve.decodePoint(publicKeyBytes, 0);
return new DeviceLinkInfo(deviceIdentifier, deviceKey);
}
private static Map<String, String> getQueryMap(String query) {
String[] params = query.split("&");
Map<String, String> map = new HashMap<>();
for (String param : params) {
final String[] paramParts = param.split("=");
String name = URLDecoder.decode(paramParts[0], StandardCharsets.UTF_8);
String value = URLDecoder.decode(paramParts[1], StandardCharsets.UTF_8);
var params = query.split("&");
var map = new HashMap<String, String>();
for (var param : params) {
final var paramParts = param.split("=");
var name = URLDecoder.decode(paramParts[0], StandardCharsets.UTF_8);
var value = URLDecoder.decode(paramParts[1], StandardCharsets.UTF_8);
map.put(name, value);
}
return map;
@ -62,7 +62,7 @@ public class DeviceLinkInfo {
}
public String createDeviceLinkUri() {
final String deviceKeyString = Base64.getEncoder().encodeToString(deviceKey.serialize()).replace("=", "");
final var deviceKeyString = Base64.getEncoder().encodeToString(deviceKey.serialize()).replace("=", "");
return "tsdevice:/?uuid="
+ URLEncoder.encode(deviceIdentifier, StandardCharsets.UTF_8)
+ "&pub_key="

View file

@ -29,7 +29,7 @@ class SendReceiptAction implements HandleAction {
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final SendReceiptAction that = (SendReceiptAction) o;
final var that = (SendReceiptAction) o;
return timestamp == that.timestamp && address.equals(that.address);
}
@ -110,7 +110,7 @@ class SendGroupInfoRequestAction implements HandleAction {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final SendGroupInfoRequestAction that = (SendGroupInfoRequestAction) o;
final var that = (SendGroupInfoRequestAction) o;
if (!address.equals(that.address)) return false;
return groupId.equals(that.groupId);
@ -118,7 +118,7 @@ class SendGroupInfoRequestAction implements HandleAction {
@Override
public int hashCode() {
int result = address.hashCode();
var result = address.hashCode();
result = 31 * result + groupId.hashCode();
return result;
}
@ -144,7 +144,7 @@ class SendGroupInfoAction implements HandleAction {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final SendGroupInfoAction that = (SendGroupInfoAction) o;
final var that = (SendGroupInfoAction) o;
if (!address.equals(that.address)) return false;
return groupId.equals(that.groupId);
@ -152,7 +152,7 @@ class SendGroupInfoAction implements HandleAction {
@Override
public int hashCode() {
int result = address.hashCode();
var result = address.hashCode();
result = 31 * result + groupId.hashCode();
return result;
}

View file

@ -18,7 +18,7 @@ public class LibSignalLogger implements SignalProtocolLogger {
@Override
public void log(final int priority, final String tag, final String message) {
final String logMessage = String.format("[%s]: %s", tag, message);
final var logMessage = String.format("[%s]: %s", tag, message);
switch (priority) {
case SignalProtocolLogger.VERBOSE:
logger.trace(logMessage);

File diff suppressed because it is too large Load diff

View file

@ -79,37 +79,30 @@ public class ProvisioningManager {
public static ProvisioningManager init(
File settingsPath, ServiceEnvironment serviceEnvironment, String userAgent
) {
PathConfig pathConfig = PathConfig.createDefault(settingsPath);
var pathConfig = PathConfig.createDefault(settingsPath);
final ServiceEnvironmentConfig serviceConfiguration = ServiceConfig.getServiceEnvironmentConfig(
serviceEnvironment,
userAgent);
final var serviceConfiguration = ServiceConfig.getServiceEnvironmentConfig(serviceEnvironment, userAgent);
return new ProvisioningManager(pathConfig, serviceConfiguration, userAgent);
}
public String getDeviceLinkUri() throws TimeoutException, IOException {
String deviceUuid = accountManager.getNewDeviceUuid();
var deviceUuid = accountManager.getNewDeviceUuid();
return new DeviceLinkInfo(deviceUuid, identityKey.getPublicKey().getPublicKey()).createDeviceLinkUri();
}
public String finishDeviceLink(String deviceName) throws IOException, InvalidKeyException, TimeoutException, UserAlreadyExists {
SignalServiceAccountManager.NewDeviceRegistrationReturn ret = accountManager.finishNewDeviceRegistration(
identityKey,
false,
true,
registrationId,
deviceName);
var ret = accountManager.finishNewDeviceRegistration(identityKey, false, true, registrationId, deviceName);
String username = ret.getNumber();
var username = ret.getNumber();
// TODO do this check before actually registering
if (SignalAccount.userExists(pathConfig.getDataPath(), username)) {
throw new UserAlreadyExists(username, SignalAccount.getFileName(pathConfig.getDataPath(), username));
}
// Create new account with the synced identity
byte[] profileKeyBytes = ret.getProfileKey();
var profileKeyBytes = ret.getProfileKey();
ProfileKey profileKey;
if (profileKeyBytes == null) {
profileKey = KeyUtils.createProfileKey();
@ -121,7 +114,7 @@ public class ProvisioningManager {
}
}
try (SignalAccount account = SignalAccount.createLinkedAccount(pathConfig.getDataPath(),
try (var account = SignalAccount.createLinkedAccount(pathConfig.getDataPath(),
username,
ret.getUuid(),
password,
@ -131,7 +124,7 @@ public class ProvisioningManager {
profileKey)) {
account.save();
try (Manager m = new Manager(account, pathConfig, serviceEnvironmentConfig, userAgent)) {
try (var m = new Manager(account, pathConfig, serviceEnvironmentConfig, userAgent)) {
try {
m.refreshPreKeys();

View file

@ -22,12 +22,8 @@ import org.asamk.signal.manager.config.ServiceEnvironmentConfig;
import org.asamk.signal.manager.helper.PinHelper;
import org.asamk.signal.manager.storage.SignalAccount;
import org.asamk.signal.manager.util.KeyUtils;
import org.signal.zkgroup.profiles.ProfileKey;
import org.whispersystems.libsignal.IdentityKeyPair;
import org.whispersystems.libsignal.util.KeyHelper;
import org.whispersystems.libsignal.util.guava.Optional;
import org.whispersystems.signalservice.api.KbsPinData;
import org.whispersystems.signalservice.api.KeyBackupService;
import org.whispersystems.signalservice.api.KeyBackupServicePinException;
import org.whispersystems.signalservice.api.KeyBackupSystemNoDataException;
import org.whispersystems.signalservice.api.SignalServiceAccountManager;
@ -82,7 +78,7 @@ public class RegistrationManager implements Closeable {
groupsV2Operations,
ServiceConfig.AUTOMATIC_NETWORK_RETRY,
timer);
final KeyBackupService keyBackupService = accountManager.getKeyBackupService(ServiceConfig.getIasKeyStore(),
final var keyBackupService = accountManager.getKeyBackupService(ServiceConfig.getIasKeyStore(),
serviceEnvironmentConfig.getKeyBackupConfig().getEnclaveName(),
serviceEnvironmentConfig.getKeyBackupConfig().getServiceId(),
serviceEnvironmentConfig.getKeyBackupConfig().getMrenclave(),
@ -93,17 +89,15 @@ public class RegistrationManager implements Closeable {
public static RegistrationManager init(
String username, File settingsPath, ServiceEnvironment serviceEnvironment, String userAgent
) throws IOException {
PathConfig pathConfig = PathConfig.createDefault(settingsPath);
var pathConfig = PathConfig.createDefault(settingsPath);
final ServiceEnvironmentConfig serviceConfiguration = ServiceConfig.getServiceEnvironmentConfig(
serviceEnvironment,
userAgent);
final var serviceConfiguration = ServiceConfig.getServiceEnvironmentConfig(serviceEnvironment, userAgent);
if (!SignalAccount.userExists(pathConfig.getDataPath(), username)) {
IdentityKeyPair identityKey = KeyUtils.generateIdentityKeyPair();
int registrationId = KeyHelper.generateRegistrationId(false);
var identityKey = KeyUtils.generateIdentityKeyPair();
var registrationId = KeyHelper.generateRegistrationId(false);
ProfileKey profileKey = KeyUtils.createProfileKey();
SignalAccount account = SignalAccount.create(pathConfig.getDataPath(),
var profileKey = KeyUtils.createProfileKey();
var account = SignalAccount.create(pathConfig.getDataPath(),
username,
identityKey,
registrationId,
@ -113,7 +107,7 @@ public class RegistrationManager implements Closeable {
return new RegistrationManager(account, pathConfig, serviceConfiguration, userAgent);
}
SignalAccount account = SignalAccount.load(pathConfig.getDataPath(), username);
var account = SignalAccount.load(pathConfig.getDataPath(), username);
return new RegistrationManager(account, pathConfig, serviceConfiguration, userAgent);
}
@ -147,12 +141,12 @@ public class RegistrationManager implements Closeable {
throw e;
}
KbsPinData registrationLockData = pinHelper.getRegistrationLockData(pin, e);
var registrationLockData = pinHelper.getRegistrationLockData(pin, e);
if (registrationLockData == null) {
throw e;
}
String registrationLock = registrationLockData.getMasterKey().deriveRegistrationLock();
var registrationLock = registrationLockData.getMasterKey().deriveRegistrationLock();
try {
response = verifyAccountWithCode(verificationCode, null, registrationLock);
} catch (LockedException _e) {
@ -175,7 +169,7 @@ public class RegistrationManager implements Closeable {
account.getSignalProtocolStore().getIdentityKeyPair().getPublicKey(),
TrustLevel.TRUSTED_VERIFIED);
try (Manager m = new Manager(account, pathConfig, serviceEnvironmentConfig, userAgent)) {
try (var m = new Manager(account, pathConfig, serviceEnvironmentConfig, userAgent)) {
m.refreshPreKeys();

View file

@ -39,7 +39,7 @@ public class ServiceConfig {
try {
TrustStore contactTrustStore = new IasTrustStore();
KeyStore keyStore = KeyStore.getInstance("BKS");
var keyStore = KeyStore.getInstance("BKS");
keyStore.load(contactTrustStore.getKeyStoreInputStream(),
contactTrustStore.getKeyStorePassword().toCharArray());
@ -74,7 +74,7 @@ public class ServiceConfig {
.header("User-Agent", userAgent)
.build());
final List<Interceptor> interceptors = List.of(userAgentInterceptor);
final var interceptors = List.of(userAgentInterceptor);
switch (serviceEnvironment) {
case LIVE:

View file

@ -50,7 +50,7 @@ public abstract class GroupId {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final GroupId groupId = (GroupId) o;
final var groupId = (GroupId) o;
return Arrays.equals(id, groupId.id);
}

View file

@ -35,7 +35,7 @@ public final class GroupInviteLinkUrl {
* @throws InvalidGroupLinkException If group url, but cannot be parsed.
*/
public static GroupInviteLinkUrl fromUri(String urlString) throws InvalidGroupLinkException, UnknownGroupLinkVersionException {
URI uri = getGroupUrl(urlString);
var uri = getGroupUrl(urlString);
if (uri == null) {
return null;
@ -46,21 +46,21 @@ public final class GroupInviteLinkUrl {
throw new InvalidGroupLinkException("No path was expected in uri");
}
String encoding = uri.getFragment();
var encoding = uri.getFragment();
if (encoding == null || encoding.length() == 0) {
throw new InvalidGroupLinkException("No reference was in the uri");
}
byte[] bytes = Base64UrlSafe.decodePaddingAgnostic(encoding);
GroupInviteLink groupInviteLink = GroupInviteLink.parseFrom(bytes);
var bytes = Base64UrlSafe.decodePaddingAgnostic(encoding);
var groupInviteLink = GroupInviteLink.parseFrom(bytes);
switch (groupInviteLink.getContentsCase()) {
case V1CONTENTS: {
GroupInviteLink.GroupInviteLinkContentsV1 groupInviteLinkContentsV1 = groupInviteLink.getV1Contents();
GroupMasterKey groupMasterKey = new GroupMasterKey(groupInviteLinkContentsV1.getGroupMasterKey()
var groupInviteLinkContentsV1 = groupInviteLink.getV1Contents();
var groupMasterKey = new GroupMasterKey(groupInviteLinkContentsV1.getGroupMasterKey()
.toByteArray());
GroupLinkPassword password = GroupLinkPassword.fromBytes(groupInviteLinkContentsV1.getInviteLinkPassword()
var password = GroupLinkPassword.fromBytes(groupInviteLinkContentsV1.getInviteLinkPassword()
.toByteArray());
return new GroupInviteLinkUrl(groupMasterKey, password);
@ -78,7 +78,7 @@ public final class GroupInviteLinkUrl {
*/
private static URI getGroupUrl(String urlString) {
try {
URI url = new URI(urlString);
var url = new URI(urlString);
if (!"https".equalsIgnoreCase(url.getScheme()) && !"sgnl".equalsIgnoreCase(url.getScheme())) {
return null;
@ -97,13 +97,13 @@ public final class GroupInviteLinkUrl {
}
protected static String createUrl(GroupMasterKey groupMasterKey, GroupLinkPassword password) {
GroupInviteLink groupInviteLink = GroupInviteLink.newBuilder()
var groupInviteLink = GroupInviteLink.newBuilder()
.setV1Contents(GroupInviteLink.GroupInviteLinkContentsV1.newBuilder()
.setGroupMasterKey(ByteString.copyFrom(groupMasterKey.serialize()))
.setInviteLinkPassword(ByteString.copyFrom(password.serialize())))
.build();
String encoding = Base64UrlSafe.encodeBytesWithoutPadding(groupInviteLink.toByteArray());
var encoding = Base64UrlSafe.encodeBytesWithoutPadding(groupInviteLink.toByteArray());
return GROUP_URL_PREFIX + encoding;
}

View file

@ -18,13 +18,13 @@ public class GroupUtils {
final SignalServiceDataMessage.Builder messageBuilder, final GroupInfo groupInfo
) {
if (groupInfo instanceof GroupInfoV1) {
SignalServiceGroup group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.DELIVER)
var group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.DELIVER)
.withId(groupInfo.getGroupId().serialize())
.build();
messageBuilder.asGroupMessage(group);
} else {
final GroupInfoV2 groupInfoV2 = (GroupInfoV2) groupInfo;
SignalServiceGroupV2 group = SignalServiceGroupV2.newBuilder(groupInfoV2.getMasterKey())
final var groupInfoV2 = (GroupInfoV2) groupInfo;
var group = SignalServiceGroupV2.newBuilder(groupInfoV2.getMasterKey())
.withRevision(groupInfoV2.getGroup() == null ? 0 : groupInfoV2.getGroup().getRevision())
.build();
messageBuilder.asGroupMessage(group);
@ -46,13 +46,12 @@ public class GroupUtils {
}
public static GroupIdV2 getGroupIdV2(GroupMasterKey groupMasterKey) {
final GroupSecretParams groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupMasterKey);
final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupMasterKey);
return getGroupIdV2(groupSecretParams);
}
public static GroupIdV2 getGroupIdV2(GroupIdV1 groupIdV1) {
final GroupSecretParams groupSecretParams = GroupSecretParams.deriveFromMasterKey(deriveV2MigrationMasterKey(
groupIdV1));
final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(deriveV2MigrationMasterKey(groupIdV1));
return getGroupIdV2(groupSecretParams);
}

View file

@ -2,7 +2,6 @@ package org.asamk.signal.manager.helper;
import com.google.protobuf.InvalidProtocolBufferException;
import org.asamk.signal.manager.groups.GroupIdV2;
import org.asamk.signal.manager.groups.GroupLinkPassword;
import org.asamk.signal.manager.groups.GroupUtils;
import org.asamk.signal.manager.storage.groups.GroupInfoV2;
@ -20,7 +19,6 @@ import org.signal.zkgroup.VerificationFailedException;
import org.signal.zkgroup.groups.GroupMasterKey;
import org.signal.zkgroup.groups.GroupSecretParams;
import org.signal.zkgroup.groups.UuidCiphertext;
import org.signal.zkgroup.profiles.ProfileKeyCredential;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.libsignal.util.Pair;
@ -41,7 +39,6 @@ import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
@ -80,7 +77,7 @@ public class GroupHelper {
public DecryptedGroup getDecryptedGroup(final GroupSecretParams groupSecretParams) {
try {
final GroupsV2AuthorizationString groupsV2AuthorizationString = groupAuthorizationProvider.getAuthorizationForToday(
final var groupsV2AuthorizationString = groupAuthorizationProvider.getAuthorizationForToday(
groupSecretParams);
return groupsV2Api.getGroup(groupSecretParams, groupsV2AuthorizationString);
} catch (IOException | VerificationFailedException | InvalidGroupStateException e) {
@ -92,7 +89,7 @@ public class GroupHelper {
public DecryptedGroupJoinInfo getDecryptedGroupJoinInfo(
GroupMasterKey groupMasterKey, GroupLinkPassword password
) throws IOException, GroupLinkNotActiveException {
GroupSecretParams groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupMasterKey);
var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupMasterKey);
return groupsV2Api.getGroupJoinInfo(groupSecretParams,
Optional.fromNullable(password).transform(GroupLinkPassword::serialize),
@ -102,13 +99,13 @@ public class GroupHelper {
public GroupInfoV2 createGroupV2(
String name, Collection<SignalServiceAddress> members, File avatarFile
) throws IOException {
final byte[] avatarBytes = readAvatarBytes(avatarFile);
final GroupsV2Operations.NewGroup newGroup = buildNewGroupV2(name, members, avatarBytes);
final var avatarBytes = readAvatarBytes(avatarFile);
final var newGroup = buildNewGroupV2(name, members, avatarBytes);
if (newGroup == null) {
return null;
}
final GroupSecretParams groupSecretParams = newGroup.getGroupSecretParams();
final var groupSecretParams = newGroup.getGroupSecretParams();
final GroupsV2AuthorizationString groupAuthForToday;
final DecryptedGroup decryptedGroup;
@ -125,9 +122,9 @@ public class GroupHelper {
return null;
}
final GroupIdV2 groupId = GroupUtils.getGroupIdV2(groupSecretParams);
final GroupMasterKey masterKey = groupSecretParams.getMasterKey();
GroupInfoV2 g = new GroupInfoV2(groupId, masterKey);
final var groupId = GroupUtils.getGroupIdV2(groupSecretParams);
final var masterKey = groupSecretParams.getMasterKey();
var g = new GroupInfoV2(groupId, masterKey);
g.setGroup(decryptedGroup);
return g;
@ -144,8 +141,7 @@ public class GroupHelper {
private GroupsV2Operations.NewGroup buildNewGroupV2(
String name, Collection<SignalServiceAddress> members, byte[] avatar
) {
final ProfileKeyCredential profileKeyCredential = profileKeyCredentialProvider.getProfileKeyCredential(
selfAddressProvider.getSelfAddress());
final var profileKeyCredential = profileKeyCredentialProvider.getProfileKeyCredential(selfAddressProvider.getSelfAddress());
if (profileKeyCredential == null) {
logger.warn("Cannot create a V2 group as self does not have a versioned profile");
return null;
@ -153,14 +149,14 @@ public class GroupHelper {
if (!areMembersValid(members)) return null;
GroupCandidate self = new GroupCandidate(selfAddressProvider.getSelfAddress().getUuid().orNull(),
var self = new GroupCandidate(selfAddressProvider.getSelfAddress().getUuid().orNull(),
Optional.fromNullable(profileKeyCredential));
Set<GroupCandidate> candidates = members.stream()
var candidates = members.stream()
.map(member -> new GroupCandidate(member.getUuid().get(),
Optional.fromNullable(profileKeyCredentialProvider.getProfileKeyCredential(member))))
.collect(Collectors.toSet());
final GroupSecretParams groupSecretParams = GroupSecretParams.generate();
final var groupSecretParams = GroupSecretParams.generate();
return groupsV2Operations.createNewGroup(groupSecretParams,
name,
Optional.fromNullable(avatar),
@ -171,7 +167,7 @@ public class GroupHelper {
}
private boolean areMembersValid(final Collection<SignalServiceAddress> members) {
final Set<String> noUuidCapability = members.stream()
final var noUuidCapability = members.stream()
.filter(address -> !address.getUuid().isPresent())
.map(SignalServiceAddress::getLegacyIdentifier)
.collect(Collectors.toSet());
@ -181,7 +177,7 @@ public class GroupHelper {
return false;
}
final Set<SignalProfile> noGv2Capability = members.stream()
final var noGv2Capability = members.stream()
.map(profileProvider::getProfile)
.filter(profile -> profile != null && !profile.getCapabilities().gv2)
.collect(Collectors.toSet());
@ -197,22 +193,20 @@ public class GroupHelper {
public Pair<DecryptedGroup, GroupChange> updateGroupV2(
GroupInfoV2 groupInfoV2, String name, File avatarFile
) throws IOException {
final GroupSecretParams groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupInfoV2.getMasterKey());
GroupsV2Operations.GroupOperations groupOperations = groupsV2Operations.forGroup(groupSecretParams);
final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupInfoV2.getMasterKey());
var groupOperations = groupsV2Operations.forGroup(groupSecretParams);
GroupChange.Actions.Builder change = name != null
? groupOperations.createModifyGroupTitle(name)
: GroupChange.Actions.newBuilder();
var change = name != null ? groupOperations.createModifyGroupTitle(name) : GroupChange.Actions.newBuilder();
if (avatarFile != null) {
final byte[] avatarBytes = readAvatarBytes(avatarFile);
String avatarCdnKey = groupsV2Api.uploadAvatar(avatarBytes,
final var avatarBytes = readAvatarBytes(avatarFile);
var avatarCdnKey = groupsV2Api.uploadAvatar(avatarBytes,
groupSecretParams,
groupAuthorizationProvider.getAuthorizationForToday(groupSecretParams));
change.setModifyAvatar(GroupChange.Actions.ModifyAvatarAction.newBuilder().setAvatar(avatarCdnKey));
}
final Optional<UUID> uuid = this.selfAddressProvider.getSelfAddress().getUuid();
final var uuid = this.selfAddressProvider.getSelfAddress().getUuid();
if (uuid.isPresent()) {
change.setSourceUuid(UuidUtil.toByteString(uuid.get()));
}
@ -223,22 +217,22 @@ public class GroupHelper {
public Pair<DecryptedGroup, GroupChange> updateGroupV2(
GroupInfoV2 groupInfoV2, Set<SignalServiceAddress> newMembers
) throws IOException {
final GroupSecretParams groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupInfoV2.getMasterKey());
GroupsV2Operations.GroupOperations groupOperations = groupsV2Operations.forGroup(groupSecretParams);
final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupInfoV2.getMasterKey());
var groupOperations = groupsV2Operations.forGroup(groupSecretParams);
if (!areMembersValid(newMembers)) {
throw new IOException("Failed to update group");
}
Set<GroupCandidate> candidates = newMembers.stream()
var candidates = newMembers.stream()
.map(member -> new GroupCandidate(member.getUuid().get(),
Optional.fromNullable(profileKeyCredentialProvider.getProfileKeyCredential(member))))
.collect(Collectors.toSet());
final GroupChange.Actions.Builder change = groupOperations.createModifyGroupMembershipChange(candidates,
final var change = groupOperations.createModifyGroupMembershipChange(candidates,
selfAddressProvider.getSelfAddress().getUuid().get());
final Optional<UUID> uuid = this.selfAddressProvider.getSelfAddress().getUuid();
final var uuid = this.selfAddressProvider.getSelfAddress().getUuid();
if (uuid.isPresent()) {
change.setSourceUuid(UuidUtil.toByteString(uuid.get()));
}
@ -247,10 +241,9 @@ public class GroupHelper {
}
public Pair<DecryptedGroup, GroupChange> leaveGroup(GroupInfoV2 groupInfoV2) throws IOException {
List<DecryptedPendingMember> pendingMembersList = groupInfoV2.getGroup().getPendingMembersList();
final UUID selfUuid = selfAddressProvider.getSelfAddress().getUuid().get();
Optional<DecryptedPendingMember> selfPendingMember = DecryptedGroupUtil.findPendingByUuid(pendingMembersList,
selfUuid);
var pendingMembersList = groupInfoV2.getGroup().getPendingMembersList();
final var selfUuid = selfAddressProvider.getSelfAddress().getUuid().get();
var selfPendingMember = DecryptedGroupUtil.findPendingByUuid(pendingMembersList, selfUuid);
if (selfPendingMember.isPresent()) {
return revokeInvites(groupInfoV2, Set.of(selfPendingMember.get()));
@ -264,19 +257,17 @@ public class GroupHelper {
GroupLinkPassword groupLinkPassword,
DecryptedGroupJoinInfo decryptedGroupJoinInfo
) throws IOException {
final GroupSecretParams groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupMasterKey);
final GroupsV2Operations.GroupOperations groupOperations = groupsV2Operations.forGroup(groupSecretParams);
final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupMasterKey);
final var groupOperations = groupsV2Operations.forGroup(groupSecretParams);
final SignalServiceAddress selfAddress = this.selfAddressProvider.getSelfAddress();
final ProfileKeyCredential profileKeyCredential = profileKeyCredentialProvider.getProfileKeyCredential(
selfAddress);
final var selfAddress = this.selfAddressProvider.getSelfAddress();
final var profileKeyCredential = profileKeyCredentialProvider.getProfileKeyCredential(selfAddress);
if (profileKeyCredential == null) {
throw new IOException("Cannot join a V2 group as self does not have a versioned profile");
}
boolean requestToJoin = decryptedGroupJoinInfo.getAddFromInviteLink()
== AccessControl.AccessRequired.ADMINISTRATOR;
GroupChange.Actions.Builder change = requestToJoin
var requestToJoin = decryptedGroupJoinInfo.getAddFromInviteLink() == AccessControl.AccessRequired.ADMINISTRATOR;
var change = requestToJoin
? groupOperations.createGroupJoinRequest(profileKeyCredential)
: groupOperations.createGroupJoinDirect(profileKeyCredential);
@ -286,19 +277,18 @@ public class GroupHelper {
}
public Pair<DecryptedGroup, GroupChange> acceptInvite(GroupInfoV2 groupInfoV2) throws IOException {
final GroupSecretParams groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupInfoV2.getMasterKey());
final GroupsV2Operations.GroupOperations groupOperations = groupsV2Operations.forGroup(groupSecretParams);
final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupInfoV2.getMasterKey());
final var groupOperations = groupsV2Operations.forGroup(groupSecretParams);
final SignalServiceAddress selfAddress = this.selfAddressProvider.getSelfAddress();
final ProfileKeyCredential profileKeyCredential = profileKeyCredentialProvider.getProfileKeyCredential(
selfAddress);
final var selfAddress = this.selfAddressProvider.getSelfAddress();
final var profileKeyCredential = profileKeyCredentialProvider.getProfileKeyCredential(selfAddress);
if (profileKeyCredential == null) {
throw new IOException("Cannot join a V2 group as self does not have a versioned profile");
}
final GroupChange.Actions.Builder change = groupOperations.createAcceptInviteChange(profileKeyCredential);
final var change = groupOperations.createAcceptInviteChange(profileKeyCredential);
final Optional<UUID> uuid = selfAddress.getUuid();
final var uuid = selfAddress.getUuid();
if (uuid.isPresent()) {
change.setSourceUuid(UuidUtil.toByteString(uuid.get()));
}
@ -309,9 +299,9 @@ public class GroupHelper {
public Pair<DecryptedGroup, GroupChange> revokeInvites(
GroupInfoV2 groupInfoV2, Set<DecryptedPendingMember> pendingMembers
) throws IOException {
final GroupSecretParams groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupInfoV2.getMasterKey());
final GroupsV2Operations.GroupOperations groupOperations = groupsV2Operations.forGroup(groupSecretParams);
final Set<UuidCiphertext> uuidCipherTexts = pendingMembers.stream().map(member -> {
final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupInfoV2.getMasterKey());
final var groupOperations = groupsV2Operations.forGroup(groupSecretParams);
final var uuidCipherTexts = pendingMembers.stream().map(member -> {
try {
return new UuidCiphertext(member.getUuidCipherText().toByteArray());
} catch (InvalidInputException e) {
@ -322,19 +312,19 @@ public class GroupHelper {
}
public Pair<DecryptedGroup, GroupChange> ejectMembers(GroupInfoV2 groupInfoV2, Set<UUID> uuids) throws IOException {
final GroupSecretParams groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupInfoV2.getMasterKey());
final GroupsV2Operations.GroupOperations groupOperations = groupsV2Operations.forGroup(groupSecretParams);
final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupInfoV2.getMasterKey());
final var groupOperations = groupsV2Operations.forGroup(groupSecretParams);
return commitChange(groupInfoV2, groupOperations.createRemoveMembersChange(uuids));
}
private Pair<DecryptedGroup, GroupChange> commitChange(
GroupInfoV2 groupInfoV2, GroupChange.Actions.Builder change
) throws IOException {
final GroupSecretParams groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupInfoV2.getMasterKey());
final GroupsV2Operations.GroupOperations groupOperations = groupsV2Operations.forGroup(groupSecretParams);
final DecryptedGroup previousGroupState = groupInfoV2.getGroup();
final int nextRevision = previousGroupState.getRevision() + 1;
final GroupChange.Actions changeActions = change.setRevision(nextRevision).build();
final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupInfoV2.getMasterKey());
final var groupOperations = groupsV2Operations.forGroup(groupSecretParams);
final var previousGroupState = groupInfoV2.getGroup();
final var nextRevision = previousGroupState.getRevision() + 1;
final var changeActions = change.setRevision(nextRevision).build();
final DecryptedGroupChange decryptedChange;
final DecryptedGroup decryptedGroupState;
@ -346,7 +336,7 @@ public class GroupHelper {
throw new IOException(e);
}
GroupChange signedGroupChange = groupsV2Api.patchGroup(changeActions,
var signedGroupChange = groupsV2Api.patchGroup(changeActions,
groupAuthorizationProvider.getAuthorizationForToday(groupSecretParams),
Optional.absent());
@ -359,8 +349,8 @@ public class GroupHelper {
GroupChange.Actions.Builder change,
GroupLinkPassword password
) throws IOException {
final int nextRevision = currentRevision + 1;
final GroupChange.Actions changeActions = change.setRevision(nextRevision).build();
final var nextRevision = currentRevision + 1;
final var changeActions = change.setRevision(nextRevision).build();
return groupsV2Api.patchGroup(changeActions,
groupAuthorizationProvider.getAuthorizationForToday(groupSecretParams),
@ -371,8 +361,7 @@ public class GroupHelper {
DecryptedGroup group, byte[] signedGroupChange, GroupMasterKey groupMasterKey
) {
try {
final DecryptedGroupChange decryptedGroupChange = getDecryptedGroupChange(signedGroupChange,
groupMasterKey);
final var decryptedGroupChange = getDecryptedGroupChange(signedGroupChange, groupMasterKey);
if (decryptedGroupChange == null) {
return null;
}
@ -384,8 +373,7 @@ public class GroupHelper {
private DecryptedGroupChange getDecryptedGroupChange(byte[] signedGroupChange, GroupMasterKey groupMasterKey) {
if (signedGroupChange != null) {
GroupsV2Operations.GroupOperations groupOperations = groupsV2Operations.forGroup(GroupSecretParams.deriveFromMasterKey(
groupMasterKey));
var groupOperations = groupsV2Operations.forGroup(GroupSecretParams.deriveFromMasterKey(groupMasterKey));
try {
return groupOperations.decryptChange(GroupChange.parseFrom(signedGroupChange), true).orNull();

View file

@ -6,7 +6,6 @@ import org.whispersystems.signalservice.api.KbsPinData;
import org.whispersystems.signalservice.api.KeyBackupService;
import org.whispersystems.signalservice.api.KeyBackupServicePinException;
import org.whispersystems.signalservice.api.KeyBackupSystemNoDataException;
import org.whispersystems.signalservice.api.kbs.HashedPin;
import org.whispersystems.signalservice.api.kbs.MasterKey;
import org.whispersystems.signalservice.internal.contacts.crypto.UnauthenticatedResponseException;
import org.whispersystems.signalservice.internal.contacts.entities.TokenResponse;
@ -25,15 +24,15 @@ public class PinHelper {
public void setRegistrationLockPin(
String pin, MasterKey masterKey
) throws IOException, UnauthenticatedResponseException {
final KeyBackupService.PinChangeSession pinChangeSession = keyBackupService.newPinChangeSession();
final HashedPin hashedPin = PinHashing.hashPin(pin, pinChangeSession);
final var pinChangeSession = keyBackupService.newPinChangeSession();
final var hashedPin = PinHashing.hashPin(pin, pinChangeSession);
pinChangeSession.setPin(hashedPin, masterKey);
pinChangeSession.enableRegistrationLock(masterKey);
}
public void removeRegistrationLockPin() throws IOException, UnauthenticatedResponseException {
final KeyBackupService.PinChangeSession pinChangeSession = keyBackupService.newPinChangeSession();
final var pinChangeSession = keyBackupService.newPinChangeSession();
pinChangeSession.disableRegistrationLock();
pinChangeSession.removePin();
}
@ -41,7 +40,7 @@ public class PinHelper {
public KbsPinData getRegistrationLockData(
String pin, LockedException e
) throws IOException, KeyBackupSystemNoDataException, KeyBackupServicePinException {
String basicStorageCredentials = e.getBasicStorageCredentials();
var basicStorageCredentials = e.getBasicStorageCredentials();
if (basicStorageCredentials == null) {
return null;
}
@ -52,12 +51,12 @@ public class PinHelper {
private KbsPinData getRegistrationLockData(
String pin, String basicStorageCredentials
) throws IOException, KeyBackupSystemNoDataException, KeyBackupServicePinException {
TokenResponse tokenResponse = keyBackupService.getToken(basicStorageCredentials);
var tokenResponse = keyBackupService.getToken(basicStorageCredentials);
if (tokenResponse == null || tokenResponse.getTries() == 0) {
throw new IOException("KBS Account locked");
}
KbsPinData registrationLockData = restoreMasterKey(pin, basicStorageCredentials, tokenResponse);
var registrationLockData = restoreMasterKey(pin, basicStorageCredentials, tokenResponse);
if (registrationLockData == null) {
throw new AssertionError("Failed to restore master key");
}
@ -73,12 +72,11 @@ public class PinHelper {
throw new AssertionError("Cannot restore KBS key, no storage credentials supplied");
}
KeyBackupService.RestoreSession session = keyBackupService.newRegistrationSession(basicStorageCredentials,
tokenResponse);
var session = keyBackupService.newRegistrationSession(basicStorageCredentials, tokenResponse);
try {
HashedPin hashedPin = PinHashing.hashPin(pin, session);
KbsPinData kbsData = session.restorePin(hashedPin);
var hashedPin = PinHashing.hashPin(pin, session);
var kbsData = session.restorePin(hashedPin);
if (kbsData == null) {
throw new AssertionError("Null not expected");
}

View file

@ -2,10 +2,7 @@ package org.asamk.signal.manager.helper;
import org.signal.zkgroup.profiles.ProfileKey;
import org.whispersystems.libsignal.util.guava.Optional;
import org.whispersystems.signalservice.api.SignalServiceMessagePipe;
import org.whispersystems.signalservice.api.SignalServiceMessageReceiver;
import org.whispersystems.signalservice.api.crypto.UnidentifiedAccess;
import org.whispersystems.signalservice.api.crypto.UnidentifiedAccessPair;
import org.whispersystems.signalservice.api.profiles.ProfileAndCredential;
import org.whispersystems.signalservice.api.profiles.SignalServiceProfile;
import org.whispersystems.signalservice.api.push.SignalServiceAddress;
@ -63,8 +60,8 @@ public final class ProfileHelper {
public ListenableFuture<ProfileAndCredential> retrieveProfile(
SignalServiceAddress address, SignalServiceProfile.RequestType requestType
) {
Optional<UnidentifiedAccess> unidentifiedAccess = getUnidentifiedAccess(address);
Optional<ProfileKey> profileKey = Optional.fromNullable(profileKeyProvider.getProfileKey(address));
var unidentifiedAccess = getUnidentifiedAccess(address);
var profileKey = Optional.fromNullable(profileKeyProvider.getProfileKey(address));
if (unidentifiedAccess.isPresent()) {
return new CascadingFuture<>(Arrays.asList(() -> getPipeRetrievalFuture(address,
@ -90,8 +87,8 @@ public final class ProfileHelper {
Optional<UnidentifiedAccess> unidentifiedAccess,
SignalServiceProfile.RequestType requestType
) throws IOException {
SignalServiceMessagePipe unidentifiedPipe = messagePipeProvider.getMessagePipe(true);
SignalServiceMessagePipe pipe = unidentifiedPipe != null && unidentifiedAccess.isPresent()
var unidentifiedPipe = messagePipeProvider.getMessagePipe(true);
var pipe = unidentifiedPipe != null && unidentifiedAccess.isPresent()
? unidentifiedPipe
: messagePipeProvider.getMessagePipe(false);
if (pipe != null) {
@ -102,8 +99,7 @@ public final class ProfileHelper {
if (!address.getNumber().isPresent()) {
throw new NotFoundException("Can't request profile without number");
}
SignalServiceAddress addressWithoutUuid = new SignalServiceAddress(Optional.absent(),
address.getNumber());
var addressWithoutUuid = new SignalServiceAddress(Optional.absent(), address.getNumber());
return pipe.getProfile(addressWithoutUuid, profileKey, unidentifiedAccess, requestType);
}
}
@ -117,7 +113,7 @@ public final class ProfileHelper {
Optional<UnidentifiedAccess> unidentifiedAccess,
SignalServiceProfile.RequestType requestType
) throws NotFoundException {
SignalServiceMessageReceiver receiver = messageReceiverProvider.getMessageReceiver();
var receiver = messageReceiverProvider.getMessageReceiver();
try {
return receiver.retrieveProfile(address, profileKey, unidentifiedAccess, requestType);
} catch (NoClassDefFoundError e) {
@ -125,13 +121,13 @@ public final class ProfileHelper {
if (!address.getNumber().isPresent()) {
throw new NotFoundException("Can't request profile without number");
}
SignalServiceAddress addressWithoutUuid = new SignalServiceAddress(Optional.absent(), address.getNumber());
var addressWithoutUuid = new SignalServiceAddress(Optional.absent(), address.getNumber());
return receiver.retrieveProfile(addressWithoutUuid, profileKey, unidentifiedAccess, requestType);
}
}
private Optional<UnidentifiedAccess> getUnidentifiedAccess(SignalServiceAddress recipient) {
Optional<UnidentifiedAccessPair> unidentifiedAccess = unidentifiedAccessProvider.getAccessFor(recipient);
var unidentifiedAccess = unidentifiedAccessProvider.getAccessFor(recipient);
if (unidentifiedAccess.isPresent()) {
return unidentifiedAccess.get().getTargetUnidentifiedAccess();

View file

@ -1,8 +1,6 @@
package org.asamk.signal.manager.helper;
import org.asamk.signal.manager.storage.profiles.SignalProfile;
import org.signal.libsignal.metadata.certificate.InvalidCertificateException;
import org.signal.zkgroup.profiles.ProfileKey;
import org.whispersystems.libsignal.util.guava.Optional;
import org.whispersystems.signalservice.api.crypto.UnidentifiedAccess;
import org.whispersystems.signalservice.api.crypto.UnidentifiedAccessPair;
@ -41,12 +39,12 @@ public class UnidentifiedAccessHelper {
}
public byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient) {
ProfileKey theirProfileKey = profileKeyProvider.getProfileKey(recipient);
var theirProfileKey = profileKeyProvider.getProfileKey(recipient);
if (theirProfileKey == null) {
return null;
}
SignalProfile targetProfile = profileProvider.getProfile(recipient);
var targetProfile = profileProvider.getProfile(recipient);
if (targetProfile == null || targetProfile.getUnidentifiedAccess() == null) {
return null;
}
@ -59,8 +57,8 @@ public class UnidentifiedAccessHelper {
}
public Optional<UnidentifiedAccessPair> getAccessForSync() {
byte[] selfUnidentifiedAccessKey = getSelfUnidentifiedAccessKey();
byte[] selfUnidentifiedAccessCertificate = senderCertificateProvider.getSenderCertificate();
var selfUnidentifiedAccessKey = getSelfUnidentifiedAccessKey();
var selfUnidentifiedAccessCertificate = senderCertificateProvider.getSenderCertificate();
if (selfUnidentifiedAccessKey == null || selfUnidentifiedAccessCertificate == null) {
return Optional.absent();
@ -80,9 +78,9 @@ public class UnidentifiedAccessHelper {
}
public Optional<UnidentifiedAccessPair> getAccessFor(SignalServiceAddress recipient) {
byte[] recipientUnidentifiedAccessKey = getTargetUnidentifiedAccessKey(recipient);
byte[] selfUnidentifiedAccessKey = getSelfUnidentifiedAccessKey();
byte[] selfUnidentifiedAccessCertificate = senderCertificateProvider.getSenderCertificate();
var recipientUnidentifiedAccessKey = getTargetUnidentifiedAccessKey(recipient);
var selfUnidentifiedAccessKey = getSelfUnidentifiedAccessKey();
var selfUnidentifiedAccessCertificate = senderCertificateProvider.getSenderCertificate();
if (recipientUnidentifiedAccessKey == null
|| selfUnidentifiedAccessKey == null

View file

@ -8,24 +8,18 @@ import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.asamk.signal.manager.groups.GroupId;
import org.asamk.signal.manager.storage.contacts.ContactInfo;
import org.asamk.signal.manager.storage.contacts.JsonContactsStore;
import org.asamk.signal.manager.storage.groups.GroupInfo;
import org.asamk.signal.manager.storage.groups.GroupInfoV1;
import org.asamk.signal.manager.storage.groups.JsonGroupStore;
import org.asamk.signal.manager.storage.messageCache.MessageCache;
import org.asamk.signal.manager.storage.profiles.ProfileStore;
import org.asamk.signal.manager.storage.protocol.IdentityInfo;
import org.asamk.signal.manager.storage.protocol.JsonSignalProtocolStore;
import org.asamk.signal.manager.storage.protocol.RecipientStore;
import org.asamk.signal.manager.storage.protocol.SessionInfo;
import org.asamk.signal.manager.storage.protocol.SignalServiceAddressResolver;
import org.asamk.signal.manager.storage.stickers.StickerStore;
import org.asamk.signal.manager.storage.threads.LegacyJsonThreadStore;
import org.asamk.signal.manager.storage.threads.ThreadInfo;
import org.asamk.signal.manager.util.IOUtils;
import org.asamk.signal.manager.util.KeyUtils;
import org.asamk.signal.manager.util.Utils;
@ -99,10 +93,10 @@ public class SignalAccount implements Closeable {
}
public static SignalAccount load(File dataPath, String username) throws IOException {
final File fileName = getFileName(dataPath, username);
final Pair<FileChannel, FileLock> pair = openFileChannel(fileName);
final var fileName = getFileName(dataPath, username);
final var pair = openFileChannel(fileName);
try {
SignalAccount account = new SignalAccount(pair.first(), pair.second());
var account = new SignalAccount(pair.first(), pair.second());
account.load(dataPath);
account.migrateLegacyConfigs();
@ -118,13 +112,13 @@ public class SignalAccount implements Closeable {
File dataPath, String username, IdentityKeyPair identityKey, int registrationId, ProfileKey profileKey
) throws IOException {
IOUtils.createPrivateDirectories(dataPath);
File fileName = getFileName(dataPath, username);
var fileName = getFileName(dataPath, username);
if (!fileName.exists()) {
IOUtils.createPrivateFile(fileName);
}
final Pair<FileChannel, FileLock> pair = openFileChannel(fileName);
SignalAccount account = new SignalAccount(pair.first(), pair.second());
final var pair = openFileChannel(fileName);
var account = new SignalAccount(pair.first(), pair.second());
account.username = username;
account.profileKey = profileKey;
@ -155,13 +149,13 @@ public class SignalAccount implements Closeable {
ProfileKey profileKey
) throws IOException {
IOUtils.createPrivateDirectories(dataPath);
File fileName = getFileName(dataPath, username);
var fileName = getFileName(dataPath, username);
if (!fileName.exists()) {
IOUtils.createPrivateFile(fileName);
}
final Pair<FileChannel, FileLock> pair = openFileChannel(fileName);
SignalAccount account = new SignalAccount(pair.first(), pair.second());
final var pair = openFileChannel(fileName);
var account = new SignalAccount(pair.first(), pair.second());
account.username = username;
account.uuid = uuid;
@ -192,8 +186,8 @@ public class SignalAccount implements Closeable {
save();
}
// Store profile keys only in profile store
for (ContactInfo contact : getContactStore().getContacts()) {
String profileKeyString = contact.profileKey;
for (var contact : getContactStore().getContacts()) {
var profileKeyString = contact.profileKey;
if (profileKeyString == null) {
continue;
}
@ -230,7 +224,7 @@ public class SignalAccount implements Closeable {
if (username == null) {
return false;
}
File f = getFileName(dataPath, username);
var f = getFileName(dataPath, username);
return !(!f.exists() || f.isDirectory());
}
@ -288,7 +282,7 @@ public class SignalAccount implements Closeable {
signalProtocolStore = jsonProcessor.convertValue(Utils.getNotNullNode(rootNode, "axolotlStore"),
JsonSignalProtocolStore.class);
registered = Utils.getNotNullNode(rootNode, "registered").asBoolean();
JsonNode groupStoreNode = rootNode.get("groupStore");
var groupStoreNode = rootNode.get("groupStore");
if (groupStoreNode != null) {
groupStore = jsonProcessor.convertValue(groupStoreNode, JsonGroupStore.class);
groupStore.groupCachePath = getGroupCachePath(dataPath, username);
@ -297,7 +291,7 @@ public class SignalAccount implements Closeable {
groupStore = new JsonGroupStore(getGroupCachePath(dataPath, username));
}
JsonNode contactStoreNode = rootNode.get("contactStore");
var contactStoreNode = rootNode.get("contactStore");
if (contactStoreNode != null) {
contactStore = jsonProcessor.convertValue(contactStoreNode, JsonContactsStore.class);
}
@ -305,7 +299,7 @@ public class SignalAccount implements Closeable {
contactStore = new JsonContactsStore();
}
JsonNode recipientStoreNode = rootNode.get("recipientStore");
var recipientStoreNode = rootNode.get("recipientStore");
if (recipientStoreNode != null) {
recipientStore = jsonProcessor.convertValue(recipientStoreNode, RecipientStore.class);
}
@ -314,29 +308,29 @@ public class SignalAccount implements Closeable {
recipientStore.resolveServiceAddress(getSelfAddress());
for (ContactInfo contact : contactStore.getContacts()) {
for (var contact : contactStore.getContacts()) {
recipientStore.resolveServiceAddress(contact.getAddress());
}
for (GroupInfo group : groupStore.getGroups()) {
for (var group : groupStore.getGroups()) {
if (group instanceof GroupInfoV1) {
GroupInfoV1 groupInfoV1 = (GroupInfoV1) group;
var groupInfoV1 = (GroupInfoV1) group;
groupInfoV1.members = groupInfoV1.members.stream()
.map(m -> recipientStore.resolveServiceAddress(m))
.collect(Collectors.toSet());
}
}
for (SessionInfo session : signalProtocolStore.getSessions()) {
for (var session : signalProtocolStore.getSessions()) {
session.address = recipientStore.resolveServiceAddress(session.address);
}
for (IdentityInfo identity : signalProtocolStore.getIdentities()) {
for (var identity : signalProtocolStore.getIdentities()) {
identity.setAddress(recipientStore.resolveServiceAddress(identity.getAddress()));
}
}
JsonNode profileStoreNode = rootNode.get("profileStore");
var profileStoreNode = rootNode.get("profileStore");
if (profileStoreNode != null) {
profileStore = jsonProcessor.convertValue(profileStoreNode, ProfileStore.class);
}
@ -344,7 +338,7 @@ public class SignalAccount implements Closeable {
profileStore = new ProfileStore();
}
JsonNode stickerStoreNode = rootNode.get("stickerStore");
var stickerStoreNode = rootNode.get("stickerStore");
if (stickerStoreNode != null) {
stickerStore = jsonProcessor.convertValue(stickerStoreNode, StickerStore.class);
}
@ -354,22 +348,21 @@ public class SignalAccount implements Closeable {
messageCache = new MessageCache(getMessageCachePath(dataPath, username));
JsonNode threadStoreNode = rootNode.get("threadStore");
var threadStoreNode = rootNode.get("threadStore");
if (threadStoreNode != null && !threadStoreNode.isNull()) {
LegacyJsonThreadStore threadStore = jsonProcessor.convertValue(threadStoreNode,
LegacyJsonThreadStore.class);
var threadStore = jsonProcessor.convertValue(threadStoreNode, LegacyJsonThreadStore.class);
// Migrate thread info to group and contact store
for (ThreadInfo thread : threadStore.getThreads()) {
for (var thread : threadStore.getThreads()) {
if (thread.id == null || thread.id.isEmpty()) {
continue;
}
try {
ContactInfo contactInfo = contactStore.getContact(new SignalServiceAddress(null, thread.id));
var contactInfo = contactStore.getContact(new SignalServiceAddress(null, thread.id));
if (contactInfo != null) {
contactInfo.messageExpirationTime = thread.messageExpirationTime;
contactStore.updateContact(contactInfo);
} else {
GroupInfo groupInfo = groupStore.getGroup(GroupId.fromBase64(thread.id));
var groupInfo = groupStore.getGroup(GroupId.fromBase64(thread.id));
if (groupInfo instanceof GroupInfoV1) {
((GroupInfoV1) groupInfo).messageExpirationTime = thread.messageExpirationTime;
groupStore.updateGroup(groupInfo);
@ -385,7 +378,7 @@ public class SignalAccount implements Closeable {
if (fileChannel == null) {
return;
}
ObjectNode rootNode = jsonProcessor.createObjectNode();
var rootNode = jsonProcessor.createObjectNode();
rootNode.put("username", username)
.put("uuid", uuid == null ? null : uuid.toString())
.put("deviceId", deviceId)
@ -407,10 +400,10 @@ public class SignalAccount implements Closeable {
.putPOJO("profileStore", profileStore)
.putPOJO("stickerStore", stickerStore);
try {
try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
try (var output = new ByteArrayOutputStream()) {
// Write to memory first to prevent corrupting the file in case of serialization errors
jsonProcessor.writeValue(output, rootNode);
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
var input = new ByteArrayInputStream(output.toByteArray());
synchronized (fileChannel) {
fileChannel.position(0);
input.transferTo(Channels.newOutputStream(fileChannel));
@ -424,8 +417,8 @@ public class SignalAccount implements Closeable {
}
private static Pair<FileChannel, FileLock> openFileChannel(File fileName) throws IOException {
FileChannel fileChannel = new RandomAccessFile(fileName, "rw").getChannel();
FileLock lock = fileChannel.tryLock();
var fileChannel = new RandomAccessFile(fileName, "rw").getChannel();
var lock = fileChannel.tryLock();
if (lock == null) {
logger.info("Config file is in use by another instance, waiting…");
lock = fileChannel.lock();
@ -439,7 +432,7 @@ public class SignalAccount implements Closeable {
}
public void addPreKeys(Collection<PreKeyRecord> records) {
for (PreKeyRecord record : records) {
for (var record : records) {
signalProtocolStore.storePreKey(record.getId(), record);
}
preKeyIdOffset = (preKeyIdOffset + records.size()) % Medium.MAX_VALUE;

View file

@ -13,8 +13,8 @@ public class JsonContactsStore {
private List<ContactInfo> contacts = new ArrayList<>();
public void updateContact(ContactInfo contact) {
final SignalServiceAddress contactAddress = contact.getAddress();
for (int i = 0; i < contacts.size(); i++) {
final var contactAddress = contact.getAddress();
for (var i = 0; i < contacts.size(); i++) {
if (contacts.get(i).getAddress().matches(contactAddress)) {
contacts.set(i, contact);
return;
@ -25,7 +25,7 @@ public class JsonContactsStore {
}
public ContactInfo getContact(SignalServiceAddress address) {
for (ContactInfo contact : contacts) {
for (var contact : contacts) {
if (contact.getAddress().matches(address)) {
if (contact.uuid == null) {
contact.uuid = address.getUuid().orNull();

View file

@ -57,7 +57,7 @@ public abstract class GroupInfo {
@JsonIgnore
public boolean isMember(SignalServiceAddress address) {
for (SignalServiceAddress member : getMembers()) {
for (var member : getMembers()) {
if (member.matches(address)) {
return true;
}
@ -67,7 +67,7 @@ public abstract class GroupInfo {
@JsonIgnore
public boolean isPendingMember(SignalServiceAddress address) {
for (SignalServiceAddress member : getPendingMembers()) {
for (var member : getPendingMembers()) {
if (member.matches(address)) {
return true;
}

View file

@ -135,7 +135,7 @@ public class GroupInfoV1 extends GroupInfo {
}
public void addMembers(Collection<SignalServiceAddress> addresses) {
for (SignalServiceAddress address : addresses) {
for (var address : addresses) {
if (this.members.contains(address)) {
continue;
}
@ -178,7 +178,7 @@ public class GroupInfoV1 extends GroupInfo {
final Set<SignalServiceAddress> value, final JsonGenerator jgen, final SerializerProvider provider
) throws IOException {
jgen.writeStartArray(value.size());
for (SignalServiceAddress address : value) {
for (var address : value) {
if (address.getUuid().isPresent()) {
jgen.writeObject(new JsonSignalServiceAddress(address));
} else {
@ -195,13 +195,13 @@ public class GroupInfoV1 extends GroupInfo {
public Set<SignalServiceAddress> deserialize(
JsonParser jsonParser, DeserializationContext deserializationContext
) throws IOException {
Set<SignalServiceAddress> addresses = new HashSet<>();
var addresses = new HashSet<SignalServiceAddress>();
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
for (JsonNode n : node) {
for (var n : node) {
if (n.isTextual()) {
addresses.add(new SignalServiceAddress(null, n.textValue()));
} else {
JsonSignalServiceAddress address = jsonProcessor.treeToValue(n, JsonSignalServiceAddress.class);
var address = jsonProcessor.treeToValue(n, JsonSignalServiceAddress.class);
addresses.add(address.toSignalServiceAddress());
}
}

View file

@ -30,7 +30,6 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -59,10 +58,10 @@ public class JsonGroupStore {
if (group instanceof GroupInfoV2 && ((GroupInfoV2) group).getGroup() != null) {
try {
IOUtils.createPrivateDirectories(groupCachePath);
try (FileOutputStream stream = new FileOutputStream(getGroupFile(group.getGroupId()))) {
try (var stream = new FileOutputStream(getGroupFile(group.getGroupId()))) {
((GroupInfoV2) group).getGroup().writeTo(stream);
}
final File groupFileLegacy = getGroupFileLegacy(group.getGroupId());
final var groupFileLegacy = getGroupFileLegacy(group.getGroupId());
if (groupFileLegacy.exists()) {
groupFileLegacy.delete();
}
@ -77,7 +76,7 @@ public class JsonGroupStore {
}
public GroupInfo getGroup(GroupId groupId) {
GroupInfo group = groups.get(groupId);
var group = groups.get(groupId);
if (group == null) {
if (groupId instanceof GroupIdV1) {
group = groups.get(GroupUtils.getGroupIdV2((GroupIdV1) groupId));
@ -90,9 +89,9 @@ public class JsonGroupStore {
}
private GroupInfoV1 getGroupV1ByV2Id(GroupIdV2 groupIdV2) {
for (GroupInfo g : groups.values()) {
for (var g : groups.values()) {
if (g instanceof GroupInfoV1) {
final GroupInfoV1 gv1 = (GroupInfoV1) g;
final var gv1 = (GroupInfoV1) g;
if (groupIdV2.equals(gv1.getExpectedV2Id())) {
return gv1;
}
@ -103,14 +102,14 @@ public class JsonGroupStore {
private void loadDecryptedGroup(final GroupInfo group) {
if (group instanceof GroupInfoV2 && ((GroupInfoV2) group).getGroup() == null) {
File groupFile = getGroupFile(group.getGroupId());
var groupFile = getGroupFile(group.getGroupId());
if (!groupFile.exists()) {
groupFile = getGroupFileLegacy(group.getGroupId());
}
if (!groupFile.exists()) {
return;
}
try (FileInputStream stream = new FileInputStream(groupFile)) {
try (var stream = new FileInputStream(groupFile)) {
((GroupInfoV2) group).setGroup(DecryptedGroup.parseFrom(stream));
} catch (IOException ignored) {
}
@ -126,7 +125,7 @@ public class JsonGroupStore {
}
public GroupInfoV1 getOrCreateGroupV1(GroupIdV1 groupId) {
GroupInfo group = getGroup(groupId);
var group = getGroup(groupId);
if (group instanceof GroupInfoV1) {
return (GroupInfoV1) group;
}
@ -139,8 +138,8 @@ public class JsonGroupStore {
}
public List<GroupInfo> getGroups() {
final Collection<GroupInfo> groups = this.groups.values();
for (GroupInfo group : groups) {
final var groups = this.groups.values();
for (var group : groups) {
loadDecryptedGroup(group);
}
return new ArrayList<>(groups);
@ -152,13 +151,13 @@ public class JsonGroupStore {
public void serialize(
final Map<String, GroupInfo> value, final JsonGenerator jgen, final SerializerProvider provider
) throws IOException {
final Collection<GroupInfo> groups = value.values();
final var groups = value.values();
jgen.writeStartArray(groups.size());
for (GroupInfo group : groups) {
for (var group : groups) {
if (group instanceof GroupInfoV1) {
jgen.writeObject(group);
} else if (group instanceof GroupInfoV2) {
final GroupInfoV2 groupV2 = (GroupInfoV2) group;
final var groupV2 = (GroupInfoV2) group;
jgen.writeStartObject();
jgen.writeStringField("groupId", groupV2.getGroupId().toBase64());
jgen.writeStringField("masterKey",
@ -179,16 +178,15 @@ public class JsonGroupStore {
public Map<GroupId, GroupInfo> deserialize(
JsonParser jsonParser, DeserializationContext deserializationContext
) throws IOException {
Map<GroupId, GroupInfo> groups = new HashMap<>();
var groups = new HashMap<GroupId, GroupInfo>();
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
for (JsonNode n : node) {
for (var n : node) {
GroupInfo g;
if (n.hasNonNull("masterKey")) {
// a v2 group
GroupIdV2 groupId = GroupIdV2.fromBase64(n.get("groupId").asText());
var groupId = GroupIdV2.fromBase64(n.get("groupId").asText());
try {
GroupMasterKey masterKey = new GroupMasterKey(Base64.getDecoder()
.decode(n.get("masterKey").asText()));
var masterKey = new GroupMasterKey(Base64.getDecoder().decode(n.get("masterKey").asText()));
g = new GroupInfoV2(groupId, masterKey);
} catch (InvalidInputException | IllegalArgumentException e) {
throw new AssertionError("Invalid master key for group " + groupId.toBase64());

View file

@ -36,7 +36,7 @@ public class MessageCache {
return Stream.of(dir);
}
final File[] files = Objects.requireNonNull(dir.listFiles());
final var files = Objects.requireNonNull(dir.listFiles());
if (files.length == 0) {
try {
Files.delete(dir.toPath());
@ -50,11 +50,11 @@ public class MessageCache {
}
public CachedMessage cacheMessage(SignalServiceEnvelope envelope) {
final long now = new Date().getTime();
final String source = envelope.hasSource() ? envelope.getSourceAddress().getLegacyIdentifier() : "";
final var now = new Date().getTime();
final var source = envelope.hasSource() ? envelope.getSourceAddress().getLegacyIdentifier() : "";
try {
File cacheFile = getMessageCacheFile(source, now, envelope.getTimestamp());
var cacheFile = getMessageCacheFile(source, now, envelope.getTimestamp());
MessageCacheUtils.storeEnvelope(envelope, cacheFile);
return new CachedMessage(cacheFile);
} catch (IOException e) {
@ -72,7 +72,7 @@ public class MessageCache {
}
private File getMessageCacheFile(String sender, long now, long timestamp) throws IOException {
File cachePath = getMessageCachePath(sender);
var cachePath = getMessageCachePath(sender);
IOUtils.createPrivateDirectories(cachePath);
return new File(cachePath, now + "_" + timestamp);
}

View file

@ -22,7 +22,6 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.UUID;
public class ProfileStore {
@ -34,7 +33,7 @@ public class ProfileStore {
private final List<SignalProfileEntry> profiles = new ArrayList<>();
public SignalProfileEntry getProfileEntry(SignalServiceAddress serviceAddress) {
for (SignalProfileEntry entry : profiles) {
for (var entry : profiles) {
if (entry.getServiceAddress().matches(serviceAddress)) {
return entry;
}
@ -43,7 +42,7 @@ public class ProfileStore {
}
public ProfileKey getProfileKey(SignalServiceAddress serviceAddress) {
for (SignalProfileEntry entry : profiles) {
for (var entry : profiles) {
if (entry.getServiceAddress().matches(serviceAddress)) {
return entry.getProfileKey();
}
@ -58,12 +57,8 @@ public class ProfileStore {
SignalProfile profile,
ProfileKeyCredential profileKeyCredential
) {
SignalProfileEntry newEntry = new SignalProfileEntry(serviceAddress,
profileKey,
now,
profile,
profileKeyCredential);
for (int i = 0; i < profiles.size(); i++) {
var newEntry = new SignalProfileEntry(serviceAddress, profileKey, now, profile, profileKeyCredential);
for (var i = 0; i < profiles.size(); i++) {
if (profiles.get(i).getServiceAddress().matches(serviceAddress)) {
profiles.set(i, newEntry);
return;
@ -74,8 +69,8 @@ public class ProfileStore {
}
public void storeProfileKey(SignalServiceAddress serviceAddress, ProfileKey profileKey) {
SignalProfileEntry newEntry = new SignalProfileEntry(serviceAddress, profileKey, 0, null, null);
for (int i = 0; i < profiles.size(); i++) {
var newEntry = new SignalProfileEntry(serviceAddress, profileKey, 0, null, null);
for (var i = 0; i < profiles.size(); i++) {
if (profiles.get(i).getServiceAddress().matches(serviceAddress)) {
if (!profiles.get(i).getProfileKey().equals(profileKey)) {
profiles.set(i, newEntry);
@ -95,13 +90,13 @@ public class ProfileStore {
) throws IOException {
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
List<SignalProfileEntry> addresses = new ArrayList<>();
var addresses = new ArrayList<SignalProfileEntry>();
if (node.isArray()) {
for (JsonNode entry : node) {
String name = entry.hasNonNull("name") ? entry.get("name").asText() : null;
UUID uuid = entry.hasNonNull("uuid") ? UuidUtil.parseOrNull(entry.get("uuid").asText()) : null;
final SignalServiceAddress serviceAddress = new SignalServiceAddress(uuid, name);
for (var entry : node) {
var name = entry.hasNonNull("name") ? entry.get("name").asText() : null;
var uuid = entry.hasNonNull("uuid") ? UuidUtil.parseOrNull(entry.get("uuid").asText()) : null;
final var serviceAddress = new SignalServiceAddress(uuid, name);
ProfileKey profileKey = null;
try {
profileKey = new ProfileKey(Base64.getDecoder().decode(entry.get("profileKey").asText()));
@ -115,8 +110,8 @@ public class ProfileStore {
} catch (Throwable ignored) {
}
}
long lastUpdateTimestamp = entry.get("lastUpdateTimestamp").asLong();
SignalProfile profile = jsonProcessor.treeToValue(entry.get("profile"), SignalProfile.class);
var lastUpdateTimestamp = entry.get("lastUpdateTimestamp").asLong();
var profile = jsonProcessor.treeToValue(entry.get("profile"), SignalProfile.class);
addresses.add(new SignalProfileEntry(serviceAddress,
profileKey,
lastUpdateTimestamp,
@ -136,8 +131,8 @@ public class ProfileStore {
List<SignalProfileEntry> profiles, JsonGenerator json, SerializerProvider serializerProvider
) throws IOException {
json.writeStartArray();
for (SignalProfileEntry profileEntry : profiles) {
final SignalServiceAddress address = profileEntry.getServiceAddress();
for (var profileEntry : profiles) {
final var address = profileEntry.getServiceAddress();
json.writeStartObject();
if (address.getNumber().isPresent()) {
json.writeStringField("name", address.getNumber().get());

View file

@ -25,7 +25,6 @@ import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.UUID;
public class JsonIdentityKeyStore implements IdentityKeyStore {
@ -85,7 +84,7 @@ public class JsonIdentityKeyStore implements IdentityKeyStore {
public boolean saveIdentity(
SignalServiceAddress serviceAddress, IdentityKey identityKey, TrustLevel trustLevel, Date added
) {
for (IdentityInfo id : identities) {
for (var id : identities) {
if (!id.address.matches(serviceAddress) || !id.identityKey.equals(identityKey)) {
continue;
}
@ -111,7 +110,7 @@ public class JsonIdentityKeyStore implements IdentityKeyStore {
public void setIdentityTrustLevel(
SignalServiceAddress serviceAddress, IdentityKey identityKey, TrustLevel trustLevel
) {
for (IdentityInfo id : identities) {
for (var id : identities) {
if (!id.address.matches(serviceAddress) || !id.identityKey.equals(identityKey)) {
continue;
}
@ -129,10 +128,10 @@ public class JsonIdentityKeyStore implements IdentityKeyStore {
@Override
public boolean isTrustedIdentity(SignalProtocolAddress address, IdentityKey identityKey, Direction direction) {
// TODO implement possibility for different handling of incoming/outgoing trust decisions
SignalServiceAddress serviceAddress = resolveSignalServiceAddress(address.getName());
boolean trustOnFirstUse = true;
var serviceAddress = resolveSignalServiceAddress(address.getName());
var trustOnFirstUse = true;
for (IdentityInfo id : identities) {
for (var id : identities) {
if (!id.address.matches(serviceAddress)) {
continue;
}
@ -149,20 +148,20 @@ public class JsonIdentityKeyStore implements IdentityKeyStore {
@Override
public IdentityKey getIdentity(SignalProtocolAddress address) {
SignalServiceAddress serviceAddress = resolveSignalServiceAddress(address.getName());
IdentityInfo identity = getIdentity(serviceAddress);
var serviceAddress = resolveSignalServiceAddress(address.getName());
var identity = getIdentity(serviceAddress);
return identity == null ? null : identity.getIdentityKey();
}
public IdentityInfo getIdentity(SignalServiceAddress serviceAddress) {
long maxDate = 0;
IdentityInfo maxIdentity = null;
for (IdentityInfo id : this.identities) {
for (var id : this.identities) {
if (!id.address.matches(serviceAddress)) {
continue;
}
final long time = id.getDateAdded().getTime();
final var time = id.getDateAdded().getTime();
if (maxIdentity == null || maxDate <= time) {
maxDate = time;
maxIdentity = id;
@ -177,8 +176,8 @@ public class JsonIdentityKeyStore implements IdentityKeyStore {
}
public List<IdentityInfo> getIdentities(SignalServiceAddress serviceAddress) {
List<IdentityInfo> identities = new ArrayList<>();
for (IdentityInfo identity : this.identities) {
var identities = new ArrayList<IdentityInfo>();
for (var identity : this.identities) {
if (identity.address.matches(serviceAddress)) {
identities.add(identity);
}
@ -194,34 +193,32 @@ public class JsonIdentityKeyStore implements IdentityKeyStore {
) throws IOException {
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
int localRegistrationId = node.get("registrationId").asInt();
IdentityKeyPair identityKeyPair = new IdentityKeyPair(Base64.getDecoder()
.decode(node.get("identityKey").asText()));
var localRegistrationId = node.get("registrationId").asInt();
var identityKeyPair = new IdentityKeyPair(Base64.getDecoder().decode(node.get("identityKey").asText()));
JsonIdentityKeyStore keyStore = new JsonIdentityKeyStore(identityKeyPair, localRegistrationId);
var keyStore = new JsonIdentityKeyStore(identityKeyPair, localRegistrationId);
JsonNode trustedKeysNode = node.get("trustedKeys");
var trustedKeysNode = node.get("trustedKeys");
if (trustedKeysNode.isArray()) {
for (JsonNode trustedKey : trustedKeysNode) {
String trustedKeyName = trustedKey.hasNonNull("name") ? trustedKey.get("name").asText() : null;
for (var trustedKey : trustedKeysNode) {
var 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")
var uuid = trustedKey.hasNonNull("uuid")
? UuidUtil.parseOrNull(trustedKey.get("uuid").asText())
: null;
final SignalServiceAddress serviceAddress = uuid == null
final var serviceAddress = uuid == null
? Utils.getSignalServiceAddressFromIdentifier(trustedKeyName)
: new SignalServiceAddress(uuid, trustedKeyName);
try {
IdentityKey id = new IdentityKey(Base64.getDecoder()
.decode(trustedKey.get("identityKey").asText()), 0);
TrustLevel trustLevel = trustedKey.hasNonNull("trustLevel") ? TrustLevel.fromInt(trustedKey.get(
var id = new IdentityKey(Base64.getDecoder().decode(trustedKey.get("identityKey").asText()), 0);
var trustLevel = trustedKey.hasNonNull("trustLevel") ? TrustLevel.fromInt(trustedKey.get(
"trustLevel").asInt()) : TrustLevel.TRUSTED_UNVERIFIED;
Date added = trustedKey.hasNonNull("addedTimestamp") ? new Date(trustedKey.get("addedTimestamp")
var added = trustedKey.hasNonNull("addedTimestamp") ? new Date(trustedKey.get("addedTimestamp")
.asLong()) : new Date();
keyStore.saveIdentity(serviceAddress, id, trustLevel, added);
} catch (InvalidKeyException e) {
@ -251,7 +248,7 @@ public class JsonIdentityKeyStore implements IdentityKeyStore {
Base64.getEncoder()
.encodeToString(jsonIdentityKeyStore.getIdentityKeyPair().getPublicKey().serialize()));
json.writeArrayFieldStart("trustedKeys");
for (IdentityInfo trustedKey : jsonIdentityKeyStore.identities) {
for (var trustedKey : jsonIdentityKeyStore.identities) {
json.writeStartObject();
if (trustedKey.getAddress().getNumber().isPresent()) {
json.writeStringField("name", trustedKey.getAddress().getNumber().get());

View file

@ -69,16 +69,16 @@ class JsonPreKeyStore implements PreKeyStore {
) throws IOException {
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
Map<Integer, byte[]> preKeyMap = new HashMap<>();
var preKeyMap = new HashMap<Integer, byte[]>();
if (node.isArray()) {
for (JsonNode preKey : node) {
final int preKeyId = preKey.get("id").asInt();
final byte[] preKeyRecord = Base64.getDecoder().decode(preKey.get("record").asText());
for (var preKey : node) {
final var preKeyId = preKey.get("id").asInt();
final var preKeyRecord = Base64.getDecoder().decode(preKey.get("record").asText());
preKeyMap.put(preKeyId, preKeyRecord);
}
}
JsonPreKeyStore keyStore = new JsonPreKeyStore();
var keyStore = new JsonPreKeyStore();
keyStore.addPreKeys(preKeyMap);
return keyStore;
@ -92,7 +92,7 @@ class JsonPreKeyStore implements PreKeyStore {
JsonPreKeyStore jsonPreKeyStore, JsonGenerator json, SerializerProvider serializerProvider
) throws IOException {
json.writeStartArray();
for (Map.Entry<Integer, byte[]> preKey : jsonPreKeyStore.store.entrySet()) {
for (var preKey : jsonPreKeyStore.store.entrySet()) {
json.writeStartObject();
json.writeNumberField("id", preKey.getKey());
json.writeStringField("record", Base64.getEncoder().encodeToString(preKey.getValue()));

View file

@ -22,7 +22,6 @@ import java.util.ArrayList;
import java.util.Base64;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
class JsonSessionStore implements SignalServiceSessionStore {
@ -49,14 +48,14 @@ class JsonSessionStore implements SignalServiceSessionStore {
@Override
public synchronized SessionRecord loadSession(SignalProtocolAddress address) {
SignalServiceAddress serviceAddress = resolveSignalServiceAddress(address.getName());
for (SessionInfo info : sessions) {
var serviceAddress = resolveSignalServiceAddress(address.getName());
for (var info : sessions) {
if (info.address.matches(serviceAddress) && info.deviceId == address.getDeviceId()) {
try {
return new SessionRecord(info.sessionRecord);
} catch (IOException e) {
logger.warn("Failed to load session, resetting session: {}", e.getMessage());
final SessionRecord sessionRecord = new SessionRecord();
final var sessionRecord = new SessionRecord();
info.sessionRecord = sessionRecord.serialize();
return sessionRecord;
}
@ -72,10 +71,10 @@ class JsonSessionStore implements SignalServiceSessionStore {
@Override
public synchronized List<Integer> getSubDeviceSessions(String name) {
SignalServiceAddress serviceAddress = resolveSignalServiceAddress(name);
var serviceAddress = resolveSignalServiceAddress(name);
List<Integer> deviceIds = new LinkedList<>();
for (SessionInfo info : sessions) {
var deviceIds = new LinkedList<Integer>();
for (var info : sessions) {
if (info.address.matches(serviceAddress) && info.deviceId != 1) {
deviceIds.add(info.deviceId);
}
@ -86,8 +85,8 @@ class JsonSessionStore implements SignalServiceSessionStore {
@Override
public synchronized void storeSession(SignalProtocolAddress address, SessionRecord record) {
SignalServiceAddress serviceAddress = resolveSignalServiceAddress(address.getName());
for (SessionInfo info : sessions) {
var serviceAddress = resolveSignalServiceAddress(address.getName());
for (var info : sessions) {
if (info.address.matches(serviceAddress) && info.deviceId == address.getDeviceId()) {
if (!info.address.getUuid().isPresent() || !info.address.getNumber().isPresent()) {
info.address = serviceAddress;
@ -102,8 +101,8 @@ class JsonSessionStore implements SignalServiceSessionStore {
@Override
public synchronized boolean containsSession(SignalProtocolAddress address) {
SignalServiceAddress serviceAddress = resolveSignalServiceAddress(address.getName());
for (SessionInfo info : sessions) {
var serviceAddress = resolveSignalServiceAddress(address.getName());
for (var info : sessions) {
if (info.address.matches(serviceAddress) && info.deviceId == address.getDeviceId()) {
return true;
}
@ -113,13 +112,13 @@ class JsonSessionStore implements SignalServiceSessionStore {
@Override
public synchronized void deleteSession(SignalProtocolAddress address) {
SignalServiceAddress serviceAddress = resolveSignalServiceAddress(address.getName());
var serviceAddress = resolveSignalServiceAddress(address.getName());
sessions.removeIf(info -> info.address.matches(serviceAddress) && info.deviceId == address.getDeviceId());
}
@Override
public synchronized void deleteAllSessions(String name) {
SignalServiceAddress serviceAddress = resolveSignalServiceAddress(name);
var serviceAddress = resolveSignalServiceAddress(name);
deleteAllSessions(serviceAddress);
}
@ -129,7 +128,7 @@ class JsonSessionStore implements SignalServiceSessionStore {
@Override
public void archiveSession(final SignalProtocolAddress address) {
final SessionRecord sessionRecord = loadSession(address);
final var sessionRecord = loadSession(address);
if (sessionRecord == null) {
return;
}
@ -138,9 +137,9 @@ class JsonSessionStore implements SignalServiceSessionStore {
}
public void archiveAllSessions() {
for (SessionInfo info : sessions) {
for (var info : sessions) {
try {
final SessionRecord sessionRecord = new SessionRecord(info.sessionRecord);
final var sessionRecord = new SessionRecord(info.sessionRecord);
sessionRecord.archiveCurrentState();
info.sessionRecord = sessionRecord.serialize();
} catch (IOException ignored) {
@ -156,23 +155,23 @@ class JsonSessionStore implements SignalServiceSessionStore {
) throws IOException {
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
JsonSessionStore sessionStore = new JsonSessionStore();
var sessionStore = new JsonSessionStore();
if (node.isArray()) {
for (JsonNode session : node) {
String sessionName = session.hasNonNull("name") ? session.get("name").asText() : null;
for (var session : node) {
var 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;
final SignalServiceAddress serviceAddress = uuid == null
var uuid = session.hasNonNull("uuid") ? UuidUtil.parseOrNull(session.get("uuid").asText()) : null;
final var serviceAddress = uuid == null
? Utils.getSignalServiceAddressFromIdentifier(sessionName)
: new SignalServiceAddress(uuid, sessionName);
final int deviceId = session.get("deviceId").asInt();
final byte[] record = Base64.getDecoder().decode(session.get("record").asText());
SessionInfo sessionInfo = new SessionInfo(serviceAddress, deviceId, record);
final var deviceId = session.get("deviceId").asInt();
final var record = Base64.getDecoder().decode(session.get("record").asText());
var sessionInfo = new SessionInfo(serviceAddress, deviceId, record);
sessionStore.sessions.add(sessionInfo);
}
}
@ -188,7 +187,7 @@ class JsonSessionStore implements SignalServiceSessionStore {
JsonSessionStore jsonSessionStore, JsonGenerator json, SerializerProvider serializerProvider
) throws IOException {
json.writeStartArray();
for (SessionInfo sessionInfo : jsonSessionStore.sessions) {
for (var sessionInfo : jsonSessionStore.sessions) {
json.writeStartObject();
if (sessionInfo.address.getNumber().isPresent()) {
json.writeStringField("name", sessionInfo.address.getNumber().get());

View file

@ -51,9 +51,9 @@ class JsonSignedPreKeyStore implements SignedPreKeyStore {
@Override
public List<SignedPreKeyRecord> loadSignedPreKeys() {
try {
List<SignedPreKeyRecord> results = new LinkedList<>();
var results = new LinkedList<SignedPreKeyRecord>();
for (byte[] serialized : store.values()) {
for (var serialized : store.values()) {
results.add(new SignedPreKeyRecord(serialized));
}
@ -86,16 +86,16 @@ class JsonSignedPreKeyStore implements SignedPreKeyStore {
) throws IOException {
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
Map<Integer, byte[]> preKeyMap = new HashMap<>();
var preKeyMap = new HashMap<Integer, byte[]>();
if (node.isArray()) {
for (JsonNode preKey : node) {
final int preKeyId = preKey.get("id").asInt();
final byte[] preKeyRecord = Base64.getDecoder().decode(preKey.get("record").asText());
for (var preKey : node) {
final var preKeyId = preKey.get("id").asInt();
final var preKeyRecord = Base64.getDecoder().decode(preKey.get("record").asText());
preKeyMap.put(preKeyId, preKeyRecord);
}
}
JsonSignedPreKeyStore keyStore = new JsonSignedPreKeyStore();
var keyStore = new JsonSignedPreKeyStore();
keyStore.addSignedPreKeys(preKeyMap);
return keyStore;
@ -109,7 +109,7 @@ class JsonSignedPreKeyStore implements SignedPreKeyStore {
JsonSignedPreKeyStore jsonPreKeyStore, JsonGenerator json, SerializerProvider serializerProvider
) throws IOException {
json.writeStartArray();
for (Map.Entry<Integer, byte[]> signedPreKey : jsonPreKeyStore.store.entrySet()) {
for (var signedPreKey : jsonPreKeyStore.store.entrySet()) {
json.writeStartObject();
json.writeNumberField("id", signedPreKey.getKey());
json.writeStringField("record", Base64.getEncoder().encodeToString(signedPreKey.getValue()));

View file

@ -17,7 +17,6 @@ import org.whispersystems.signalservice.api.util.UuidUtil;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
public class RecipientStore {
@ -33,7 +32,7 @@ public class RecipientStore {
return serviceAddress;
}
for (SignalServiceAddress address : addresses) {
for (var address : addresses) {
if (address.matches(serviceAddress)) {
return address;
}
@ -54,13 +53,13 @@ public class RecipientStore {
) throws IOException {
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
Set<SignalServiceAddress> addresses = new HashSet<>();
var addresses = new HashSet<SignalServiceAddress>();
if (node.isArray()) {
for (JsonNode recipient : node) {
String recipientName = recipient.get("name").asText();
UUID uuid = UuidUtil.parseOrThrow(recipient.get("uuid").asText());
final SignalServiceAddress serviceAddress = new SignalServiceAddress(uuid, recipientName);
for (var recipient : node) {
var recipientName = recipient.get("name").asText();
var uuid = UuidUtil.parseOrThrow(recipient.get("uuid").asText());
final var serviceAddress = new SignalServiceAddress(uuid, recipientName);
addresses.add(serviceAddress);
}
}
@ -76,7 +75,7 @@ public class RecipientStore {
Set<SignalServiceAddress> addresses, JsonGenerator json, SerializerProvider serializerProvider
) throws IOException {
json.writeStartArray();
for (SignalServiceAddress address : addresses) {
for (var address : addresses) {
json.writeStartObject();
json.writeStringField("name", address.getNumber().get());
json.writeStringField("uuid", address.getUuid().get().toString());

View file

@ -12,7 +12,6 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.io.IOException;
import java.util.Base64;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
@ -36,9 +35,9 @@ public class StickerStore {
public void serialize(
final Map<byte[], Sticker> value, final JsonGenerator jgen, final SerializerProvider provider
) throws IOException {
final Collection<Sticker> stickers = value.values();
final var stickers = value.values();
jgen.writeStartArray(stickers.size());
for (Sticker sticker : stickers) {
for (var sticker : stickers) {
jgen.writeStartObject();
jgen.writeStringField("packId", Base64.getEncoder().encodeToString(sticker.getPackId()));
jgen.writeStringField("packKey", Base64.getEncoder().encodeToString(sticker.getPackKey()));
@ -55,12 +54,12 @@ public class StickerStore {
public Map<byte[], Sticker> deserialize(
JsonParser jsonParser, DeserializationContext deserializationContext
) throws IOException {
Map<byte[], Sticker> stickers = new HashMap<>();
var stickers = new HashMap<byte[], Sticker>();
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
for (JsonNode n : node) {
byte[] packId = Base64.getDecoder().decode(n.get("packId").asText());
byte[] packKey = Base64.getDecoder().decode(n.get("packKey").asText());
boolean installed = n.get("installed").asBoolean(false);
for (var n : node) {
var packId = Base64.getDecoder().decode(n.get("packId").asText());
var packKey = Base64.getDecoder().decode(n.get("packKey").asText());
var installed = n.get("installed").asBoolean(false);
stickers.put(packId, new Sticker(packId, packKey, installed));
}

View file

@ -47,10 +47,10 @@ public class LegacyJsonThreadStore {
public Map<String, ThreadInfo> deserialize(
JsonParser jsonParser, DeserializationContext deserializationContext
) throws IOException {
Map<String, ThreadInfo> threads = new HashMap<>();
var threads = new HashMap<String, ThreadInfo>();
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
for (JsonNode n : node) {
ThreadInfo t = jsonProcessor.treeToValue(n, ThreadInfo.class);
for (var n : node) {
var t = jsonProcessor.treeToValue(n, ThreadInfo.class);
threads.put(t.id, t);
}

View file

@ -18,7 +18,7 @@ public class AttachmentUtils {
List<SignalServiceAttachment> signalServiceAttachments = null;
if (attachments != null) {
signalServiceAttachments = new ArrayList<>(attachments.size());
for (String attachment : attachments) {
for (var attachment : attachments) {
try {
signalServiceAttachments.add(createAttachment(new File(attachment)));
} catch (IOException e) {
@ -30,7 +30,7 @@ public class AttachmentUtils {
}
public static SignalServiceAttachmentStream createAttachment(File attachmentFile) throws IOException {
final StreamDetails streamDetails = Utils.createStreamDetailsFromFile(attachmentFile);
final var streamDetails = Utils.createStreamDetailsFromFile(attachmentFile);
return createAttachment(streamDetails, Optional.of(attachmentFile.getName()));
}
@ -38,7 +38,7 @@ public class AttachmentUtils {
StreamDetails streamDetails, Optional<String> name
) {
// TODO mabybe add a parameter to set the voiceNote, borderless, preview, width, height and caption option
final long uploadTimestamp = System.currentTimeMillis();
final var uploadTimestamp = System.currentTimeMillis();
Optional<byte[]> preview = Optional.absent();
Optional<String> caption = Optional.absent();
Optional<String> blurHash = Optional.absent();

View file

@ -7,7 +7,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.EnumSet;
@ -20,13 +19,13 @@ import static java.nio.file.attribute.PosixFilePermission.OWNER_WRITE;
public class IOUtils {
public static File createTempFile() throws IOException {
final File tempFile = File.createTempFile("signal-cli_tmp_", ".tmp");
final var tempFile = File.createTempFile("signal-cli_tmp_", ".tmp");
tempFile.deleteOnExit();
return tempFile;
}
public static byte[] readFully(InputStream in) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
var baos = new ByteArrayOutputStream();
IOUtils.copyStream(in, baos);
return baos.toByteArray();
}
@ -36,7 +35,7 @@ public class IOUtils {
return;
}
final Path path = file.toPath();
final var path = file.toPath();
try {
Set<PosixFilePermission> perms = EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE);
Files.createDirectories(path, PosixFilePermissions.asFileAttribute(perms));
@ -46,7 +45,7 @@ public class IOUtils {
}
public static void createPrivateFile(File path) throws IOException {
final Path file = path.toPath();
final var file = path.toPath();
try {
Set<PosixFilePermission> perms = EnumSet.of(OWNER_READ, OWNER_WRITE);
Files.createFile(file, PosixFilePermissions.asFileAttribute(perms));
@ -66,7 +65,7 @@ public class IOUtils {
}
public static void copyStream(InputStream input, OutputStream output, int bufferSize) throws IOException {
byte[] buffer = new byte[bufferSize];
var buffer = new byte[bufferSize];
int read;
while ((read = input.read(buffer)) != -1) {

View file

@ -6,8 +6,6 @@ import org.whispersystems.libsignal.IdentityKey;
import org.whispersystems.libsignal.IdentityKeyPair;
import org.whispersystems.libsignal.InvalidKeyException;
import org.whispersystems.libsignal.ecc.Curve;
import org.whispersystems.libsignal.ecc.ECKeyPair;
import org.whispersystems.libsignal.ecc.ECPrivateKey;
import org.whispersystems.libsignal.state.PreKeyRecord;
import org.whispersystems.libsignal.state.SignedPreKeyRecord;
import org.whispersystems.libsignal.util.Medium;
@ -26,19 +24,19 @@ public class KeyUtils {
}
public static IdentityKeyPair generateIdentityKeyPair() {
ECKeyPair djbKeyPair = Curve.generateKeyPair();
IdentityKey djbIdentityKey = new IdentityKey(djbKeyPair.getPublicKey());
ECPrivateKey djbPrivateKey = djbKeyPair.getPrivateKey();
var djbKeyPair = Curve.generateKeyPair();
var djbIdentityKey = new IdentityKey(djbKeyPair.getPublicKey());
var djbPrivateKey = djbKeyPair.getPrivateKey();
return new IdentityKeyPair(djbIdentityKey, djbPrivateKey);
}
public static List<PreKeyRecord> generatePreKeyRecords(final int offset, final int batchSize) {
List<PreKeyRecord> records = new ArrayList<>(batchSize);
for (int i = 0; i < batchSize; i++) {
int preKeyId = (offset + i) % Medium.MAX_VALUE;
ECKeyPair keyPair = Curve.generateKeyPair();
PreKeyRecord record = new PreKeyRecord(preKeyId, keyPair);
var records = new ArrayList<PreKeyRecord>(batchSize);
for (var i = 0; i < batchSize; i++) {
var preKeyId = (offset + i) % Medium.MAX_VALUE;
var keyPair = Curve.generateKeyPair();
var record = new PreKeyRecord(preKeyId, keyPair);
records.add(record);
}
@ -48,7 +46,7 @@ public class KeyUtils {
public static SignedPreKeyRecord generateSignedPreKeyRecord(
final IdentityKeyPair identityKeyPair, final int signedPreKeyId
) {
ECKeyPair keyPair = Curve.generateKeyPair();
var keyPair = Curve.generateKeyPair();
byte[] signature;
try {
signature = Curve.calculateSignature(identityKeyPair.getPrivateKey(), keyPair.getPublicKey().serialize());
@ -83,12 +81,12 @@ public class KeyUtils {
}
private static String getSecret(int size) {
byte[] secret = getSecretBytes(size);
var secret = getSecretBytes(size);
return Base64.getEncoder().encodeToString(secret);
}
public static byte[] getSecretBytes(int size) {
byte[] secret = new byte[size];
var secret = new byte[size];
secureRandom.nextBytes(secret);
return secret;
}

View file

@ -16,32 +16,32 @@ import java.util.UUID;
public class MessageCacheUtils {
public static SignalServiceEnvelope loadEnvelope(File file) throws IOException {
try (FileInputStream f = new FileInputStream(file)) {
DataInputStream in = new DataInputStream(f);
int version = in.readInt();
try (var f = new FileInputStream(file)) {
var in = new DataInputStream(f);
var version = in.readInt();
if (version > 4) {
return null;
}
int type = in.readInt();
String source = in.readUTF();
var type = in.readInt();
var source = in.readUTF();
UUID sourceUuid = null;
if (version >= 3) {
sourceUuid = UuidUtil.parseOrNull(in.readUTF());
}
int sourceDevice = in.readInt();
var sourceDevice = in.readInt();
if (version == 1) {
// read legacy relay field
in.readUTF();
}
long timestamp = in.readLong();
var timestamp = in.readLong();
byte[] content = null;
int contentLen = in.readInt();
var contentLen = in.readInt();
if (contentLen > 0) {
content = new byte[contentLen];
in.readFully(content);
}
byte[] legacyMessage = null;
int legacyMessageLen = in.readInt();
var legacyMessageLen = in.readInt();
if (legacyMessageLen > 0) {
legacyMessage = new byte[legacyMessageLen];
in.readFully(legacyMessage);
@ -75,8 +75,8 @@ public class MessageCacheUtils {
}
public static void storeEnvelope(SignalServiceEnvelope envelope, File file) throws IOException {
try (FileOutputStream f = new FileOutputStream(file)) {
try (DataOutputStream out = new DataOutputStream(f)) {
try (var f = new FileOutputStream(file)) {
try (var out = new DataOutputStream(f)) {
out.writeInt(4); // version
out.writeInt(envelope.getType());
out.writeUTF(envelope.getSourceE164().isPresent() ? envelope.getSourceE164().get() : "");
@ -96,7 +96,7 @@ public class MessageCacheUtils {
out.writeInt(0);
}
out.writeLong(envelope.getServerReceivedTimestamp());
String uuid = envelope.getUuid();
var uuid = envelope.getUuid();
out.writeUTF(uuid == null ? "" : uuid);
out.writeLong(envelope.getServerDeliveredTimestamp());
}

View file

@ -12,18 +12,18 @@ public final class PinHashing {
}
public static HashedPin hashPin(String pin, KeyBackupService.HashSession hashSession) {
final Argon2Parameters params = new Argon2Parameters.Builder(Argon2Parameters.ARGON2_id).withParallelism(1)
final var params = new Argon2Parameters.Builder(Argon2Parameters.ARGON2_id).withParallelism(1)
.withIterations(32)
.withVersion(Argon2Parameters.ARGON2_VERSION_13)
.withMemoryAsKB(16 * 1024)
.withSalt(hashSession.hashSalt())
.build();
final Argon2BytesGenerator generator = new Argon2BytesGenerator();
final var generator = new Argon2BytesGenerator();
generator.init(params);
return PinHasher.hashPin(PinHasher.normalize(pin), password -> {
byte[] output = new byte[64];
var output = new byte[64];
generator.generateBytes(password, output);
return output;
});

View file

@ -13,11 +13,11 @@ public class ProfileUtils {
public static SignalProfile decryptProfile(
final ProfileKey profileKey, final SignalServiceProfile encryptedProfile
) {
ProfileCipher profileCipher = new ProfileCipher(profileKey);
var profileCipher = new ProfileCipher(profileKey);
try {
String name = decryptName(encryptedProfile.getName(), profileCipher);
String about = decryptName(encryptedProfile.getAbout(), profileCipher);
String aboutEmoji = decryptName(encryptedProfile.getAboutEmoji(), profileCipher);
var name = decryptName(encryptedProfile.getName(), profileCipher);
var about = decryptName(encryptedProfile.getAbout(), profileCipher);
var aboutEmoji = decryptName(encryptedProfile.getAboutEmoji(), profileCipher);
String unidentifiedAccess;
try {
unidentifiedAccess = encryptedProfile.getUnidentifiedAccess() == null

View file

@ -13,8 +13,6 @@ import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class StickerUtils {
@ -33,7 +31,7 @@ public class StickerUtils {
throw new StickerPackInvalidException("Could not find manifest.json");
}
JsonStickerPack pack = parseStickerPack(rootPath, zip);
var pack = parseStickerPack(rootPath, zip);
if (pack.stickers == null) {
throw new StickerPackInvalidException("Must set a 'stickers' field.");
@ -43,8 +41,8 @@ public class StickerUtils {
throw new StickerPackInvalidException("Must include stickers.");
}
List<SignalServiceStickerManifestUpload.StickerInfo> stickers = new ArrayList<>(pack.stickers.size());
for (JsonStickerPack.JsonSticker sticker : pack.stickers) {
var stickers = new ArrayList<SignalServiceStickerManifestUpload.StickerInfo>(pack.stickers.size());
for (var sticker : pack.stickers) {
if (sticker.file == null) {
throw new StickerPackInvalidException("Must set a 'file' field on each sticker.");
}
@ -56,9 +54,8 @@ public class StickerUtils {
throw new StickerPackInvalidException("Could not find find " + sticker.file);
}
String contentType = Utils.getFileMimeType(new File(sticker.file), null);
SignalServiceStickerManifestUpload.StickerInfo stickerInfo = new SignalServiceStickerManifestUpload.StickerInfo(
data.first(),
var contentType = Utils.getFileMimeType(new File(sticker.file), null);
var stickerInfo = new SignalServiceStickerManifestUpload.StickerInfo(data.first(),
data.second(),
Optional.fromNullable(sticker.emoji).or(""),
contentType);
@ -78,7 +75,7 @@ public class StickerUtils {
throw new StickerPackInvalidException("Could not find find " + pack.cover.file);
}
String contentType = Utils.getFileMimeType(new File(pack.cover.file), null);
var contentType = Utils.getFileMimeType(new File(pack.cover.file), null);
cover = new SignalServiceStickerManifestUpload.StickerInfo(data.first(),
data.second(),
Optional.fromNullable(pack.cover.emoji).or(""),
@ -102,10 +99,10 @@ public class StickerUtils {
final String rootPath, final ZipFile zip, final String subfile
) throws IOException {
if (zip != null) {
final ZipEntry entry = zip.getEntry(subfile);
final var entry = zip.getEntry(subfile);
return new Pair<>(zip.getInputStream(entry), entry.getSize());
} else {
final File file = new File(rootPath, subfile);
final var file = new File(rootPath, subfile);
return new Pair<>(new FileInputStream(file), file.length());
}
}

View file

@ -3,7 +3,6 @@ package org.asamk.signal.manager.util;
import com.fasterxml.jackson.databind.JsonNode;
import org.whispersystems.libsignal.IdentityKey;
import org.whispersystems.libsignal.fingerprint.Fingerprint;
import org.whispersystems.libsignal.fingerprint.NumericFingerprintGenerator;
import org.whispersystems.signalservice.api.push.SignalServiceAddress;
import org.whispersystems.signalservice.api.util.StreamDetails;
@ -21,7 +20,7 @@ import java.nio.file.Files;
public class Utils {
public static String getFileMimeType(File file, String defaultMimeType) throws IOException {
String mime = Files.probeContentType(file.toPath());
var mime = Files.probeContentType(file.toPath());
if (mime == null) {
try (InputStream bufferedStream = new BufferedInputStream(new FileInputStream(file))) {
mime = URLConnection.guessContentTypeFromStream(bufferedStream);
@ -35,8 +34,8 @@ public class Utils {
public static StreamDetails createStreamDetailsFromFile(File file) throws IOException {
InputStream stream = new FileInputStream(file);
final long size = file.length();
final String mime = getFileMimeType(file, "application/octet-stream");
final var size = file.length();
final var mime = getFileMimeType(file, "application/octet-stream");
return new StreamDetails(stream, mime, size);
}
@ -66,7 +65,7 @@ public class Utils {
theirId = theirAddress.getNumber().get().getBytes();
}
Fingerprint fingerprint = new NumericFingerprintGenerator(5200).createFor(version,
var fingerprint = new NumericFingerprintGenerator(5200).createFor(version,
ownId,
ownIdentityKey,
theirId,
@ -83,7 +82,7 @@ public class Utils {
}
public static JsonNode getNotNullNode(JsonNode parent, String name) throws InvalidObjectException {
JsonNode node = parent.get(name);
var node = parent.get(name);
if (node == null || node.isNull()) {
throw new InvalidObjectException(String.format("Incorrect file format: expected parameter %s not found ",
name));

View file

@ -3,10 +3,7 @@ package org.asamk.signal;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import net.sourceforge.argparse4j.inf.Subparsers;
import org.asamk.Signal;
import org.asamk.signal.commands.Command;
@ -33,7 +30,6 @@ import org.whispersystems.signalservice.api.util.PhoneNumberFormatter;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
@ -44,7 +40,7 @@ public class App {
private final Namespace ns;
static ArgumentParser buildArgumentParser() {
ArgumentParser parser = ArgumentParsers.newFor("signal-cli")
var parser = ArgumentParsers.newFor("signal-cli")
.build()
.defaultHelp(true)
.description("Commandline interface for Signal.")
@ -59,7 +55,7 @@ public class App {
parser.addArgument("-u", "--username").help("Specify your phone number, that will be used for verification.");
MutuallyExclusiveGroup mut = parser.addMutuallyExclusiveGroup();
var mut = parser.addMutuallyExclusiveGroup();
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());
@ -68,11 +64,11 @@ public class App {
.type(Arguments.enumStringType(OutputType.class))
.setDefault(OutputType.PLAIN_TEXT);
Subparsers subparsers = parser.addSubparsers().title("subcommands").dest("command");
var subparsers = parser.addSubparsers().title("subcommands").dest("command");
final Map<String, Command> commands = Commands.getCommands();
for (Map.Entry<String, Command> entry : commands.entrySet()) {
Subparser subparser = subparsers.addParser(entry.getKey());
final var commands = Commands.getCommands();
for (var entry : commands.entrySet()) {
var subparser = subparsers.addParser(entry.getKey());
entry.getValue().attachToSubparser(subparser);
}
@ -84,8 +80,8 @@ public class App {
}
public int init() {
String commandKey = ns.getString("command");
Command command = Commands.getCommand(commandKey);
var commandKey = ns.getString("command");
var command = Commands.getCommand(commandKey);
if (command == null) {
logger.error("Command not implemented!");
return 1;
@ -97,7 +93,7 @@ public class App {
return 1;
}
String username = ns.getString("username");
var username = ns.getString("username");
final boolean useDbus = ns.getBoolean("dbus");
final boolean useDbusSystem = ns.getBoolean("dbus_system");
@ -107,14 +103,14 @@ public class App {
}
final File dataPath;
String config = ns.getString("config");
var config = ns.getString("config");
if (config != null) {
dataPath = new File(config);
} else {
dataPath = getDefaultDataPath();
}
final ServiceEnvironment serviceEnvironment = ServiceEnvironment.LIVE;
final var serviceEnvironment = ServiceEnvironment.LIVE;
if (!ServiceConfig.getCapabilities().isGv2()) {
logger.warn("WARNING: Support for new group V2 is disabled,"
@ -136,7 +132,7 @@ public class App {
}
if (username == null) {
List<String> usernames = Manager.getAllLocalUsernames(dataPath);
var usernames = Manager.getAllLocalUsernames(dataPath);
if (usernames.size() == 0) {
System.err.println("No local users found, you first need to register or link an account");
return 1;
@ -172,7 +168,7 @@ public class App {
private int handleProvisioningCommand(
final ProvisioningCommand command, final File dataPath, final ServiceEnvironment serviceEnvironment
) {
ProvisioningManager pm = ProvisioningManager.init(dataPath, serviceEnvironment, BaseConfig.USER_AGENT);
var pm = ProvisioningManager.init(dataPath, serviceEnvironment, BaseConfig.USER_AGENT);
return command.handleCommand(ns, pm);
}
@ -189,7 +185,7 @@ public class App {
logger.error("Error loading or creating state file: {}", e.getMessage());
return 2;
}
try (RegistrationManager m = manager) {
try (var m = manager) {
return command.handleCommand(ns, m);
} catch (IOException e) {
logger.error("Cleanup failed", e);
@ -203,7 +199,7 @@ public class App {
final File dataPath,
final ServiceEnvironment serviceEnvironment
) {
try (Manager m = loadManager(username, dataPath, serviceEnvironment)) {
try (var m = loadManager(username, dataPath, serviceEnvironment)) {
if (m == null) {
return 2;
}
@ -221,14 +217,14 @@ public class App {
final ServiceEnvironment serviceEnvironment,
final List<String> usernames
) {
final List<Manager> managers = usernames.stream()
final var managers = usernames.stream()
.map(u -> loadManager(u, dataPath, serviceEnvironment))
.filter(Objects::nonNull)
.collect(Collectors.toList());
int result = command.handleCommand(ns, managers);
var result = command.handleCommand(ns, managers);
for (Manager m : managers) {
for (var m : managers) {
try {
m.close();
} catch (IOException e) {
@ -270,8 +266,8 @@ public class App {
} else {
busType = DBusConnection.DBusBusType.SESSION;
}
try (DBusConnection dBusConn = DBusConnection.getConnection(busType)) {
Signal ts = dBusConn.getRemoteObject(DbusConfig.getBusname(),
try (var dBusConn = DBusConnection.getConnection(busType)) {
var ts = dBusConn.getRemoteObject(DbusConfig.getBusname(),
DbusConfig.getObjectPath(username),
Signal.class);
@ -302,14 +298,14 @@ public class App {
* @return the data directory to be used by signal-cli.
*/
private static File getDefaultDataPath() {
File dataPath = new File(IOUtils.getDataHomeDir(), "signal-cli");
var dataPath = new File(IOUtils.getDataHomeDir(), "signal-cli");
if (dataPath.exists()) {
return dataPath;
}
File configPath = new File(System.getProperty("user.home"), ".config");
var configPath = new File(System.getProperty("user.home"), ".config");
File legacySettingsPath = new File(configPath, "signal");
var legacySettingsPath = new File(configPath, "signal");
if (legacySettingsPath.exists()) {
return legacySettingsPath;
}

View file

@ -5,15 +5,10 @@ import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.groups.GroupUtils;
import org.freedesktop.dbus.connections.impl.DBusConnection;
import org.freedesktop.dbus.exceptions.DBusException;
import org.whispersystems.signalservice.api.messages.SignalServiceAttachment;
import org.whispersystems.signalservice.api.messages.SignalServiceContent;
import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage;
import org.whispersystems.signalservice.api.messages.SignalServiceEnvelope;
import org.whispersystems.signalservice.api.messages.SignalServiceGroup;
import org.whispersystems.signalservice.api.messages.SignalServiceReceiptMessage;
import org.whispersystems.signalservice.api.messages.multidevice.SentTranscriptMessage;
import org.whispersystems.signalservice.api.messages.multidevice.SignalServiceSyncMessage;
import org.whispersystems.signalservice.api.push.SignalServiceAddress;
import java.util.ArrayList;
import java.util.List;
@ -46,11 +41,11 @@ public class JsonDbusReceiveMessageHandler extends JsonReceiveMessageHandler {
e.printStackTrace();
}
} else if (content != null) {
final SignalServiceAddress sender = !envelope.isUnidentifiedSender() && envelope.hasSource()
final var sender = !envelope.isUnidentifiedSender() && envelope.hasSource()
? envelope.getSourceAddress()
: content.getSender();
if (content.getReceiptMessage().isPresent()) {
final SignalServiceReceiptMessage receiptMessage = content.getReceiptMessage().get();
final var receiptMessage = content.getReceiptMessage().get();
if (receiptMessage.isDeliveryReceipt()) {
for (long timestamp : receiptMessage.getTimestamps()) {
try {
@ -63,9 +58,9 @@ public class JsonDbusReceiveMessageHandler extends JsonReceiveMessageHandler {
}
}
} else if (content.getDataMessage().isPresent()) {
SignalServiceDataMessage message = content.getDataMessage().get();
var message = content.getDataMessage().get();
byte[] groupId = getGroupId(message);
var groupId = getGroupId(message);
if (!message.isEndSession() && (
groupId == null
|| message.getGroupContext().get().getGroupV1Type() == null
@ -83,15 +78,15 @@ public class JsonDbusReceiveMessageHandler extends JsonReceiveMessageHandler {
}
}
} else if (content.getSyncMessage().isPresent()) {
SignalServiceSyncMessage sync_message = content.getSyncMessage().get();
var sync_message = content.getSyncMessage().get();
if (sync_message.getSent().isPresent()) {
SentTranscriptMessage transcript = sync_message.getSent().get();
var transcript = sync_message.getSent().get();
if (transcript.getDestination().isPresent() || transcript.getMessage()
.getGroupContext()
.isPresent()) {
SignalServiceDataMessage message = transcript.getMessage();
byte[] groupId = getGroupId(message);
var message = transcript.getMessage();
var groupId = getGroupId(message);
try {
conn.sendMessage(new Signal.SyncMessageReceived(objectPath,
@ -118,9 +113,9 @@ public class JsonDbusReceiveMessageHandler extends JsonReceiveMessageHandler {
}
static private List<String> getAttachments(SignalServiceDataMessage message, Manager m) {
List<String> attachments = new ArrayList<>();
var attachments = new ArrayList<String>();
if (message.getAttachments().isPresent()) {
for (SignalServiceAttachment attachment : message.getAttachments().get()) {
for (var attachment : message.getAttachments().get()) {
if (attachment.isPointer()) {
attachments.add(m.getAttachmentFile(attachment.asPointer().getRemoteId()).getAbsolutePath());
}

View file

@ -10,7 +10,6 @@ import org.whispersystems.signalservice.api.messages.SignalServiceEnvelope;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class JsonReceiveMessageHandler implements Manager.ReceiveMessageHandler {
@ -26,7 +25,7 @@ public class JsonReceiveMessageHandler implements Manager.ReceiveMessageHandler
@Override
public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
final Map<String, Object> object = new HashMap<>();
final var object = new HashMap<String, Object>();
if (exception != null) {
object.put("error", new JsonError(exception));
}

View file

@ -18,7 +18,6 @@ package org.asamk.signal;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;
@ -36,11 +35,11 @@ public class Main {
// Configuring the logger needs to happen before any logger is initialized
configureLogging(isVerbose(args));
ArgumentParser parser = App.buildArgumentParser();
var parser = App.buildArgumentParser();
Namespace ns = parser.parseArgsOrFail(args);
var ns = parser.parseArgsOrFail(args);
int res = new App(ns).init();
var res = new App(ns).init();
System.exit(res);
}
@ -51,7 +50,7 @@ public class Main {
}
private static boolean isVerbose(String[] args) {
ArgumentParser parser = ArgumentParsers.newFor("signal-cli").build().defaultHelp(false);
var parser = ArgumentParsers.newFor("signal-cli").build().defaultHelp(false);
parser.addArgument("--verbose").action(Arguments.storeTrue());
Namespace ns;

View file

@ -20,7 +20,7 @@ public final class PlainTextWriterImpl implements PlainTextWriter {
@Override
public void println(String format, Object... args) throws IOException {
final String message = MessageFormatter.arrayFormat(format, args).getMessage();
final var message = MessageFormatter.arrayFormat(format, args).getMessage();
writer.write(message);
writer.write(System.lineSeparator());

View file

@ -3,46 +3,24 @@ package org.asamk.signal;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.groups.GroupId;
import org.asamk.signal.manager.groups.GroupUtils;
import org.asamk.signal.manager.storage.groups.GroupInfo;
import org.asamk.signal.util.DateUtils;
import org.asamk.signal.util.Util;
import org.slf4j.helpers.MessageFormatter;
import org.whispersystems.libsignal.UntrustedIdentityException;
import org.whispersystems.signalservice.api.messages.SignalServiceAttachment;
import org.whispersystems.signalservice.api.messages.SignalServiceAttachmentPointer;
import org.whispersystems.signalservice.api.messages.SignalServiceContent;
import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage;
import org.whispersystems.signalservice.api.messages.SignalServiceEnvelope;
import org.whispersystems.signalservice.api.messages.SignalServiceGroup;
import org.whispersystems.signalservice.api.messages.SignalServiceGroupContext;
import org.whispersystems.signalservice.api.messages.SignalServiceGroupV2;
import org.whispersystems.signalservice.api.messages.SignalServiceReceiptMessage;
import org.whispersystems.signalservice.api.messages.SignalServiceTypingMessage;
import org.whispersystems.signalservice.api.messages.calls.AnswerMessage;
import org.whispersystems.signalservice.api.messages.calls.BusyMessage;
import org.whispersystems.signalservice.api.messages.calls.HangupMessage;
import org.whispersystems.signalservice.api.messages.calls.IceUpdateMessage;
import org.whispersystems.signalservice.api.messages.calls.OfferMessage;
import org.whispersystems.signalservice.api.messages.calls.OpaqueMessage;
import org.whispersystems.signalservice.api.messages.calls.SignalServiceCallMessage;
import org.whispersystems.signalservice.api.messages.multidevice.BlockedListMessage;
import org.whispersystems.signalservice.api.messages.multidevice.ConfigurationMessage;
import org.whispersystems.signalservice.api.messages.multidevice.ContactsMessage;
import org.whispersystems.signalservice.api.messages.multidevice.KeysMessage;
import org.whispersystems.signalservice.api.messages.multidevice.MessageRequestResponseMessage;
import org.whispersystems.signalservice.api.messages.multidevice.ReadMessage;
import org.whispersystems.signalservice.api.messages.multidevice.SentTranscriptMessage;
import org.whispersystems.signalservice.api.messages.multidevice.SignalServiceSyncMessage;
import org.whispersystems.signalservice.api.messages.multidevice.StickerPackOperationMessage;
import org.whispersystems.signalservice.api.messages.multidevice.VerifiedMessage;
import org.whispersystems.signalservice.api.messages.multidevice.ViewOnceOpenMessage;
import org.whispersystems.signalservice.api.messages.shared.SharedContact;
import org.whispersystems.signalservice.api.push.SignalServiceAddress;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import java.util.List;
import java.util.stream.Collectors;
public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
@ -68,7 +46,7 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
PlainTextWriter writer = new PlainTextWriterImpl(System.out);
if (envelope.hasSource()) {
SignalServiceAddress source = envelope.getSourceAddress();
var source = envelope.getSourceAddress();
writer.println("Envelope from: {} (device: {})", formatContact(source), envelope.getSourceDevice());
if (source.getRelay().isPresent()) {
writer.println("Relayed by: {}", source.getRelay().get());
@ -86,7 +64,7 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
} else if (envelope.isSignalMessage() || envelope.isPreKeySignalMessage() || envelope.isUnidentifiedSender()) {
if (exception != null) {
if (exception instanceof UntrustedIdentityException) {
UntrustedIdentityException e = (UntrustedIdentityException) exception;
var e = (UntrustedIdentityException) exception;
writer.println(
"The users key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
writer.println(
@ -112,28 +90,28 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
DateUtils.formatTimestamp(content.getServerDeliveredTimestamp()));
if (content.getDataMessage().isPresent()) {
SignalServiceDataMessage message = content.getDataMessage().get();
var message = content.getDataMessage().get();
printDataMessage(writer, message);
}
if (content.getSyncMessage().isPresent()) {
writer.println("Received a sync message");
SignalServiceSyncMessage syncMessage = content.getSyncMessage().get();
var syncMessage = content.getSyncMessage().get();
printSyncMessage(writer, syncMessage);
}
if (content.getCallMessage().isPresent()) {
writer.println("Received a call message");
SignalServiceCallMessage callMessage = content.getCallMessage().get();
var callMessage = content.getCallMessage().get();
printCallMessage(writer.indentedWriter(), callMessage);
}
if (content.getReceiptMessage().isPresent()) {
writer.println("Received a receipt message");
SignalServiceReceiptMessage receiptMessage = content.getReceiptMessage().get();
var receiptMessage = content.getReceiptMessage().get();
printReceiptMessage(writer.indentedWriter(), receiptMessage);
}
if (content.getTypingMessage().isPresent()) {
writer.println("Received a typing message");
SignalServiceTypingMessage typingMessage = content.getTypingMessage().get();
var typingMessage = content.getTypingMessage().get();
printTypingMessage(writer.indentedWriter(), typingMessage);
}
}
@ -156,32 +134,32 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
}
if (message.getGroupContext().isPresent()) {
writer.println("Group info:");
final SignalServiceGroupContext groupContext = message.getGroupContext().get();
final var groupContext = message.getGroupContext().get();
printGroupContext(writer.indentedWriter(), groupContext);
}
if (message.getGroupCallUpdate().isPresent()) {
writer.println("Group call update:");
final SignalServiceDataMessage.GroupCallUpdate groupCallUpdate = message.getGroupCallUpdate().get();
final var groupCallUpdate = message.getGroupCallUpdate().get();
writer.indentedWriter().println("Era id: {}", groupCallUpdate.getEraId());
}
if (message.getPreviews().isPresent()) {
writer.println("Previews:");
final List<SignalServiceDataMessage.Preview> previews = message.getPreviews().get();
for (SignalServiceDataMessage.Preview preview : previews) {
final var previews = message.getPreviews().get();
for (var preview : previews) {
writer.println("- Preview");
printPreview(writer.indentedWriter(), preview);
}
}
if (message.getSharedContacts().isPresent()) {
final List<SharedContact> sharedContacts = message.getSharedContacts().get();
final var sharedContacts = message.getSharedContacts().get();
writer.println("Contacts:");
for (SharedContact contact : sharedContacts) {
for (var contact : sharedContacts) {
writer.println("- Contact:");
printSharedContact(writer.indentedWriter(), contact);
}
}
if (message.getSticker().isPresent()) {
final SignalServiceDataMessage.Sticker sticker = message.getSticker().get();
final var sticker = message.getSticker().get();
writer.println("Sticker:");
printSticker(writer.indentedWriter(), sticker);
}
@ -199,27 +177,27 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
}
if (message.getReaction().isPresent()) {
writer.println("Reaction:");
final SignalServiceDataMessage.Reaction reaction = message.getReaction().get();
final var reaction = message.getReaction().get();
printReaction(writer.indentedWriter(), reaction);
}
if (message.getQuote().isPresent()) {
writer.println("Quote:");
SignalServiceDataMessage.Quote quote = message.getQuote().get();
var quote = message.getQuote().get();
printQuote(writer.indentedWriter(), quote);
}
if (message.getRemoteDelete().isPresent()) {
final SignalServiceDataMessage.RemoteDelete remoteDelete = message.getRemoteDelete().get();
final var remoteDelete = message.getRemoteDelete().get();
writer.println("Remote delete message: timestamp = {}", remoteDelete.getTargetSentTimestamp());
}
if (message.getMentions().isPresent()) {
writer.println("Mentions:");
for (SignalServiceDataMessage.Mention mention : message.getMentions().get()) {
for (var mention : message.getMentions().get()) {
printMention(writer, mention);
}
}
if (message.getAttachments().isPresent()) {
writer.println("Attachments:");
for (SignalServiceAttachment attachment : message.getAttachments().get()) {
for (var attachment : message.getAttachments().get()) {
writer.println("- Attachment:");
printAttachment(writer.indentedWriter(), attachment);
}
@ -233,7 +211,7 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
writer.println("Timestamp: {}", DateUtils.formatTimestamp(typingMessage.getTimestamp()));
if (typingMessage.getGroupId().isPresent()) {
writer.println("Group Info:");
final GroupId groupId = GroupId.unknownVersion(typingMessage.getGroupId().get());
final var groupId = GroupId.unknownVersion(typingMessage.getGroupId().get());
printGroupInfo(writer.indentedWriter(), groupId);
}
}
@ -261,34 +239,34 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
final PlainTextWriter writer, final SignalServiceCallMessage callMessage
) throws IOException {
if (callMessage.getDestinationDeviceId().isPresent()) {
final Integer deviceId = callMessage.getDestinationDeviceId().get();
final var deviceId = callMessage.getDestinationDeviceId().get();
writer.println("Destination device id: {}", deviceId);
}
if (callMessage.getAnswerMessage().isPresent()) {
AnswerMessage answerMessage = callMessage.getAnswerMessage().get();
var answerMessage = callMessage.getAnswerMessage().get();
writer.println("Answer message: {}, sdp: {})", answerMessage.getId(), answerMessage.getSdp());
}
if (callMessage.getBusyMessage().isPresent()) {
BusyMessage busyMessage = callMessage.getBusyMessage().get();
var busyMessage = callMessage.getBusyMessage().get();
writer.println("Busy message: {}", busyMessage.getId());
}
if (callMessage.getHangupMessage().isPresent()) {
HangupMessage hangupMessage = callMessage.getHangupMessage().get();
var hangupMessage = callMessage.getHangupMessage().get();
writer.println("Hangup message: {}", hangupMessage.getId());
}
if (callMessage.getIceUpdateMessages().isPresent()) {
writer.println("Ice update messages:");
List<IceUpdateMessage> iceUpdateMessages = callMessage.getIceUpdateMessages().get();
for (IceUpdateMessage iceUpdateMessage : iceUpdateMessages) {
var iceUpdateMessages = callMessage.getIceUpdateMessages().get();
for (var iceUpdateMessage : iceUpdateMessages) {
writer.println("- {}, sdp: {}", iceUpdateMessage.getId(), iceUpdateMessage.getSdp());
}
}
if (callMessage.getOfferMessage().isPresent()) {
OfferMessage offerMessage = callMessage.getOfferMessage().get();
var offerMessage = callMessage.getOfferMessage().get();
writer.println("Offer message: {}, sdp: {}", offerMessage.getId(), offerMessage.getSdp());
}
if (callMessage.getOpaqueMessage().isPresent()) {
final OpaqueMessage opaqueMessage = callMessage.getOpaqueMessage().get();
final var opaqueMessage = callMessage.getOpaqueMessage().get();
writer.println("Opaque message: size {}", opaqueMessage.getOpaque().length);
}
}
@ -297,8 +275,8 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
final PlainTextWriter writer, final SignalServiceSyncMessage syncMessage
) throws IOException {
if (syncMessage.getContacts().isPresent()) {
final ContactsMessage contactsMessage = syncMessage.getContacts().get();
String type = contactsMessage.isComplete() ? "complete" : "partial";
final var contactsMessage = syncMessage.getContacts().get();
var type = contactsMessage.isComplete() ? "complete" : "partial";
writer.println("Received {} sync contacts:", type);
printAttachment(writer.indentedWriter(), contactsMessage.getContactsStream());
}
@ -308,7 +286,7 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
}
if (syncMessage.getRead().isPresent()) {
writer.println("Received sync read messages list");
for (ReadMessage rm : syncMessage.getRead().get()) {
for (var rm : syncMessage.getRead().get()) {
writer.println("- From: {} Message timestamp: {}",
formatContact(rm.getSender()),
DateUtils.formatTimestamp(rm.getTimestamp()));
@ -333,7 +311,7 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
}
if (syncMessage.getSent().isPresent()) {
writer.println("Received sync sent message");
final SentTranscriptMessage sentTranscriptMessage = syncMessage.getSent().get();
final var sentTranscriptMessage = syncMessage.getSent().get();
String to;
if (sentTranscriptMessage.getDestination().isPresent()) {
to = formatContact(sentTranscriptMessage.getDestination().get());
@ -353,28 +331,28 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
.println("Expiration started at: {}",
DateUtils.formatTimestamp(sentTranscriptMessage.getExpirationStartTimestamp()));
}
SignalServiceDataMessage message = sentTranscriptMessage.getMessage();
var message = sentTranscriptMessage.getMessage();
printDataMessage(writer.indentedWriter(), message);
}
if (syncMessage.getBlockedList().isPresent()) {
writer.println("Received sync message with block list");
writer.println("Blocked numbers:");
final BlockedListMessage blockedList = syncMessage.getBlockedList().get();
for (SignalServiceAddress address : blockedList.getAddresses()) {
final var blockedList = syncMessage.getBlockedList().get();
for (var address : blockedList.getAddresses()) {
writer.println("- {}", address.getLegacyIdentifier());
}
}
if (syncMessage.getVerified().isPresent()) {
writer.println("Received sync message with verified identities:");
final VerifiedMessage verifiedMessage = syncMessage.getVerified().get();
final var verifiedMessage = syncMessage.getVerified().get();
writer.println("- {}: {}", formatContact(verifiedMessage.getDestination()), verifiedMessage.getVerified());
String safetyNumber = Util.formatSafetyNumber(m.computeSafetyNumber(verifiedMessage.getDestination(),
var safetyNumber = Util.formatSafetyNumber(m.computeSafetyNumber(verifiedMessage.getDestination(),
verifiedMessage.getIdentityKey()));
writer.indentedWriter().println(safetyNumber);
}
if (syncMessage.getConfiguration().isPresent()) {
writer.println("Received sync message with configuration:");
final ConfigurationMessage configurationMessage = syncMessage.getConfiguration().get();
final var configurationMessage = syncMessage.getConfiguration().get();
if (configurationMessage.getReadReceipts().isPresent()) {
writer.println("- Read receipts: {}",
configurationMessage.getReadReceipts().get() ? "enabled" : "disabled");
@ -393,21 +371,20 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
}
}
if (syncMessage.getFetchType().isPresent()) {
final SignalServiceSyncMessage.FetchType fetchType = syncMessage.getFetchType().get();
final var fetchType = syncMessage.getFetchType().get();
writer.println("Received sync message with fetch type: {}", fetchType);
}
if (syncMessage.getViewOnceOpen().isPresent()) {
final ViewOnceOpenMessage viewOnceOpenMessage = syncMessage.getViewOnceOpen().get();
final var viewOnceOpenMessage = syncMessage.getViewOnceOpen().get();
writer.println("Received sync message with view once open message:");
writer.indentedWriter().println("Sender: {}", formatContact(viewOnceOpenMessage.getSender()));
writer.indentedWriter()
.println("Timestamp: {}", DateUtils.formatTimestamp(viewOnceOpenMessage.getTimestamp()));
}
if (syncMessage.getStickerPackOperations().isPresent()) {
final List<StickerPackOperationMessage> stickerPackOperationMessages = syncMessage.getStickerPackOperations()
.get();
final var stickerPackOperationMessages = syncMessage.getStickerPackOperations().get();
writer.println("Received sync message with sticker pack operations:");
for (StickerPackOperationMessage m : stickerPackOperationMessages) {
for (var m : stickerPackOperationMessages) {
writer.println("- {}", m.getType().isPresent() ? m.getType().get() : "<unknown>");
if (m.getPackId().isPresent()) {
writer.indentedWriter()
@ -420,7 +397,7 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
}
}
if (syncMessage.getMessageRequestResponse().isPresent()) {
final MessageRequestResponseMessage requestResponseMessage = syncMessage.getMessageRequestResponse().get();
final var requestResponseMessage = syncMessage.getMessageRequestResponse().get();
writer.println("Received message request response:");
writer.indentedWriter().println("Type: {}", requestResponseMessage.getType());
if (requestResponseMessage.getGroupId().isPresent()) {
@ -434,7 +411,7 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
}
}
if (syncMessage.getKeys().isPresent()) {
final KeysMessage keysMessage = syncMessage.getKeys().get();
final var keysMessage = syncMessage.getKeys().get();
writer.println("Received sync message with keys:");
if (keysMessage.getStorageService().isPresent()) {
writer.println("- storage key: length: {}", keysMessage.getStorageService().get().serialize().length);
@ -482,13 +459,13 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
writer.println("Text: {}", quote.getText());
if (quote.getMentions() != null && quote.getMentions().size() > 0) {
writer.println("Mentions:");
for (SignalServiceDataMessage.Mention mention : quote.getMentions()) {
for (var mention : quote.getMentions()) {
printMention(writer, mention);
}
}
if (quote.getAttachments().size() > 0) {
writer.println("Attachments:");
for (SignalServiceDataMessage.Quote.QuotedAttachment attachment : quote.getAttachments()) {
for (var attachment : quote.getAttachments()) {
writer.println("- Filename: {}", attachment.getFileName());
writer.indent(w -> {
w.println("Type: {}", attachment.getContentType());
@ -503,7 +480,7 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
private void printSharedContact(final PlainTextWriter writer, final SharedContact contact) throws IOException {
writer.println("Name:");
SharedContact.Name name = contact.getName();
var name = contact.getName();
writer.indent(w -> {
if (name.getDisplay().isPresent() && !name.getDisplay().get().isBlank()) {
w.println("Display name: {}", name.getDisplay().get());
@ -526,7 +503,7 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
});
if (contact.getAvatar().isPresent()) {
SharedContact.Avatar avatar = contact.getAvatar().get();
var avatar = contact.getAvatar().get();
writer.println("Avatar: (profile: {})", avatar.isProfile());
printAttachment(writer.indentedWriter(), avatar.getAttachment());
}
@ -537,7 +514,7 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
if (contact.getPhone().isPresent()) {
writer.println("Phone details:");
for (SharedContact.Phone phone : contact.getPhone().get()) {
for (var phone : contact.getPhone().get()) {
writer.println("- Phone:");
writer.indent(w -> {
if (phone.getValue() != null) {
@ -555,7 +532,7 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
if (contact.getEmail().isPresent()) {
writer.println("Email details:");
for (SharedContact.Email email : contact.getEmail().get()) {
for (var email : contact.getEmail().get()) {
writer.println("- Email:");
writer.indent(w -> {
if (email.getValue() != null) {
@ -573,7 +550,7 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
if (contact.getAddress().isPresent()) {
writer.println("Address details:");
for (SharedContact.PostalAddress address : contact.getAddress().get()) {
for (var address : contact.getAddress().get()) {
writer.println("- Address:");
writer.indent(w -> {
if (address.getType() != null) {
@ -611,14 +588,14 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
private void printGroupContext(
final PlainTextWriter writer, final SignalServiceGroupContext groupContext
) throws IOException {
final GroupId groupId = GroupUtils.getGroupId(groupContext);
final var groupId = GroupUtils.getGroupId(groupContext);
if (groupContext.getGroupV1().isPresent()) {
SignalServiceGroup groupInfo = groupContext.getGroupV1().get();
var groupInfo = groupContext.getGroupV1().get();
printGroupInfo(writer, groupId);
writer.println("Type: {}", groupInfo.getType());
if (groupInfo.getMembers().isPresent()) {
writer.println("Members:");
for (SignalServiceAddress member : groupInfo.getMembers().get()) {
for (var member : groupInfo.getMembers().get()) {
writer.println("- {}", formatContact(member));
}
}
@ -627,7 +604,7 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
printAttachment(writer.indentedWriter(), groupInfo.getAvatar().get());
}
} else if (groupContext.getGroupV2().isPresent()) {
final SignalServiceGroupV2 groupInfo = groupContext.getGroupV2().get();
final var groupInfo = groupContext.getGroupV2().get();
printGroupInfo(writer, groupId);
writer.println("Revision: {}", groupInfo.getRevision());
writer.println("Master key length: {}", groupInfo.getMasterKey().serialize().length);
@ -638,7 +615,7 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
private void printGroupInfo(final PlainTextWriter writer, final GroupId groupId) throws IOException {
writer.println("Id: {}", groupId.toBase64());
GroupInfo group = m.getGroup(groupId);
var group = m.getGroup(groupId);
if (group != null) {
writer.println("Name: {}", group.getTitle());
} else {
@ -649,8 +626,7 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
private void printMention(
PlainTextWriter writer, SignalServiceDataMessage.Mention mention
) throws IOException {
final SignalServiceAddress address = m.resolveSignalServiceAddress(new SignalServiceAddress(mention.getUuid(),
null));
final var address = m.resolveSignalServiceAddress(new SignalServiceAddress(mention.getUuid(), null));
writer.println("- {}: {} (length: {})", formatContact(address), mention.getStart(), mention.getLength());
}
@ -658,7 +634,7 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
writer.println("Content-Type: {}", attachment.getContentType());
writer.println("Type: {}", attachment.isPointer() ? "Pointer" : attachment.isStream() ? "Stream" : "<unknown>");
if (attachment.isPointer()) {
final SignalServiceAttachmentPointer pointer = attachment.asPointer();
final var pointer = attachment.asPointer();
writer.println("Id: {} Key length: {}", pointer.getRemoteId(), pointer.getKey().length);
if (pointer.getUploadTimestamp() > 0) {
writer.println("Upload timestamp: {}", DateUtils.formatTimestamp(pointer.getUploadTimestamp()));
@ -679,7 +655,7 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
if (pointer.getWidth() > 0 || pointer.getHeight() > 0) {
writer.println("Dimensions: {}x{}", pointer.getWidth(), pointer.getHeight());
}
File file = m.getAttachmentFile(pointer.getRemoteId());
var file = m.getAttachmentFile(pointer.getRemoteId());
if (file.exists()) {
writer.println("Stored plaintext in: {}", file);
}
@ -687,8 +663,8 @@ public class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
}
private String formatContact(SignalServiceAddress address) {
final String number = address.getLegacyIdentifier();
String name = m.getContactOrProfileName(number);
final var number = address.getLegacyIdentifier();
var name = m.getContactOrProfileName(number);
if (name == null) {
return number;
} else {

View file

@ -4,7 +4,6 @@ import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.groups.GroupId;
import org.asamk.signal.manager.groups.GroupIdFormatException;
import org.asamk.signal.manager.groups.GroupNotFoundException;
import org.asamk.signal.util.Util;
@ -21,7 +20,7 @@ public class BlockCommand implements LocalCommand {
@Override
public int handleCommand(final Namespace ns, final Manager m) {
for (String contact_number : ns.<String>getList("contact")) {
for (var contact_number : ns.<String>getList("contact")) {
try {
m.setContactBlocked(contact_number, true);
} catch (InvalidNumberException e) {
@ -30,9 +29,9 @@ public class BlockCommand implements LocalCommand {
}
if (ns.<String>getList("group") != null) {
for (String groupIdString : ns.<String>getList("group")) {
for (var groupIdString : ns.<String>getList("group")) {
try {
GroupId groupId = Util.decodeGroupId(groupIdString);
var groupId = Util.decodeGroupId(groupIdString);
m.setGroupBlocked(groupId, true);
} catch (GroupIdFormatException | GroupNotFoundException e) {
System.err.println(e.getMessage());

View file

@ -45,7 +45,7 @@ public class DaemonCommand implements MultiLocalCommand {
@Override
public int handleCommand(final Namespace ns, final Manager m) {
boolean inJson = ns.get("output") == OutputType.JSON || ns.getBoolean("json");
var inJson = ns.get("output") == OutputType.JSON || ns.getBoolean("json");
// TODO delete later when "json" variable is removed
if (ns.getBoolean("json")) {
@ -61,9 +61,9 @@ public class DaemonCommand implements MultiLocalCommand {
busType = DBusConnection.DBusBusType.SESSION;
}
try (DBusConnection conn = DBusConnection.getConnection(busType)) {
String objectPath = DbusConfig.getObjectPath();
Thread t = run(conn, objectPath, m, ignoreAttachments, inJson);
try (var conn = DBusConnection.getConnection(busType)) {
var objectPath = DbusConfig.getObjectPath();
var t = run(conn, objectPath, m, ignoreAttachments, inJson);
conn.requestBusName(DbusConfig.getBusname());
@ -80,7 +80,7 @@ public class DaemonCommand implements MultiLocalCommand {
@Override
public int handleCommand(final Namespace ns, final List<Manager> managers) {
boolean inJson = ns.get("output") == OutputType.JSON || ns.getBoolean("json");
var inJson = ns.get("output") == OutputType.JSON || ns.getBoolean("json");
// TODO delete later when "json" variable is removed
if (ns.getBoolean("json")) {
@ -96,17 +96,17 @@ public class DaemonCommand implements MultiLocalCommand {
busType = DBusConnection.DBusBusType.SESSION;
}
try (DBusConnection conn = DBusConnection.getConnection(busType)) {
List<Thread> receiveThreads = new ArrayList<>();
for (Manager m : managers) {
String objectPath = DbusConfig.getObjectPath(m.getUsername());
Thread thread = run(conn, objectPath, m, ignoreAttachments, inJson);
try (var conn = DBusConnection.getConnection(busType)) {
var receiveThreads = new ArrayList<Thread>();
for (var m : managers) {
var objectPath = DbusConfig.getObjectPath(m.getUsername());
var thread = run(conn, objectPath, m, ignoreAttachments, inJson);
receiveThreads.add(thread);
}
conn.requestBusName(DbusConfig.getBusname());
for (Thread t : receiveThreads) {
for (var t : receiveThreads) {
try {
t.join();
} catch (InterruptedException ignored) {
@ -124,7 +124,7 @@ public class DaemonCommand implements MultiLocalCommand {
) throws DBusException {
conn.exportObject(objectPath, new DbusSignalImpl(m));
final Thread thread = new Thread(() -> {
final var thread = new Thread(() -> {
while (true) {
try {
m.receiveMessages(1,

View file

@ -12,7 +12,6 @@ import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@ -38,7 +37,7 @@ public class GetUserStatusCommand implements LocalCommand {
@Override
public int handleCommand(final Namespace ns, final Manager m) {
// Setup the json object mapper
boolean inJson = ns.get("output") == OutputType.JSON || ns.getBoolean("json");
var inJson = ns.get("output") == OutputType.JSON || ns.getBoolean("json");
// TODO delete later when "json" variable is removed
if (ns.getBoolean("json")) {
@ -56,9 +55,9 @@ public class GetUserStatusCommand implements LocalCommand {
// Output
if (inJson) {
final JsonWriter jsonWriter = new JsonWriter(System.out);
final var jsonWriter = new JsonWriter(System.out);
List<JsonUserStatus> jsonUserStatuses = registered.entrySet()
var jsonUserStatuses = registered.entrySet()
.stream()
.map(entry -> new JsonUserStatus(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
@ -70,7 +69,7 @@ public class GetUserStatusCommand implements LocalCommand {
return 3;
}
} else {
for (Map.Entry<String, Boolean> entry : registered.entrySet()) {
for (var entry : registered.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}

View file

@ -4,16 +4,12 @@ import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.groups.GroupId;
import org.asamk.signal.manager.groups.GroupInviteLinkUrl;
import org.freedesktop.dbus.exceptions.DBusExecutionException;
import org.whispersystems.libsignal.util.Pair;
import org.whispersystems.signalservice.api.groupsv2.GroupLinkNotActiveException;
import org.whispersystems.signalservice.api.messages.SendMessageResult;
import org.whispersystems.signalservice.internal.push.exceptions.GroupPatchNotAcceptedException;
import java.io.IOException;
import java.util.List;
import static org.asamk.signal.util.ErrorUtils.handleAssertionError;
import static org.asamk.signal.util.ErrorUtils.handleIOException;
@ -29,7 +25,7 @@ public class JoinGroupCommand implements LocalCommand {
@Override
public int handleCommand(final Namespace ns, final Manager m) {
final GroupInviteLinkUrl linkUrl;
String uri = ns.getString("uri");
var uri = ns.getString("uri");
try {
linkUrl = GroupInviteLinkUrl.fromUri(uri);
} catch (GroupInviteLinkUrl.InvalidGroupLinkException e) {
@ -46,8 +42,8 @@ public class JoinGroupCommand implements LocalCommand {
}
try {
final Pair<GroupId, List<SendMessageResult>> results = m.joinGroup(linkUrl);
GroupId newGroupId = results.first();
final var results = m.joinGroup(linkUrl);
var newGroupId = results.first();
if (!m.getGroup(newGroupId).isMember(m.getSelfAddress())) {
System.out.println("Requested to join group \"" + newGroupId.toBase64() + "\"");
} else {

View file

@ -21,13 +21,13 @@ public class LinkCommand implements ProvisioningCommand {
@Override
public int handleCommand(final Namespace ns, final ProvisioningManager m) {
String deviceName = ns.getString("name");
var deviceName = ns.getString("name");
if (deviceName == null) {
deviceName = "cli";
}
try {
System.out.println(m.getDeviceLinkUri());
String username = m.finishDeviceLink(deviceName);
var username = m.finishDeviceLink(deviceName);
System.out.println("Associated with: " + username);
} catch (TimeoutException e) {
System.err.println("Link request timed out, please try again.");

View file

@ -4,9 +4,6 @@ import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.storage.contacts.ContactInfo;
import java.util.List;
public class ListContactsCommand implements LocalCommand {
@ -16,8 +13,8 @@ public class ListContactsCommand implements LocalCommand {
@Override
public int handleCommand(final Namespace ns, final Manager m) {
List<ContactInfo> contacts = m.getContacts();
for (ContactInfo c : contacts) {
var contacts = m.getContacts();
for (var c : contacts) {
System.out.println(String.format("Number: %s Name: %s Blocked: %b", c.number, c.name, c.blocked));
}
return 0;

View file

@ -5,10 +5,8 @@ import net.sourceforge.argparse4j.inf.Subparser;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.util.DateUtils;
import org.whispersystems.signalservice.api.messages.multidevice.DeviceInfo;
import java.io.IOException;
import java.util.List;
public class ListDevicesCommand implements LocalCommand {
@ -19,8 +17,8 @@ public class ListDevicesCommand implements LocalCommand {
@Override
public int handleCommand(final Namespace ns, final Manager m) {
try {
List<DeviceInfo> devices = m.getLinkedDevices();
for (DeviceInfo d : devices) {
var devices = m.getLinkedDevices();
for (var d : devices) {
System.out.println("Device "
+ d.getId()
+ (d.getId() == m.getDeviceId() ? " (this device)" : "")

View file

@ -7,7 +7,6 @@ import net.sourceforge.argparse4j.inf.Subparser;
import org.asamk.signal.JsonWriter;
import org.asamk.signal.OutputType;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.groups.GroupInviteLinkUrl;
import org.asamk.signal.manager.storage.groups.GroupInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -15,7 +14,6 @@ import org.whispersystems.signalservice.api.push.SignalServiceAddress;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@ -32,7 +30,7 @@ public class ListGroupsCommand implements LocalCommand {
private static void printGroupPlainText(Manager m, GroupInfo group, boolean detailed) {
if (detailed) {
final GroupInviteLinkUrl groupInviteLink = group.getGroupInviteLink();
final var groupInviteLink = group.getGroupInviteLink();
System.out.println(String.format(
"Id: %s Name: %s Active: %s Blocked: %b Members: %s Pending members: %s Requesting members: %s Link: %s",
@ -70,11 +68,11 @@ public class ListGroupsCommand implements LocalCommand {
@Override
public int handleCommand(final Namespace ns, final Manager m) {
if (ns.get("output") == OutputType.JSON) {
final JsonWriter jsonWriter = new JsonWriter(System.out);
final var jsonWriter = new JsonWriter(System.out);
List<JsonGroup> jsonGroups = new ArrayList<>();
for (GroupInfo group : m.getGroups()) {
final GroupInviteLinkUrl groupInviteLink = group.getGroupInviteLink();
var jsonGroups = new ArrayList<JsonGroup>();
for (var group : m.getGroups()) {
final var groupInviteLink = group.getGroupInviteLink();
jsonGroups.add(new JsonGroup(group.getGroupId().toBase64(),
group.getTitle(),
@ -96,7 +94,7 @@ public class ListGroupsCommand implements LocalCommand {
return 0;
} else {
boolean detailed = ns.getBoolean("detailed");
for (GroupInfo group : m.getGroups()) {
for (var group : m.getGroups()) {
printGroupPlainText(m, group, detailed);
}
}

View file

@ -9,12 +9,10 @@ import org.asamk.signal.util.Hex;
import org.asamk.signal.util.Util;
import org.whispersystems.signalservice.api.util.InvalidNumberException;
import java.util.List;
public class ListIdentitiesCommand implements LocalCommand {
private static void printIdentityFingerprint(Manager m, IdentityInfo theirId) {
String digits = Util.formatSafetyNumber(m.computeSafetyNumber(theirId.getAddress(), theirId.getIdentityKey()));
var digits = Util.formatSafetyNumber(m.computeSafetyNumber(theirId.getAddress(), theirId.getIdentityKey()));
System.out.println(String.format("%s: %s Added: %s Fingerprint: %s Safety Number: %s",
theirId.getAddress().getNumber().orNull(),
theirId.getTrustLevel(),
@ -31,14 +29,14 @@ public class ListIdentitiesCommand implements LocalCommand {
@Override
public int handleCommand(final Namespace ns, final Manager m) {
if (ns.get("number") == null) {
for (IdentityInfo identity : m.getIdentities()) {
for (var identity : m.getIdentities()) {
printIdentityFingerprint(m, identity);
}
} else {
String number = ns.getString("number");
var number = ns.getString("number");
try {
List<IdentityInfo> identities = m.getIdentities(number);
for (IdentityInfo id : identities) {
var identities = m.getIdentities(number);
for (var id : identities) {
printIdentityFingerprint(m, id);
}
} catch (InvalidNumberException e) {

View file

@ -4,16 +4,12 @@ import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.groups.GroupId;
import org.asamk.signal.manager.groups.GroupIdFormatException;
import org.asamk.signal.manager.groups.GroupNotFoundException;
import org.asamk.signal.manager.groups.NotAGroupMemberException;
import org.asamk.signal.util.Util;
import org.whispersystems.libsignal.util.Pair;
import org.whispersystems.signalservice.api.messages.SendMessageResult;
import java.io.IOException;
import java.util.List;
import static org.asamk.signal.util.ErrorUtils.handleAssertionError;
import static org.asamk.signal.util.ErrorUtils.handleGroupIdFormatException;
@ -32,8 +28,8 @@ public class QuitGroupCommand implements LocalCommand {
@Override
public int handleCommand(final Namespace ns, final Manager m) {
try {
final GroupId groupId = Util.decodeGroupId(ns.getString("group"));
final Pair<Long, List<SendMessageResult>> results = m.sendQuitGroupMessage(groupId);
final var groupId = Util.decodeGroupId(ns.getString("group"));
final var results = m.sendQuitGroupMessage(groupId);
return handleTimestampAndSendMessageResults(results.first(), results.second());
} catch (IOException e) {
handleIOException(e);

View file

@ -48,19 +48,19 @@ public class ReceiveCommand implements ExtendedDbusCommand, LocalCommand {
}
public int handleCommand(final Namespace ns, final Signal signal, DBusConnection dbusconnection) {
boolean inJson = ns.get("output") == OutputType.JSON || ns.getBoolean("json");
var inJson = ns.get("output") == OutputType.JSON || ns.getBoolean("json");
// TODO delete later when "json" variable is removed
if (ns.getBoolean("json")) {
logger.warn("\"--json\" option has been deprecated, please use the global \"--output=json\" instead.");
}
final JsonWriter jsonWriter = inJson ? new JsonWriter(System.out) : null;
final var jsonWriter = inJson ? new JsonWriter(System.out) : null;
try {
dbusconnection.addSigHandler(Signal.MessageReceived.class, messageReceived -> {
if (jsonWriter != null) {
JsonMessageEnvelope envelope = new JsonMessageEnvelope(messageReceived);
final Map<String, JsonMessageEnvelope> object = Map.of("envelope", envelope);
var envelope = new JsonMessageEnvelope(messageReceived);
final var object = Map.of("envelope", envelope);
try {
jsonWriter.write(object);
} catch (IOException e) {
@ -77,7 +77,7 @@ public class ReceiveCommand implements ExtendedDbusCommand, LocalCommand {
}
if (messageReceived.getAttachments().size() > 0) {
System.out.println("Attachments: ");
for (String attachment : messageReceived.getAttachments()) {
for (var attachment : messageReceived.getAttachments()) {
System.out.println("- Stored plaintext in: " + attachment);
}
}
@ -87,8 +87,8 @@ public class ReceiveCommand implements ExtendedDbusCommand, LocalCommand {
dbusconnection.addSigHandler(Signal.ReceiptReceived.class, receiptReceived -> {
if (jsonWriter != null) {
JsonMessageEnvelope envelope = new JsonMessageEnvelope(receiptReceived);
final Map<String, JsonMessageEnvelope> object = Map.of("envelope", envelope);
var envelope = new JsonMessageEnvelope(receiptReceived);
final var object = Map.of("envelope", envelope);
try {
jsonWriter.write(object);
} catch (IOException e) {
@ -103,8 +103,8 @@ public class ReceiveCommand implements ExtendedDbusCommand, LocalCommand {
dbusconnection.addSigHandler(Signal.SyncMessageReceived.class, syncReceived -> {
if (jsonWriter != null) {
JsonMessageEnvelope envelope = new JsonMessageEnvelope(syncReceived);
final Map<String, JsonMessageEnvelope> object = Map.of("envelope", envelope);
var envelope = new JsonMessageEnvelope(syncReceived);
final var object = Map.of("envelope", envelope);
try {
jsonWriter.write(object);
} catch (IOException e) {
@ -122,7 +122,7 @@ public class ReceiveCommand implements ExtendedDbusCommand, LocalCommand {
}
if (syncReceived.getAttachments().size() > 0) {
System.out.println("Attachments: ");
for (String attachment : syncReceived.getAttachments()) {
for (var attachment : syncReceived.getAttachments()) {
System.out.println("- Stored plaintext in: " + attachment);
}
}
@ -144,7 +144,7 @@ public class ReceiveCommand implements ExtendedDbusCommand, LocalCommand {
@Override
public int handleCommand(final Namespace ns, final Manager m) {
boolean inJson = ns.get("output") == OutputType.JSON || ns.getBoolean("json");
var inJson = ns.get("output") == OutputType.JSON || ns.getBoolean("json");
// TODO delete later when "json" variable is removed
if (ns.getBoolean("json")) {
@ -155,16 +155,14 @@ public class ReceiveCommand implements ExtendedDbusCommand, LocalCommand {
if (ns.getDouble("timeout") != null) {
timeout = ns.getDouble("timeout");
}
boolean returnOnTimeout = true;
var returnOnTimeout = true;
if (timeout < 0) {
returnOnTimeout = false;
timeout = 3600;
}
boolean ignoreAttachments = ns.getBoolean("ignore_attachments");
try {
final Manager.ReceiveMessageHandler handler = inJson
? new JsonReceiveMessageHandler(m)
: new ReceiveMessageHandler(m);
final var handler = inJson ? new JsonReceiveMessageHandler(m) : new ReceiveMessageHandler(m);
m.receiveMessages((long) (timeout * 1000),
TimeUnit.MILLISECONDS,
returnOnTimeout,

View file

@ -23,7 +23,7 @@ public class RegisterCommand implements RegistrationCommand {
@Override
public int handleCommand(final Namespace ns, final RegistrationManager m) {
final boolean voiceVerification = ns.getBoolean("voice");
final String captcha = ns.getString("captcha");
final var captcha = ns.getString("captcha");
try {
m.register(voiceVerification, captcha);

View file

@ -1,7 +1,6 @@
package org.asamk.signal.commands;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
@ -24,7 +23,7 @@ public class SendCommand implements DbusCommand {
@Override
public void attachToSubparser(final Subparser subparser) {
subparser.addArgument("recipient").help("Specify the recipients' phone number.").nargs("*");
final MutuallyExclusiveGroup mutuallyExclusiveGroup = subparser.addMutuallyExclusiveGroup();
final var mutuallyExclusiveGroup = subparser.addMutuallyExclusiveGroup();
mutuallyExclusiveGroup.addArgument("-g", "--group").help("Specify the recipient group ID.");
mutuallyExclusiveGroup.addArgument("--note-to-self")
.help("Send the message to self without notification.")
@ -40,11 +39,11 @@ public class SendCommand implements DbusCommand {
@Override
public int handleCommand(final Namespace ns, final Signal signal) {
final List<String> recipients = ns.getList("recipient");
final Boolean isEndSession = ns.getBoolean("endsession");
final String groupIdString = ns.getString("group");
final Boolean isNoteToSelf = ns.getBoolean("note_to_self");
final var isEndSession = ns.getBoolean("endsession");
final var groupIdString = ns.getString("group");
final var isNoteToSelf = ns.getBoolean("note_to_self");
final boolean noRecipients = recipients == null || recipients.isEmpty();
final var noRecipients = recipients == null || recipients.isEmpty();
if ((noRecipients && isEndSession) || (noRecipients && groupIdString == null && !isNoteToSelf)) {
System.err.println("No recipients given");
System.err.println("Aborting sending.");
@ -75,7 +74,7 @@ public class SendCommand implements DbusCommand {
}
}
String messageText = ns.getString("message");
var messageText = ns.getString("message");
if (messageText == null) {
try {
messageText = IOUtils.readAll(System.in, Charset.defaultCharset());
@ -101,7 +100,7 @@ public class SendCommand implements DbusCommand {
return 1;
}
long timestamp = signal.sendGroupMessage(messageText, attachments, groupId);
var timestamp = signal.sendGroupMessage(messageText, attachments, groupId);
System.out.println(timestamp);
return 0;
} catch (AssertionError e) {
@ -115,7 +114,7 @@ public class SendCommand implements DbusCommand {
if (isNoteToSelf) {
try {
long timestamp = signal.sendNoteToSelfMessage(messageText, attachments);
var timestamp = signal.sendNoteToSelfMessage(messageText, attachments);
System.out.println(timestamp);
return 0;
} catch (AssertionError e) {
@ -131,7 +130,7 @@ public class SendCommand implements DbusCommand {
}
try {
long timestamp = signal.sendMessage(messageText, attachments, recipients);
var timestamp = signal.sendMessage(messageText, attachments, recipients);
System.out.println(timestamp);
return 0;
} catch (AssertionError e) {

View file

@ -5,7 +5,6 @@ import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.groups.GroupId;
import org.asamk.signal.manager.groups.GroupIdFormatException;
import org.asamk.signal.manager.groups.GroupNotFoundException;
import org.asamk.signal.manager.groups.NotAGroupMemberException;
@ -48,9 +47,9 @@ public class SendReactionCommand implements LocalCommand {
@Override
public int handleCommand(final Namespace ns, final Manager m) {
final List<String> recipients = ns.getList("recipient");
final String groupIdString = ns.getString("group");
final var groupIdString = ns.getString("group");
final boolean noRecipients = recipients == null || recipients.isEmpty();
final var noRecipients = recipients == null || recipients.isEmpty();
if (noRecipients && groupIdString == null) {
System.err.println("No recipients given");
System.err.println("Aborting sending.");
@ -61,15 +60,15 @@ public class SendReactionCommand implements LocalCommand {
return 1;
}
final String emoji = ns.getString("emoji");
final var emoji = ns.getString("emoji");
final boolean isRemove = ns.getBoolean("remove");
final String targetAuthor = ns.getString("target_author");
final var targetAuthor = ns.getString("target_author");
final long targetTimestamp = ns.getLong("target_timestamp");
try {
final Pair<Long, List<SendMessageResult>> results;
if (groupIdString != null) {
GroupId groupId = Util.decodeGroupId(groupIdString);
var groupId = Util.decodeGroupId(groupIdString);
results = m.sendGroupMessageReaction(emoji, isRemove, targetAuthor, targetTimestamp, groupId);
} else {
results = m.sendMessageReaction(emoji, isRemove, targetAuthor, targetTimestamp, recipients);

View file

@ -20,7 +20,7 @@ public class SetPinCommand implements LocalCommand {
@Override
public int handleCommand(final Namespace ns, final Manager m) {
try {
String registrationLockPin = ns.getString("registrationLockPin");
var registrationLockPin = ns.getString("registrationLockPin");
m.setRegistrationLockPin(Optional.of(registrationLockPin));
return 0;
} catch (UnauthenticatedResponseException e) {

View file

@ -1,7 +1,6 @@
package org.asamk.signal.commands;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
@ -17,7 +16,7 @@ public class TrustCommand implements LocalCommand {
@Override
public void attachToSubparser(final Subparser subparser) {
subparser.addArgument("number").help("Specify the phone number, for which to set the trust.").required(true);
MutuallyExclusiveGroup mutTrust = subparser.addMutuallyExclusiveGroup();
var mutTrust = subparser.addMutuallyExclusiveGroup();
mutTrust.addArgument("-a", "--trust-all-known-keys")
.help("Trust all known keys of this user, only use this for testing.")
.action(Arguments.storeTrue());
@ -27,15 +26,15 @@ public class TrustCommand implements LocalCommand {
@Override
public int handleCommand(final Namespace ns, final Manager m) {
String number = ns.getString("number");
var number = ns.getString("number");
if (ns.getBoolean("trust_all_known_keys")) {
boolean res = m.trustIdentityAllKeys(number);
var res = m.trustIdentityAllKeys(number);
if (!res) {
System.err.println("Failed to set the trust for this number, make sure the number is correct.");
return 1;
}
} else {
String safetyNumber = ns.getString("verified_safety_number");
var safetyNumber = ns.getString("verified_safety_number");
if (safetyNumber != null) {
safetyNumber = safetyNumber.replaceAll(" ", "");
if (safetyNumber.length() == 66) {

View file

@ -4,7 +4,6 @@ import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.groups.GroupId;
import org.asamk.signal.manager.groups.GroupIdFormatException;
import org.asamk.signal.manager.groups.GroupNotFoundException;
import org.asamk.signal.util.Util;
@ -21,7 +20,7 @@ public class UnblockCommand implements LocalCommand {
@Override
public int handleCommand(final Namespace ns, final Manager m) {
for (String contact_number : ns.<String>getList("contact")) {
for (var contact_number : ns.<String>getList("contact")) {
try {
m.setContactBlocked(contact_number, false);
} catch (InvalidNumberException e) {
@ -30,9 +29,9 @@ public class UnblockCommand implements LocalCommand {
}
if (ns.<String>getList("group") != null) {
for (String groupIdString : ns.<String>getList("group")) {
for (var groupIdString : ns.<String>getList("group")) {
try {
GroupId groupId = Util.decodeGroupId(groupIdString);
var groupId = Util.decodeGroupId(groupIdString);
m.setGroupBlocked(groupId, false);
} catch (GroupIdFormatException | GroupNotFoundException e) {
System.err.println(e.getMessage());

View file

@ -23,13 +23,13 @@ public class UpdateContactCommand implements LocalCommand {
@Override
public int handleCommand(final Namespace ns, final Manager m) {
String number = ns.getString("number");
String name = ns.getString("name");
var number = ns.getString("number");
var name = ns.getString("name");
try {
m.setContactName(number, name);
Integer expiration = ns.getInt("expiration");
var expiration = ns.getInt("expiration");
if (expiration != null) {
m.setExpirationTimer(number, expiration);
}

View file

@ -40,7 +40,7 @@ public class UpdateGroupCommand implements DbusCommand {
groupId = new byte[0];
}
String groupName = ns.getString("name");
var groupName = ns.getString("name");
if (groupName == null) {
groupName = "";
}
@ -50,13 +50,13 @@ public class UpdateGroupCommand implements DbusCommand {
groupMembers = new ArrayList<>();
}
String groupAvatar = ns.getString("avatar");
var groupAvatar = ns.getString("avatar");
if (groupAvatar == null) {
groupAvatar = "";
}
try {
byte[] newGroupId = signal.updateGroup(groupId, groupName, groupMembers, groupAvatar);
var newGroupId = signal.updateGroup(groupId, groupName, groupMembers, groupAvatar);
if (groupId.length != newGroupId.length) {
System.out.println("Creating new group \"" + Base64.getEncoder().encodeToString(newGroupId) + "\"");
}

View file

@ -1,7 +1,6 @@
package org.asamk.signal.commands;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
@ -19,7 +18,7 @@ public class UpdateProfileCommand implements LocalCommand {
subparser.addArgument("--about").help("New profile about text");
subparser.addArgument("--about-emoji").help("New profile about emoji");
final MutuallyExclusiveGroup avatarOptions = subparser.addMutuallyExclusiveGroup();
final var avatarOptions = subparser.addMutuallyExclusiveGroup();
avatarOptions.addArgument("--avatar").help("Path to new profile avatar");
avatarOptions.addArgument("--remove-avatar").action(Arguments.storeTrue());
@ -28,10 +27,10 @@ public class UpdateProfileCommand implements LocalCommand {
@Override
public int handleCommand(final Namespace ns, final Manager m) {
String name = ns.getString("name");
String about = ns.getString("about");
String aboutEmoji = ns.getString("about_emoji");
String avatarPath = ns.getString("avatar");
var name = ns.getString("name");
var about = ns.getString("about");
var aboutEmoji = ns.getString("about_emoji");
var avatarPath = ns.getString("avatar");
boolean removeAvatar = ns.getBoolean("remove_avatar");
try {

View file

@ -20,8 +20,8 @@ public class UploadStickerPackCommand implements LocalCommand {
@Override
public int handleCommand(final Namespace ns, final Manager m) {
try {
File path = new File(ns.getString("path"));
String url = m.uploadStickerPack(path);
var path = new File(ns.getString("path"));
var url = m.uploadStickerPack(path);
System.out.println(url);
return 0;
} catch (IOException e) {

View file

@ -21,8 +21,8 @@ public class VerifyCommand implements RegistrationCommand {
@Override
public int handleCommand(final Namespace ns, final RegistrationManager m) {
try {
String verificationCode = ns.getString("verificationCode");
String pin = ns.getString("pin");
var verificationCode = ns.getString("verificationCode");
var pin = ns.getString("pin");
m.verifyAccount(verificationCode, pin);
return 0;
} catch (LockedException e) {

View file

@ -6,10 +6,8 @@ import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.groups.GroupId;
import org.asamk.signal.manager.groups.GroupNotFoundException;
import org.asamk.signal.manager.groups.NotAGroupMemberException;
import org.asamk.signal.manager.storage.groups.GroupInfo;
import org.asamk.signal.util.ErrorUtils;
import org.freedesktop.dbus.exceptions.DBusExecutionException;
import org.whispersystems.libsignal.util.Pair;
import org.whispersystems.libsignal.util.guava.Optional;
import org.whispersystems.signalservice.api.messages.SendMessageResult;
import org.whispersystems.signalservice.api.push.SignalServiceAddress;
@ -41,19 +39,19 @@ public class DbusSignalImpl implements Signal {
@Override
public long sendMessage(final String message, final List<String> attachments, final String recipient) {
List<String> recipients = new ArrayList<>(1);
var recipients = new ArrayList<String>(1);
recipients.add(recipient);
return sendMessage(message, attachments, recipients);
}
private static void checkSendMessageResult(long timestamp, SendMessageResult result) throws DBusExecutionException {
String error = ErrorUtils.getErrorMessageFromSendMessageResult(result);
var error = ErrorUtils.getErrorMessageFromSendMessageResult(result);
if (error == null) {
return;
}
final String message = timestamp + "\nFailed to send message:\n" + error + '\n';
final var message = timestamp + "\nFailed to send message:\n" + error + '\n';
if (result.getIdentityFailure() != null) {
throw new Error.UntrustedIdentity(message);
@ -70,15 +68,15 @@ public class DbusSignalImpl implements Signal {
return;
}
List<String> errors = ErrorUtils.getErrorMessagesFromSendMessageResults(results);
var errors = ErrorUtils.getErrorMessagesFromSendMessageResults(results);
if (errors.size() == 0) {
return;
}
StringBuilder message = new StringBuilder();
var message = new StringBuilder();
message.append(timestamp).append('\n');
message.append("Failed to send (some) messages:\n");
for (String error : errors) {
for (var error : errors) {
message.append(error).append('\n');
}
@ -88,7 +86,7 @@ public class DbusSignalImpl implements Signal {
@Override
public long sendMessage(final String message, final List<String> attachments, final List<String> recipients) {
try {
final Pair<Long, List<SendMessageResult>> results = m.sendMessage(message, attachments, recipients);
final var results = m.sendMessage(message, attachments, recipients);
checkSendMessageResults(results.first(), results.second());
return results.first();
} catch (InvalidNumberException e) {
@ -105,7 +103,7 @@ public class DbusSignalImpl implements Signal {
final String message, final List<String> attachments
) throws Error.AttachmentInvalid, Error.Failure, Error.UntrustedIdentity {
try {
final Pair<Long, SendMessageResult> results = m.sendSelfMessage(message, attachments);
final var results = m.sendSelfMessage(message, attachments);
checkSendMessageResult(results.first(), results.second());
return results.first();
} catch (AttachmentInvalidException e) {
@ -118,7 +116,7 @@ public class DbusSignalImpl implements Signal {
@Override
public void sendEndSessionMessage(final List<String> recipients) {
try {
final Pair<Long, List<SendMessageResult>> results = m.sendEndSessionMessage(recipients);
final var results = m.sendEndSessionMessage(recipients);
checkSendMessageResults(results.first(), results.second());
} catch (IOException e) {
throw new Error.Failure(e.getMessage());
@ -130,9 +128,7 @@ public class DbusSignalImpl implements Signal {
@Override
public long sendGroupMessage(final String message, final List<String> attachments, final byte[] groupId) {
try {
Pair<Long, List<SendMessageResult>> results = m.sendGroupMessage(message,
attachments,
GroupId.unknownVersion(groupId));
var results = m.sendGroupMessage(message, attachments, GroupId.unknownVersion(groupId));
checkSendMessageResults(results.first(), results.second());
return results.first();
} catch (IOException e) {
@ -182,9 +178,9 @@ public class DbusSignalImpl implements Signal {
@Override
public List<byte[]> getGroupIds() {
List<GroupInfo> groups = m.getGroups();
List<byte[]> ids = new ArrayList<>(groups.size());
for (GroupInfo group : groups) {
var groups = m.getGroups();
var ids = new ArrayList<byte[]>(groups.size());
for (var group : groups) {
ids.add(group.getGroupId().serialize());
}
return ids;
@ -192,7 +188,7 @@ public class DbusSignalImpl implements Signal {
@Override
public String getGroupName(final byte[] groupId) {
GroupInfo group = m.getGroup(GroupId.unknownVersion(groupId));
var group = m.getGroup(GroupId.unknownVersion(groupId));
if (group == null) {
return "";
} else {
@ -202,7 +198,7 @@ public class DbusSignalImpl implements Signal {
@Override
public List<String> getGroupMembers(final byte[] groupId) {
GroupInfo group = m.getGroup(GroupId.unknownVersion(groupId));
var group = m.getGroup(GroupId.unknownVersion(groupId));
if (group == null) {
return List.of();
} else {
@ -229,9 +225,10 @@ public class DbusSignalImpl implements Signal {
if (avatar.isEmpty()) {
avatar = null;
}
final Pair<GroupId, List<SendMessageResult>> results = m.updateGroup(groupId == null
? null
: GroupId.unknownVersion(groupId), name, members, avatar == null ? null : new File(avatar));
final var results = m.updateGroup(groupId == null ? null : GroupId.unknownVersion(groupId),
name,
members,
avatar == null ? null : new File(avatar));
checkSendMessageResults(0, results.second());
return results.first().serialize();
} catch (IOException e) {

View file

@ -3,8 +3,6 @@ package org.asamk.signal.json;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.whispersystems.signalservice.api.messages.SignalServiceAttachment;
import org.whispersystems.signalservice.api.messages.SignalServiceAttachmentPointer;
import org.whispersystems.signalservice.api.messages.SignalServiceAttachmentStream;
class JsonAttachment {
@ -24,12 +22,12 @@ class JsonAttachment {
this.contentType = attachment.getContentType();
if (attachment.isPointer()) {
final SignalServiceAttachmentPointer pointer = attachment.asPointer();
final var pointer = attachment.asPointer();
this.id = pointer.getRemoteId().toString();
this.filename = pointer.getFileName().orNull();
this.size = pointer.getSize().transform(Integer::longValue).orNull();
} else {
final SignalServiceAttachmentStream stream = attachment.asStream();
final var stream = attachment.asStream();
this.id = null;
this.filename = stream.getFileName().orNull();
this.size = stream.getLength();

View file

@ -6,9 +6,6 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import org.asamk.Signal;
import org.asamk.signal.manager.Manager;
import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage;
import org.whispersystems.signalservice.api.messages.SignalServiceGroup;
import org.whispersystems.signalservice.api.messages.SignalServiceGroupContext;
import org.whispersystems.signalservice.api.messages.SignalServiceGroupV2;
import java.util.List;
import java.util.stream.Collectors;
@ -63,12 +60,12 @@ class JsonDataMessage {
JsonDataMessage(SignalServiceDataMessage dataMessage, Manager m) {
this.timestamp = dataMessage.getTimestamp();
if (dataMessage.getGroupContext().isPresent()) {
final SignalServiceGroupContext groupContext = dataMessage.getGroupContext().get();
final var groupContext = dataMessage.getGroupContext().get();
if (groupContext.getGroupV1().isPresent()) {
SignalServiceGroup groupInfo = groupContext.getGroupV1().get();
var groupInfo = groupContext.getGroupV1().get();
this.groupInfo = new JsonGroupInfo(groupInfo);
} else if (groupContext.getGroupV2().isPresent()) {
SignalServiceGroupV2 groupInfo = groupContext.getGroupV2().get();
var groupInfo = groupContext.getGroupV2().get();
this.groupInfo = new JsonGroupInfo(groupInfo);
} else {
this.groupInfo = null;

View file

@ -7,7 +7,6 @@ import org.asamk.Signal;
import org.asamk.signal.manager.Manager;
import org.whispersystems.signalservice.api.messages.SignalServiceContent;
import org.whispersystems.signalservice.api.messages.SignalServiceEnvelope;
import org.whispersystems.signalservice.api.push.SignalServiceAddress;
import java.util.List;
@ -48,7 +47,7 @@ public class JsonMessageEnvelope {
public JsonMessageEnvelope(SignalServiceEnvelope envelope, SignalServiceContent content, Manager m) {
if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
SignalServiceAddress source = envelope.getSourceAddress();
var source = envelope.getSourceAddress();
this.source = source.getLegacyIdentifier();
this.sourceDevice = envelope.getSourceDevice();
this.relay = source.getRelay().orNull();

View file

@ -45,7 +45,7 @@ class JsonSyncMessage {
? new JsonSyncDataMessage(syncMessage.getSent().get(), m)
: null;
if (syncMessage.getBlockedList().isPresent()) {
final Base64.Encoder base64 = Base64.getEncoder();
final var base64 = Base64.getEncoder();
this.blockedNumbers = syncMessage.getBlockedList()
.get()
.getAddresses()

View file

@ -22,7 +22,7 @@ class JsonTypingMessage {
JsonTypingMessage(SignalServiceTypingMessage typingMessage) {
this.action = typingMessage.getAction().name();
this.timestamp = typingMessage.getTimestamp();
final Base64.Encoder encoder = Base64.getEncoder();
final var encoder = Base64.getEncoder();
this.groupId = typingMessage.getGroupId().transform(encoder::encodeToString).orNull();
}
}

View file

@ -13,7 +13,7 @@ public class DateUtils {
}
public static String formatTimestamp(long timestamp) {
Date date = new Date(timestamp);
var date = new Date(timestamp);
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX"); // Quoted "Z" to indicate UTC, no timezone offset
df.setTimeZone(tzUTC);
return timestamp + " (" + df.format(date) + ")";

View file

@ -26,14 +26,14 @@ public class ErrorUtils {
if (timestamp != 0) {
System.out.println(timestamp);
}
List<String> errors = getErrorMessagesFromSendMessageResults(results);
var errors = getErrorMessagesFromSendMessageResults(results);
return handleSendMessageResultErrors(errors);
}
public static List<String> getErrorMessagesFromSendMessageResults(List<SendMessageResult> results) {
List<String> errors = new ArrayList<>();
for (SendMessageResult result : results) {
String error = getErrorMessageFromSendMessageResult(result);
var errors = new ArrayList<String>();
for (var result : results) {
var error = getErrorMessageFromSendMessageResult(result);
if (error != null) {
errors.add(error);
}
@ -58,7 +58,7 @@ public class ErrorUtils {
return 0;
}
System.err.println("Failed to send (some) messages:");
for (String error : errors) {
for (var error : errors) {
System.err.println(error);
}
return 3;

View file

@ -8,8 +8,8 @@ public class Hex {
}
public static String toString(byte[] bytes) {
StringBuffer buf = new StringBuffer();
for (final byte aByte : bytes) {
var buf = new StringBuffer();
for (final var aByte : bytes) {
appendHexChar(buf, aByte);
buf.append(" ");
}
@ -17,8 +17,8 @@ public class Hex {
}
public static String toStringCondensed(byte[] bytes) {
StringBuffer buf = new StringBuffer();
for (final byte aByte : bytes) {
var buf = new StringBuffer();
for (final var aByte : bytes) {
appendHexChar(buf, aByte);
}
return buf.toString();
@ -30,9 +30,9 @@ public class Hex {
}
public static byte[] toByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
var len = s.length();
var data = new byte[len / 2];
for (var i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
}
return data;

View file

@ -12,8 +12,8 @@ public class IOUtils {
}
public static String readAll(InputStream in, Charset charset) throws IOException {
StringWriter output = new StringWriter();
byte[] buffer = new byte[4096];
var output = new StringWriter();
var buffer = new byte[4096];
int n;
while (-1 != (n = in.read(buffer))) {
output.write(new String(buffer, 0, n, charset));
@ -22,7 +22,7 @@ public class IOUtils {
}
public static File getDataHomeDir() {
String dataHome = System.getenv("XDG_DATA_HOME");
var dataHome = System.getenv("XDG_DATA_HOME");
if (dataHome != null) {
return new File(dataHome);
}

View file

@ -6,7 +6,7 @@ import java.security.SecureRandom;
public class RandomUtils {
private static final ThreadLocal<SecureRandom> LOCAL_RANDOM = ThreadLocal.withInitial(() -> {
SecureRandom rand = getSecureRandomUnseeded();
var rand = getSecureRandomUnseeded();
// Let the SecureRandom seed it self initially
rand.nextBoolean();

View file

@ -10,7 +10,7 @@ public class Util {
}
public static String getStringIfNotBlank(Optional<String> value) {
String string = value.orNull();
var string = value.orNull();
if (string == null || string.isBlank()) {
return null;
}
@ -18,10 +18,10 @@ public class Util {
}
public static String formatSafetyNumber(String digits) {
final int partCount = 12;
int partSize = digits.length() / partCount;
StringBuilder f = new StringBuilder(digits.length() + partCount);
for (int i = 0; i < partCount; i++) {
final var partCount = 12;
var partSize = digits.length() / partCount;
var f = new StringBuilder(digits.length() + partCount);
for (var i = 0; i < partCount; i++) {
f.append(digits, i * partSize, (i * partSize) + partSize).append(" ");
}
return f.toString();