+ return group.isMember();
+ }
+ }
+
+ @Override
+ public String uploadStickerPack(String stickerPackPath) {
+ File path = new File(stickerPackPath);
+ try {
+ return m.uploadStickerPack(path).toString();
+ } catch (IOException e) {
+ throw new Error.Failure("Upload error (maybe image size is too large):" + e.getMessage());
+ } catch (StickerPackInvalidException e) {
+ throw new Error.Failure("Invalid sticker pack: " + e.getMessage());
+ }
+ }
+
+ private static void checkSendMessageResult(long timestamp, SendMessageResult result) throws DBusExecutionException {
+ var error = SendMessageResultUtils.getErrorMessageFromSendMessageResult(result);
+
+ if (error == null) {
+ return;
+ }
+
+ final var message = "\nFailed to send message:\n" + error + '\n' + timestamp;
+
+ if (result.isIdentityFailure()) {
+ throw new Error.UntrustedIdentity(message);
+ } else {
+ throw new Error.Failure(message);
+ }
+ }
+
+ private void checkSendMessageResults(final SendMessageResults results) {
+ final var sendMessageResults = results.results().values().stream().findFirst();
+ if (results.results().size() == 1 && sendMessageResults.get().size() == 1) {
+ checkSendMessageResult(results.timestamp(), sendMessageResults.get().stream().findFirst().get());
+ return;
+ }
+
+ if (results.hasSuccess()) {
+ return;
+ }
+
+ var message = new StringBuilder();
+ message.append("Failed to send messages:\n");
+ var errors = SendMessageResultUtils.getErrorMessagesFromSendMessageResults(results.results());
+ for (var error : errors) {
+ message.append(error).append('\n');
+ }
+ message.append(results.timestamp());
+
+ throw new Error.Failure(message.toString());
+ }
+
+ private static void checkGroupSendMessageResults(
+ long timestamp, Collection<SendMessageResult> results
+ ) throws DBusExecutionException {
+ if (results.size() == 1) {
+ checkSendMessageResult(timestamp, results.stream().findFirst().get());
+ return;
+ }
+
+ var errors = SendMessageResultUtils.getErrorMessagesFromSendMessageResults(results);
+ if (errors.size() == 0 || errors.size() < results.size()) {
+ return;
+ }
+
+ var message = new StringBuilder();
+ message.append("Failed to send message:\n");
+ for (var error : errors) {
+ message.append(error).append('\n');
+ }
+ message.append(timestamp);
+
+ throw new Error.Failure(message.toString());
+ }
+
+ private static List<String> getRecipientStrings(final Set<RecipientAddress> members) {
+ return members.stream().map(RecipientAddress::getLegacyIdentifier).toList();
+ }
+
+ private static Set<RecipientIdentifier.Single> getSingleRecipientIdentifiers(
+ final Collection<String> recipientStrings, final String localNumber
+ ) throws DBusExecutionException {
+ final var identifiers = new HashSet<RecipientIdentifier.Single>();
+ for (var recipientString : recipientStrings) {
+ identifiers.add(getSingleRecipientIdentifier(recipientString, localNumber));
+ }
+ return identifiers;
+ }
+
+ private static RecipientIdentifier.Single getSingleRecipientIdentifier(
+ final String recipientString, final String localNumber
+ ) throws DBusExecutionException {
+ try {
+ return RecipientIdentifier.Single.fromString(recipientString, localNumber);
+ } catch (InvalidNumberException e) {
+ throw new Error.InvalidNumber(e.getMessage());
+ }
+ }
+
+ private RecipientIdentifier.Group getGroupRecipientIdentifier(final byte[] groupId) {
+ return new RecipientIdentifier.Group(getGroupId(groupId));
+ }
+
+ private static GroupId getGroupId(byte[] groupId) throws DBusExecutionException {
+ try {
+ return GroupId.unknownVersion(groupId);
+ } catch (Throwable e) {
+ throw new Error.InvalidGroupId("Invalid group id: " + e.getMessage());
+ }
+ }
+
+ private byte[] nullIfEmpty(final byte[] array) {
+ return array.length == 0 ? null : array;
+ }
+
+ private String nullIfEmpty(final String name) {
+ return name.isEmpty() ? null : name;
+ }
+
+ private String emptyIfNull(final String string) {
+ return string == null ? "" : string;
+ }
+
+ private static String getDeviceObjectPath(String basePath, long deviceId) {
+ return basePath + "/Devices/" + deviceId;
+ }
+
+ private void updateDevices() {
+ List<org.asamk.signal.manager.api.Device> linkedDevices;
+ try {
+ linkedDevices = m.getLinkedDevices();
+ } catch (IOException e) {
+ throw new Error.Failure("Failed to get linked devices: " + e.getMessage());
+ }
+
+ unExportDevices();
+
+ linkedDevices.forEach(d -> {
+ final var object = new DbusSignalDeviceImpl(d);
+ final var deviceObjectPath = object.getObjectPath();
+ exportObject(object);
+ if (d.isThisDevice()) {
+ thisDevice = new DBusPath(deviceObjectPath);
+ }
+ this.devices.add(new StructDevice(new DBusPath(deviceObjectPath), (long) d.id(), emptyIfNull(d.name())));
+ });
+ }
+
+ private void unExportDevices() {
+ this.devices.stream()
+ .map(StructDevice::getObjectPath)
+ .map(DBusPath::getPath)
+ .forEach(connection::unExportObject);
+ this.devices.clear();
+ }
+
+ private static String getGroupObjectPath(String basePath, byte[] groupId) {
+ return basePath + "/Groups/" + Base64.getEncoder()
+ .encodeToString(groupId)
+ .replace("+", "_")
+ .replace("/", "_")
+ .replace("=", "_");
+ }
+
+ private void updateGroups() {
+ List<org.asamk.signal.manager.api.Group> groups;
+ groups = m.getGroups();
+
+ unExportGroups();
+
+ groups.forEach(g -> {
+ final var object = new DbusSignalGroupImpl(g.groupId());
+ exportObject(object);
+ this.groups.add(new StructGroup(new DBusPath(object.getObjectPath()),
+ g.groupId().serialize(),
+ emptyIfNull(g.title())));
+ });
+ }
+
+ private void unExportGroups() {
+ this.groups.stream().map(StructGroup::getObjectPath).map(DBusPath::getPath).forEach(connection::unExportObject);
+ this.groups.clear();
+ }
+
+ private static String getConfigurationObjectPath(String basePath) {
+ return basePath + "/Configuration";
+ }
+
+ private void updateConfiguration() {
+ unExportConfiguration();
+ final var object = new DbusSignalConfigurationImpl();
+ exportObject(object);
+ }
+
+ private void unExportConfiguration() {
+ final var objectPath = getConfigurationObjectPath(this.objectPath);
+ connection.unExportObject(objectPath);
+ }
+
+ private void exportObject(final DBusInterface object) {
+ try {
+ connection.exportObject(object);
+ logger.debug("Exported dbus object: " + object.getObjectPath());
+ } catch (DBusException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public class DbusSignalDeviceImpl extends DbusProperties implements Signal.Device {
+
+ private final org.asamk.signal.manager.api.Device device;
+
+ public DbusSignalDeviceImpl(final org.asamk.signal.manager.api.Device device) {
+ super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
+ List.of(new DbusProperty<>("Id", device::id),
+ new DbusProperty<>("Name", () -> emptyIfNull(device.name()), this::setDeviceName),
+ new DbusProperty<>("Created", device::created),
+ new DbusProperty<>("LastSeen", device::lastSeen))));
+ this.device = device;
+ }
+
+ @Override
+ public String getObjectPath() {
+ return getDeviceObjectPath(objectPath, device.id());
+ }
+
+ @Override
+ public void removeDevice() throws Error.Failure {
+ try {
+ m.removeLinkedDevices(device.id());
+ updateDevices();
+ } catch (IOException e) {
+ throw new Error.Failure(e.getMessage());
+ }
+ }
+
+ private void setDeviceName(String name) {
+ if (!device.isThisDevice()) {
+ throw new Error.Failure("Only the name of this device can be changed");
+ }
+ try {
+ m.updateAccountAttributes(name);
+ // update device list
+ updateDevices();
+ } catch (IOException e) {
+ throw new Error.Failure(e.getMessage());
+ }
+ }
+ }
+
+ public class DbusSignalConfigurationImpl extends DbusProperties implements Signal.Configuration {
+
+ public DbusSignalConfigurationImpl(
+ ) {
+ super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Configuration",
+ List.of(new DbusProperty<>("ReadReceipts", this::getReadReceipts, this::setReadReceipts),
+ new DbusProperty<>("UnidentifiedDeliveryIndicators",
+ this::getUnidentifiedDeliveryIndicators,
+ this::setUnidentifiedDeliveryIndicators),
+ new DbusProperty<>("TypingIndicators",
+ this::getTypingIndicators,
+ this::setTypingIndicators),
+ new DbusProperty<>("LinkPreviews", this::getLinkPreviews, this::setLinkPreviews))));
+
+ }
+
+ @Override
+ public String getObjectPath() {
+ return getConfigurationObjectPath(objectPath);
+ }
+
+ public void setReadReceipts(Boolean readReceipts) {
+ setConfiguration(readReceipts, null, null, null);
+ }
+
+ public void setUnidentifiedDeliveryIndicators(Boolean unidentifiedDeliveryIndicators) {
+ setConfiguration(null, unidentifiedDeliveryIndicators, null, null);
+ }
+
+ public void setTypingIndicators(Boolean typingIndicators) {
+ setConfiguration(null, null, typingIndicators, null);
+ }
+
+ public void setLinkPreviews(Boolean linkPreviews) {
+ setConfiguration(null, null, null, linkPreviews);
+ }
+
+ private void setConfiguration(
+ Boolean readReceipts,
+ Boolean unidentifiedDeliveryIndicators,
+ Boolean typingIndicators,
+ Boolean linkPreviews
+ ) {
+ try {
+ m.updateConfiguration(new org.asamk.signal.manager.api.Configuration(Optional.ofNullable(readReceipts),
+ Optional.ofNullable(unidentifiedDeliveryIndicators),
+ Optional.ofNullable(typingIndicators),
+ Optional.ofNullable(linkPreviews)));
+ } catch (IOException e) {
+ throw new Error.Failure("UpdateAccount error: " + e.getMessage());
+ } catch (NotPrimaryDeviceException e) {
+ throw new Error.Failure("This command doesn't work on linked devices.");
+ }
+ }
+
+ private boolean getReadReceipts() {
+ return m.getConfiguration().readReceipts().orElse(false);
+ }
+
+ private boolean getUnidentifiedDeliveryIndicators() {
+ return m.getConfiguration().unidentifiedDeliveryIndicators().orElse(false);
+ }
+
+ private boolean getTypingIndicators() {
+ return m.getConfiguration().typingIndicators().orElse(false);
+ }
+
+ private boolean getLinkPreviews() {
+ return m.getConfiguration().linkPreviews().orElse(false);
+ }
+ }
+
+ public class DbusSignalGroupImpl extends DbusProperties implements Signal.Group {
+
+ private final GroupId groupId;
+
+ public DbusSignalGroupImpl(final GroupId groupId) {
+ this.groupId = groupId;
+ super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
+ List.of(new DbusProperty<>("Id", groupId::serialize),
+ new DbusProperty<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName),
+ new DbusProperty<>("Description",
+ () -> emptyIfNull(getGroup().description()),
+ this::setGroupDescription),
+ new DbusProperty<>("Avatar", this::setGroupAvatar),
+ new DbusProperty<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked),
+ new DbusProperty<>("IsMember", () -> getGroup().isMember()),
+ new DbusProperty<>("IsAdmin", () -> getGroup().isAdmin()),
+ new DbusProperty<>("MessageExpirationTimer",
+ () -> getGroup().messageExpirationTimer(),
+ this::setMessageExpirationTime),
+ new DbusProperty<>("Members",
+ () -> new Variant<>(getRecipientStrings(getGroup().members()), "as")),
+ new DbusProperty<>("PendingMembers",
+ () -> new Variant<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
+ new DbusProperty<>("RequestingMembers",
+ () -> new Variant<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
+ new DbusProperty<>("Admins",
+ () -> new Variant<>(getRecipientStrings(getGroup().adminMembers()), "as")),
+ new DbusProperty<>("Banned",
+ () -> new Variant<>(getRecipientStrings(getGroup().bannedMembers()), "as")),
+ new DbusProperty<>("PermissionAddMember",
+ () -> getGroup().permissionAddMember().name(),
+ this::setGroupPermissionAddMember),
+ new DbusProperty<>("PermissionEditDetails",
+ () -> getGroup().permissionEditDetails().name(),
+ this::setGroupPermissionEditDetails),
+ new DbusProperty<>("PermissionSendMessage",
+ () -> getGroup().permissionSendMessage().name(),
+ this::setGroupPermissionSendMessage),
+ new DbusProperty<>("GroupInviteLink", () -> {
+ final var groupInviteLinkUrl = getGroup().groupInviteLinkUrl();
+ return groupInviteLinkUrl == null ? "" : groupInviteLinkUrl.getUrl();
+ }))));
+ }
+
+ @Override
+ public String getObjectPath() {
+ return getGroupObjectPath(objectPath, groupId.serialize());
+ }
+
+ @Override
+ public void quitGroup() throws Error.Failure {
+ try {
+ m.quitGroup(groupId, Set.of());
+ } catch (GroupNotFoundException e) {
+ throw new Error.GroupNotFound(e.getMessage());
+ } catch (NotAGroupMemberException e) {
+ throw new Error.NotAGroupMember(e.getMessage());
+ } catch (IOException e) {
+ throw new Error.Failure(e.getMessage());
+ } catch (LastGroupAdminException e) {
+ throw new Error.LastGroupAdmin(e.getMessage());
+ } catch (UnregisteredRecipientException e) {
+ throw new Error.UntrustedIdentity(e.getSender().getIdentifier() + " is not registered.");
+ }
+ }
+
+ @Override
+ public void deleteGroup() throws Error.Failure, Error.LastGroupAdmin {
+ try {
+ m.deleteGroup(groupId);
+ } catch (IOException e) {
+ throw new Error.Failure(e.getMessage());
+ }
+ updateGroups();
+ }
+
+ @Override
+ public void addMembers(final List<String> recipients) throws Error.Failure {
+ final var memberIdentifiers = getSingleRecipientIdentifiers(recipients, m.getSelfNumber());
+ updateGroup(UpdateGroup.newBuilder().withMembers(memberIdentifiers).build());
+ }
+
+ @Override
+ public void removeMembers(final List<String> recipients) throws Error.Failure {
+ final var memberIdentifiers = getSingleRecipientIdentifiers(recipients, m.getSelfNumber());
+ updateGroup(UpdateGroup.newBuilder().withRemoveMembers(memberIdentifiers).build());
+ }
+
+ @Override
+ public void addAdmins(final List<String> recipients) throws Error.Failure {
+ final var memberIdentifiers = getSingleRecipientIdentifiers(recipients, m.getSelfNumber());
+ updateGroup(UpdateGroup.newBuilder().withAdmins(memberIdentifiers).build());
+ }
+
+ @Override
+ public void removeAdmins(final List<String> recipients) throws Error.Failure {
+ final var memberIdentifiers = getSingleRecipientIdentifiers(recipients, m.getSelfNumber());
+ updateGroup(UpdateGroup.newBuilder().withRemoveAdmins(memberIdentifiers).build());
+ }
+
+ @Override
+ public void resetLink() throws Error.Failure {
+ updateGroup(UpdateGroup.newBuilder().withResetGroupLink(true).build());
+ }
+
+ @Override
+ public void disableLink() throws Error.Failure {
+ updateGroup(UpdateGroup.newBuilder().withGroupLinkState(GroupLinkState.DISABLED).build());
+ }
+
+ @Override
+ public void enableLink(final boolean requiresApproval) throws Error.Failure {
+ updateGroup(UpdateGroup.newBuilder()
+ .withGroupLinkState(requiresApproval
+ ? GroupLinkState.ENABLED_WITH_APPROVAL
+ : GroupLinkState.ENABLED)
+ .build());
+ }
+
+ private org.asamk.signal.manager.api.Group getGroup() {
+ return m.getGroup(groupId);
+ }
+
+ private void setGroupName(final String name) {
+ updateGroup(UpdateGroup.newBuilder().withName(name).build());
+ }
+
+ private void setGroupDescription(final String description) {
+ updateGroup(UpdateGroup.newBuilder().withDescription(description).build());
+ }
+
+ private void setGroupAvatar(final String avatar) {
+ updateGroup(UpdateGroup.newBuilder().withAvatarFile(avatar).build());
+ }
+
+ private void setMessageExpirationTime(final int expirationTime) {
+ updateGroup(UpdateGroup.newBuilder().withExpirationTimer(expirationTime).build());
+ }
+
+ private void setGroupPermissionAddMember(final String permission) {
+ updateGroup(UpdateGroup.newBuilder().withAddMemberPermission(GroupPermission.valueOf(permission)).build());
+ }
+
+ private void setGroupPermissionEditDetails(final String permission) {
+ updateGroup(UpdateGroup.newBuilder()
+ .withEditDetailsPermission(GroupPermission.valueOf(permission))
+ .build());
+ }
+
+ private void setGroupPermissionSendMessage(final String permission) {
+ updateGroup(UpdateGroup.newBuilder()
+ .withIsAnnouncementGroup(GroupPermission.valueOf(permission) == GroupPermission.ONLY_ADMINS)
+ .build());
+ }
+
+ private void setIsBlocked(final boolean isBlocked) {
+ try {
+ m.setGroupsBlocked(List.of(groupId), isBlocked);
+ } catch (NotPrimaryDeviceException e) {
+ throw new Error.Failure("This command doesn't work on linked devices.");
+ } catch (GroupNotFoundException e) {
+ throw new Error.GroupNotFound(e.getMessage());
+ } catch (IOException e) {
+ throw new Error.Failure(e.getMessage());
+ }
+ }
+
+ private void updateGroup(final UpdateGroup updateGroup) {
+ try {
+ m.updateGroup(groupId, updateGroup);
+ } catch (IOException e) {
+ throw new Error.Failure(e.getMessage());
+ } catch (GroupNotFoundException | NotAGroupMemberException | GroupSendingNotAllowedException e) {
+ throw new Error.GroupNotFound(e.getMessage());
+ } catch (AttachmentInvalidException e) {
+ throw new Error.AttachmentInvalid(e.getMessage());
+ } catch (UnregisteredRecipientException e) {
+ throw new Error.UntrustedIdentity(e.getSender().getIdentifier() + " is not registered.");
+ }