]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/dbus/DbusManagerImpl.java
0d87cdb5a05188ef03d4f4389648685f604a6f4d
[signal-cli] / src / main / java / org / asamk / signal / dbus / DbusManagerImpl.java
1 package org.asamk.signal.dbus;
2
3 import org.asamk.Signal;
4 import org.asamk.signal.DbusConfig;
5 import org.asamk.signal.manager.AttachmentInvalidException;
6 import org.asamk.signal.manager.Manager;
7 import org.asamk.signal.manager.NotMasterDeviceException;
8 import org.asamk.signal.manager.StickerPackInvalidException;
9 import org.asamk.signal.manager.UntrustedIdentityException;
10 import org.asamk.signal.manager.api.Device;
11 import org.asamk.signal.manager.api.Group;
12 import org.asamk.signal.manager.api.Identity;
13 import org.asamk.signal.manager.api.InactiveGroupLinkException;
14 import org.asamk.signal.manager.api.InvalidDeviceLinkException;
15 import org.asamk.signal.manager.api.Message;
16 import org.asamk.signal.manager.api.Pair;
17 import org.asamk.signal.manager.api.RecipientIdentifier;
18 import org.asamk.signal.manager.api.SendGroupMessageResults;
19 import org.asamk.signal.manager.api.SendMessageResults;
20 import org.asamk.signal.manager.api.TypingAction;
21 import org.asamk.signal.manager.api.UpdateGroup;
22 import org.asamk.signal.manager.groups.GroupId;
23 import org.asamk.signal.manager.groups.GroupInviteLinkUrl;
24 import org.asamk.signal.manager.groups.GroupNotFoundException;
25 import org.asamk.signal.manager.groups.GroupPermission;
26 import org.asamk.signal.manager.groups.GroupSendingNotAllowedException;
27 import org.asamk.signal.manager.groups.LastGroupAdminException;
28 import org.asamk.signal.manager.groups.NotAGroupMemberException;
29 import org.asamk.signal.manager.storage.recipients.Contact;
30 import org.asamk.signal.manager.storage.recipients.Profile;
31 import org.asamk.signal.manager.storage.recipients.RecipientAddress;
32 import org.freedesktop.dbus.DBusPath;
33 import org.freedesktop.dbus.connections.impl.DBusConnection;
34 import org.freedesktop.dbus.exceptions.DBusException;
35 import org.freedesktop.dbus.interfaces.DBusInterface;
36 import org.whispersystems.signalservice.api.push.exceptions.UnregisteredUserException;
37 import org.whispersystems.signalservice.api.util.UuidUtil;
38
39 import java.io.File;
40 import java.io.IOException;
41 import java.net.URI;
42 import java.net.URISyntaxException;
43 import java.util.ArrayList;
44 import java.util.HashMap;
45 import java.util.List;
46 import java.util.Map;
47 import java.util.Optional;
48 import java.util.Set;
49 import java.util.UUID;
50 import java.util.concurrent.TimeUnit;
51 import java.util.function.Function;
52 import java.util.function.Supplier;
53 import java.util.stream.Collectors;
54
55 /**
56 * This class implements the Manager interface using the DBus Signal interface, where possible.
57 * It's used for the signal-cli dbus client mode (--dbus, --dbus-system)
58 */
59 public class DbusManagerImpl implements Manager {
60
61 private final Signal signal;
62 private final DBusConnection connection;
63
64 public DbusManagerImpl(final Signal signal, DBusConnection connection) {
65 this.signal = signal;
66 this.connection = connection;
67 }
68
69 @Override
70 public String getSelfNumber() {
71 return signal.getSelfNumber();
72 }
73
74 @Override
75 public void checkAccountState() throws IOException {
76 throw new UnsupportedOperationException();
77 }
78
79 @Override
80 public Map<String, Pair<String, UUID>> areUsersRegistered(final Set<String> numbers) throws IOException {
81 final var numbersList = new ArrayList<>(numbers);
82 final var registered = signal.isRegistered(numbersList);
83
84 final var result = new HashMap<String, Pair<String, UUID>>();
85 for (var i = 0; i < numbersList.size(); i++) {
86 result.put(numbersList.get(i),
87 new Pair<>(numbersList.get(i), registered.get(i) ? UuidUtil.UNKNOWN_UUID : null));
88 }
89 return result;
90 }
91
92 @Override
93 public void updateAccountAttributes(final String deviceName) throws IOException {
94 if (deviceName != null) {
95 final var devicePath = signal.getThisDevice();
96 getRemoteObject(devicePath, Signal.Device.class).Set("org.asamk.Signal.Device", "Name", deviceName);
97 }
98 }
99
100 @Override
101 public void updateConfiguration(
102 final Boolean readReceipts,
103 final Boolean unidentifiedDeliveryIndicators,
104 final Boolean typingIndicators,
105 final Boolean linkPreviews
106 ) throws IOException {
107 throw new UnsupportedOperationException();
108 }
109
110 @Override
111 public void setProfile(
112 final String givenName,
113 final String familyName,
114 final String about,
115 final String aboutEmoji,
116 final Optional<File> avatar
117 ) throws IOException {
118 signal.updateProfile(emptyIfNull(givenName),
119 emptyIfNull(familyName),
120 emptyIfNull(about),
121 emptyIfNull(aboutEmoji),
122 avatar == null ? "" : avatar.map(File::getPath).orElse(""),
123 avatar != null && !avatar.isPresent());
124 }
125
126 @Override
127 public void unregister() throws IOException {
128 throw new UnsupportedOperationException();
129 }
130
131 @Override
132 public void deleteAccount() throws IOException {
133 throw new UnsupportedOperationException();
134 }
135
136 @Override
137 public void submitRateLimitRecaptchaChallenge(final String challenge, final String captcha) throws IOException {
138 throw new UnsupportedOperationException();
139 }
140
141 @Override
142 public List<Device> getLinkedDevices() throws IOException {
143 final var thisDevice = signal.getThisDevice();
144 return signal.listDevices().stream().map(d -> {
145 final var device = getRemoteObject(d.getObjectPath(),
146 Signal.Device.class).GetAll("org.asamk.Signal.Device");
147 return new Device((long) device.get("Id").getValue(),
148 (String) device.get("Name").getValue(),
149 (long) device.get("Created").getValue(),
150 (long) device.get("LastSeen").getValue(),
151 thisDevice.equals(d.getObjectPath()));
152 }).collect(Collectors.toList());
153 }
154
155 @Override
156 public void removeLinkedDevices(final long deviceId) throws IOException {
157 final var devicePath = signal.getDevice(deviceId);
158 getRemoteObject(devicePath, Signal.Device.class).removeDevice();
159 }
160
161 @Override
162 public void addDeviceLink(final URI linkUri) throws IOException, InvalidDeviceLinkException {
163 signal.addDevice(linkUri.toString());
164 }
165
166 @Override
167 public void setRegistrationLockPin(final Optional<String> pin) throws IOException {
168 if (pin.isPresent()) {
169 signal.setPin(pin.get());
170 } else {
171 signal.removePin();
172 }
173 }
174
175 @Override
176 public Profile getRecipientProfile(final RecipientIdentifier.Single recipient) throws UnregisteredUserException {
177 throw new UnsupportedOperationException();
178 }
179
180 @Override
181 public List<Group> getGroups() {
182 final var groups = signal.listGroups();
183 return groups.stream().map(Signal.StructGroup::getObjectPath).map(this::getGroup).collect(Collectors.toList());
184 }
185
186 @Override
187 public SendGroupMessageResults quitGroup(
188 final GroupId groupId, final Set<RecipientIdentifier.Single> groupAdmins
189 ) throws GroupNotFoundException, IOException, NotAGroupMemberException, LastGroupAdminException {
190 if (groupAdmins.size() > 0) {
191 throw new UnsupportedOperationException();
192 }
193 final var group = getRemoteObject(signal.getGroup(groupId.serialize()), Signal.Group.class);
194 group.quitGroup();
195 return new SendGroupMessageResults(0, List.of());
196 }
197
198 @Override
199 public void deleteGroup(final GroupId groupId) throws IOException {
200 throw new UnsupportedOperationException();
201 }
202
203 @Override
204 public Pair<GroupId, SendGroupMessageResults> createGroup(
205 final String name, final Set<RecipientIdentifier.Single> members, final File avatarFile
206 ) throws IOException, AttachmentInvalidException {
207 final var newGroupId = signal.createGroup(emptyIfNull(name),
208 members.stream().map(RecipientIdentifier.Single::getIdentifier).collect(Collectors.toList()),
209 avatarFile == null ? "" : avatarFile.getPath());
210 return new Pair<>(GroupId.unknownVersion(newGroupId), new SendGroupMessageResults(0, List.of()));
211 }
212
213 @Override
214 public SendGroupMessageResults updateGroup(
215 final GroupId groupId, final UpdateGroup updateGroup
216 ) throws IOException, GroupNotFoundException, AttachmentInvalidException, NotAGroupMemberException, GroupSendingNotAllowedException {
217 final var group = getRemoteObject(signal.getGroup(groupId.serialize()), Signal.Group.class);
218 if (updateGroup.getName() != null) {
219 group.Set("org.asamk.Signal.Group", "Name", updateGroup.getName());
220 }
221 if (updateGroup.getDescription() != null) {
222 group.Set("org.asamk.Signal.Group", "Description", updateGroup.getDescription());
223 }
224 if (updateGroup.getAvatarFile() != null) {
225 group.Set("org.asamk.Signal.Group",
226 "Avatar",
227 updateGroup.getAvatarFile() == null ? "" : updateGroup.getAvatarFile().getPath());
228 }
229 if (updateGroup.getExpirationTimer() != null) {
230 group.Set("org.asamk.Signal.Group", "MessageExpirationTimer", updateGroup.getExpirationTimer());
231 }
232 if (updateGroup.getAddMemberPermission() != null) {
233 group.Set("org.asamk.Signal.Group", "PermissionAddMember", updateGroup.getAddMemberPermission().name());
234 }
235 if (updateGroup.getEditDetailsPermission() != null) {
236 group.Set("org.asamk.Signal.Group", "PermissionEditDetails", updateGroup.getEditDetailsPermission().name());
237 }
238 if (updateGroup.getIsAnnouncementGroup() != null) {
239 group.Set("org.asamk.Signal.Group",
240 "PermissionSendMessage",
241 updateGroup.getIsAnnouncementGroup()
242 ? GroupPermission.ONLY_ADMINS.name()
243 : GroupPermission.EVERY_MEMBER.name());
244 }
245 if (updateGroup.getMembers() != null) {
246 group.addMembers(updateGroup.getMembers()
247 .stream()
248 .map(RecipientIdentifier.Single::getIdentifier)
249 .collect(Collectors.toList()));
250 }
251 if (updateGroup.getRemoveMembers() != null) {
252 group.removeMembers(updateGroup.getRemoveMembers()
253 .stream()
254 .map(RecipientIdentifier.Single::getIdentifier)
255 .collect(Collectors.toList()));
256 }
257 if (updateGroup.getAdmins() != null) {
258 group.addAdmins(updateGroup.getAdmins()
259 .stream()
260 .map(RecipientIdentifier.Single::getIdentifier)
261 .collect(Collectors.toList()));
262 }
263 if (updateGroup.getRemoveAdmins() != null) {
264 group.removeAdmins(updateGroup.getRemoveAdmins()
265 .stream()
266 .map(RecipientIdentifier.Single::getIdentifier)
267 .collect(Collectors.toList()));
268 }
269 if (updateGroup.isResetGroupLink()) {
270 group.resetLink();
271 }
272 if (updateGroup.getGroupLinkState() != null) {
273 switch (updateGroup.getGroupLinkState()) {
274 case DISABLED -> group.disableLink();
275 case ENABLED -> group.enableLink(false);
276 case ENABLED_WITH_APPROVAL -> group.enableLink(true);
277 }
278 }
279 return new SendGroupMessageResults(0, List.of());
280 }
281
282 @Override
283 public Pair<GroupId, SendGroupMessageResults> joinGroup(final GroupInviteLinkUrl inviteLinkUrl) throws IOException, InactiveGroupLinkException {
284 final var newGroupId = signal.joinGroup(inviteLinkUrl.getUrl());
285 return new Pair<>(GroupId.unknownVersion(newGroupId), new SendGroupMessageResults(0, List.of()));
286 }
287
288 @Override
289 public void sendTypingMessage(
290 final TypingAction action, final Set<RecipientIdentifier> recipients
291 ) throws IOException, UntrustedIdentityException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
292 for (final var recipient : recipients) {
293 if (recipient instanceof RecipientIdentifier.Single) {
294 signal.sendTyping(((RecipientIdentifier.Single) recipient).getIdentifier(),
295 action == TypingAction.STOP);
296 } else if (recipient instanceof RecipientIdentifier.Group) {
297 throw new UnsupportedOperationException();
298 }
299 }
300 }
301
302 @Override
303 public void sendReadReceipt(
304 final RecipientIdentifier.Single sender, final List<Long> messageIds
305 ) throws IOException, UntrustedIdentityException {
306 signal.sendReadReceipt(sender.getIdentifier(), messageIds);
307 }
308
309 @Override
310 public void sendViewedReceipt(
311 final RecipientIdentifier.Single sender, final List<Long> messageIds
312 ) throws IOException, UntrustedIdentityException {
313 throw new UnsupportedOperationException();
314 }
315
316 @Override
317 public SendMessageResults sendMessage(
318 final Message message, final Set<RecipientIdentifier> recipients
319 ) throws IOException, AttachmentInvalidException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
320 return handleMessage(recipients,
321 numbers -> signal.sendMessage(message.messageText(), message.attachments(), numbers),
322 () -> signal.sendNoteToSelfMessage(message.messageText(), message.attachments()),
323 groupId -> signal.sendGroupMessage(message.messageText(), message.attachments(), groupId));
324 }
325
326 @Override
327 public SendMessageResults sendRemoteDeleteMessage(
328 final long targetSentTimestamp, final Set<RecipientIdentifier> recipients
329 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
330 return handleMessage(recipients,
331 numbers -> signal.sendRemoteDeleteMessage(targetSentTimestamp, numbers),
332 () -> signal.sendRemoteDeleteMessage(targetSentTimestamp, signal.getSelfNumber()),
333 groupId -> signal.sendGroupRemoteDeleteMessage(targetSentTimestamp, groupId));
334 }
335
336 @Override
337 public SendMessageResults sendMessageReaction(
338 final String emoji,
339 final boolean remove,
340 final RecipientIdentifier.Single targetAuthor,
341 final long targetSentTimestamp,
342 final Set<RecipientIdentifier> recipients
343 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
344 return handleMessage(recipients,
345 numbers -> signal.sendMessageReaction(emoji,
346 remove,
347 targetAuthor.getIdentifier(),
348 targetSentTimestamp,
349 numbers),
350 () -> signal.sendMessageReaction(emoji,
351 remove,
352 targetAuthor.getIdentifier(),
353 targetSentTimestamp,
354 signal.getSelfNumber()),
355 groupId -> signal.sendGroupMessageReaction(emoji,
356 remove,
357 targetAuthor.getIdentifier(),
358 targetSentTimestamp,
359 groupId));
360 }
361
362 @Override
363 public SendMessageResults sendEndSessionMessage(final Set<RecipientIdentifier.Single> recipients) throws IOException {
364 signal.sendEndSessionMessage(recipients.stream()
365 .map(RecipientIdentifier.Single::getIdentifier)
366 .collect(Collectors.toList()));
367 return new SendMessageResults(0, Map.of());
368 }
369
370 @Override
371 public void setContactName(
372 final RecipientIdentifier.Single recipient, final String name
373 ) throws NotMasterDeviceException, UnregisteredUserException {
374 signal.setContactName(recipient.getIdentifier(), name);
375 }
376
377 @Override
378 public void setContactBlocked(
379 final RecipientIdentifier.Single recipient, final boolean blocked
380 ) throws NotMasterDeviceException, IOException {
381 signal.setContactBlocked(recipient.getIdentifier(), blocked);
382 }
383
384 @Override
385 public void setGroupBlocked(
386 final GroupId groupId, final boolean blocked
387 ) throws GroupNotFoundException, IOException {
388 setGroupProperty(groupId, "IsBlocked", blocked);
389 }
390
391 private void setGroupProperty(final GroupId groupId, final String propertyName, final boolean blocked) {
392 final var group = getRemoteObject(signal.getGroup(groupId.serialize()), Signal.Group.class);
393 group.Set("org.asamk.Signal.Group", propertyName, blocked);
394 }
395
396 @Override
397 public void setExpirationTimer(
398 final RecipientIdentifier.Single recipient, final int messageExpirationTimer
399 ) throws IOException {
400 signal.setExpirationTimer(recipient.getIdentifier(), messageExpirationTimer);
401 }
402
403 @Override
404 public URI uploadStickerPack(final File path) throws IOException, StickerPackInvalidException {
405 try {
406 return new URI(signal.uploadStickerPack(path.getPath()));
407 } catch (URISyntaxException e) {
408 throw new AssertionError(e);
409 }
410 }
411
412 @Override
413 public void requestAllSyncData() throws IOException {
414 signal.sendSyncRequest();
415 }
416
417 @Override
418 public void addReceiveHandler(final ReceiveMessageHandler handler) {
419 throw new UnsupportedOperationException();
420 }
421
422 @Override
423 public void removeReceiveHandler(final ReceiveMessageHandler handler) {
424 throw new UnsupportedOperationException();
425 }
426
427 @Override
428 public boolean isReceiving() {
429 throw new UnsupportedOperationException();
430 }
431
432 @Override
433 public void receiveMessages(final ReceiveMessageHandler handler) throws IOException {
434 throw new UnsupportedOperationException();
435 }
436
437 @Override
438 public void receiveMessages(
439 final long timeout, final TimeUnit unit, final ReceiveMessageHandler handler
440 ) throws IOException {
441 throw new UnsupportedOperationException();
442 }
443
444 @Override
445 public void setIgnoreAttachments(final boolean ignoreAttachments) {
446 throw new UnsupportedOperationException();
447 }
448
449 @Override
450 public boolean hasCaughtUpWithOldMessages() {
451 throw new UnsupportedOperationException();
452 }
453
454 @Override
455 public boolean isContactBlocked(final RecipientIdentifier.Single recipient) {
456 return signal.isContactBlocked(recipient.getIdentifier());
457 }
458
459 @Override
460 public File getAttachmentFile(final String attachmentId) {
461 throw new UnsupportedOperationException();
462 }
463
464 @Override
465 public void sendContacts() throws IOException {
466 signal.sendContacts();
467 }
468
469 @Override
470 public List<Pair<RecipientAddress, Contact>> getContacts() {
471 throw new UnsupportedOperationException();
472 }
473
474 @Override
475 public String getContactOrProfileName(final RecipientIdentifier.Single recipient) {
476 return signal.getContactName(recipient.getIdentifier());
477 }
478
479 @Override
480 public Group getGroup(final GroupId groupId) {
481 final var groupPath = signal.getGroup(groupId.serialize());
482 return getGroup(groupPath);
483 }
484
485 @SuppressWarnings("unchecked")
486 private Group getGroup(final DBusPath groupPath) {
487 final var group = getRemoteObject(groupPath, Signal.Group.class).GetAll("org.asamk.Signal.Group");
488 final var id = (byte[]) group.get("Id").getValue();
489 try {
490 return new Group(GroupId.unknownVersion(id),
491 (String) group.get("Name").getValue(),
492 (String) group.get("Description").getValue(),
493 GroupInviteLinkUrl.fromUri((String) group.get("GroupInviteLink").getValue()),
494 ((List<String>) group.get("Members").getValue()).stream()
495 .map(m -> new RecipientAddress(null, m))
496 .collect(Collectors.toSet()),
497 ((List<String>) group.get("PendingMembers").getValue()).stream()
498 .map(m -> new RecipientAddress(null, m))
499 .collect(Collectors.toSet()),
500 ((List<String>) group.get("RequestingMembers").getValue()).stream()
501 .map(m -> new RecipientAddress(null, m))
502 .collect(Collectors.toSet()),
503 ((List<String>) group.get("Admins").getValue()).stream()
504 .map(m -> new RecipientAddress(null, m))
505 .collect(Collectors.toSet()),
506 (boolean) group.get("IsBlocked").getValue(),
507 (int) group.get("MessageExpirationTimer").getValue(),
508 GroupPermission.valueOf((String) group.get("PermissionAddMember").getValue()),
509 GroupPermission.valueOf((String) group.get("PermissionEditDetails").getValue()),
510 GroupPermission.valueOf((String) group.get("PermissionSendMessage").getValue()),
511 (boolean) group.get("IsMember").getValue(),
512 (boolean) group.get("IsAdmin").getValue());
513 } catch (GroupInviteLinkUrl.InvalidGroupLinkException | GroupInviteLinkUrl.UnknownGroupLinkVersionException e) {
514 throw new AssertionError(e);
515 }
516 }
517
518 @Override
519 public List<Identity> getIdentities() {
520 throw new UnsupportedOperationException();
521 }
522
523 @Override
524 public List<Identity> getIdentities(final RecipientIdentifier.Single recipient) {
525 throw new UnsupportedOperationException();
526 }
527
528 @Override
529 public boolean trustIdentityVerified(final RecipientIdentifier.Single recipient, final byte[] fingerprint) {
530 throw new UnsupportedOperationException();
531 }
532
533 @Override
534 public boolean trustIdentityVerifiedSafetyNumber(
535 final RecipientIdentifier.Single recipient, final String safetyNumber
536 ) {
537 throw new UnsupportedOperationException();
538 }
539
540 @Override
541 public boolean trustIdentityVerifiedSafetyNumber(
542 final RecipientIdentifier.Single recipient, final byte[] safetyNumber
543 ) {
544 throw new UnsupportedOperationException();
545 }
546
547 @Override
548 public boolean trustIdentityAllKeys(final RecipientIdentifier.Single recipient) {
549 throw new UnsupportedOperationException();
550 }
551
552 @Override
553 public void close() throws IOException {
554 }
555
556 private SendMessageResults handleMessage(
557 Set<RecipientIdentifier> recipients,
558 Function<List<String>, Long> recipientsHandler,
559 Supplier<Long> noteToSelfHandler,
560 Function<byte[], Long> groupHandler
561 ) {
562 long timestamp = 0;
563 final var singleRecipients = recipients.stream()
564 .filter(r -> r instanceof RecipientIdentifier.Single)
565 .map(RecipientIdentifier.Single.class::cast)
566 .map(RecipientIdentifier.Single::getIdentifier)
567 .collect(Collectors.toList());
568 if (singleRecipients.size() > 0) {
569 timestamp = recipientsHandler.apply(singleRecipients);
570 }
571
572 if (recipients.contains(RecipientIdentifier.NoteToSelf.INSTANCE)) {
573 timestamp = noteToSelfHandler.get();
574 }
575 final var groupRecipients = recipients.stream()
576 .filter(r -> r instanceof RecipientIdentifier.Group)
577 .map(RecipientIdentifier.Group.class::cast)
578 .map(RecipientIdentifier.Group::groupId)
579 .collect(Collectors.toList());
580 for (final var groupId : groupRecipients) {
581 timestamp = groupHandler.apply(groupId.serialize());
582 }
583 return new SendMessageResults(timestamp, Map.of());
584 }
585
586 private String emptyIfNull(final String string) {
587 return string == null ? "" : string;
588 }
589
590 private <T extends DBusInterface> T getRemoteObject(final DBusPath devicePath, final Class<T> type) {
591 try {
592 return connection.getRemoteObject(DbusConfig.getBusname(), devicePath.getPath(), type);
593 } catch (DBusException e) {
594 throw new AssertionError(e);
595 }
596 }
597 }