]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/storage/recipients/RecipientStore.java
44c0bafaa4fbb786b2124759dbb34a25d971a8db
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / storage / recipients / RecipientStore.java
1 package org.asamk.signal.manager.storage.recipients;
2
3 import org.asamk.signal.manager.api.Contact;
4 import org.asamk.signal.manager.api.Pair;
5 import org.asamk.signal.manager.api.Profile;
6 import org.asamk.signal.manager.api.UnregisteredRecipientException;
7 import org.asamk.signal.manager.storage.Database;
8 import org.asamk.signal.manager.storage.Utils;
9 import org.asamk.signal.manager.storage.contacts.ContactsStore;
10 import org.asamk.signal.manager.storage.profiles.ProfileStore;
11 import org.signal.libsignal.zkgroup.InvalidInputException;
12 import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredential;
13 import org.signal.libsignal.zkgroup.profiles.ProfileKey;
14 import org.slf4j.Logger;
15 import org.slf4j.LoggerFactory;
16 import org.whispersystems.signalservice.api.push.ServiceId;
17 import org.whispersystems.signalservice.api.push.ServiceId.ACI;
18 import org.whispersystems.signalservice.api.push.ServiceId.PNI;
19 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
20 import org.whispersystems.signalservice.api.util.UuidUtil;
21
22 import java.sql.Connection;
23 import java.sql.ResultSet;
24 import java.sql.SQLException;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Collection;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Objects;
32 import java.util.Optional;
33 import java.util.Set;
34 import java.util.function.Supplier;
35 import java.util.stream.Collectors;
36
37 public class RecipientStore implements RecipientIdCreator, RecipientResolver, RecipientTrustedResolver, ContactsStore, ProfileStore {
38
39 private final static Logger logger = LoggerFactory.getLogger(RecipientStore.class);
40 private static final String TABLE_RECIPIENT = "recipient";
41 private static final String SQL_IS_CONTACT = "r.given_name IS NOT NULL OR r.family_name IS NOT NULL OR r.expiration_time > 0 OR r.profile_sharing = TRUE OR r.color IS NOT NULL OR r.blocked = TRUE OR r.archived = TRUE";
42
43 private final RecipientMergeHandler recipientMergeHandler;
44 private final SelfAddressProvider selfAddressProvider;
45 private final Database database;
46
47 private final Object recipientsLock = new Object();
48 private final Map<Long, Long> recipientsMerged = new HashMap<>();
49
50 private final Map<ServiceId, RecipientWithAddress> recipientAddressCache = new HashMap<>();
51
52 public static void createSql(Connection connection) throws SQLException {
53 // When modifying the CREATE statement here, also add a migration in AccountDatabase.java
54 try (final var statement = connection.createStatement()) {
55 statement.executeUpdate("""
56 CREATE TABLE recipient (
57 _id INTEGER PRIMARY KEY AUTOINCREMENT,
58 number TEXT UNIQUE,
59 username TEXT UNIQUE,
60 uuid BLOB UNIQUE,
61 pni BLOB UNIQUE,
62 profile_key BLOB,
63 profile_key_credential BLOB,
64
65 given_name TEXT,
66 family_name TEXT,
67 color TEXT,
68
69 expiration_time INTEGER NOT NULL DEFAULT 0,
70 blocked INTEGER NOT NULL DEFAULT FALSE,
71 archived INTEGER NOT NULL DEFAULT FALSE,
72 profile_sharing INTEGER NOT NULL DEFAULT FALSE,
73
74 profile_last_update_timestamp INTEGER NOT NULL DEFAULT 0,
75 profile_given_name TEXT,
76 profile_family_name TEXT,
77 profile_about TEXT,
78 profile_about_emoji TEXT,
79 profile_avatar_url_path TEXT,
80 profile_mobile_coin_address BLOB,
81 profile_unidentified_access_mode TEXT,
82 profile_capabilities TEXT
83 ) STRICT;
84 """);
85 }
86 }
87
88 public RecipientStore(
89 final RecipientMergeHandler recipientMergeHandler,
90 final SelfAddressProvider selfAddressProvider,
91 final Database database
92 ) {
93 this.recipientMergeHandler = recipientMergeHandler;
94 this.selfAddressProvider = selfAddressProvider;
95 this.database = database;
96 }
97
98 public RecipientAddress resolveRecipientAddress(RecipientId recipientId) {
99 final var sql = (
100 """
101 SELECT r.number, r.uuid, r.pni, r.username
102 FROM %s r
103 WHERE r._id = ?
104 """
105 ).formatted(TABLE_RECIPIENT);
106 try (final var connection = database.getConnection()) {
107 try (final var statement = connection.prepareStatement(sql)) {
108 statement.setLong(1, recipientId.id());
109 return Utils.executeQuerySingleRow(statement, this::getRecipientAddressFromResultSet);
110 }
111 } catch (SQLException e) {
112 throw new RuntimeException("Failed read from recipient store", e);
113 }
114 }
115
116 public Collection<RecipientId> getRecipientIdsWithEnabledProfileSharing() {
117 final var sql = (
118 """
119 SELECT r._id
120 FROM %s r
121 WHERE r.blocked = FALSE AND r.profile_sharing = TRUE
122 """
123 ).formatted(TABLE_RECIPIENT);
124 try (final var connection = database.getConnection()) {
125 try (final var statement = connection.prepareStatement(sql)) {
126 try (var result = Utils.executeQueryForStream(statement, this::getRecipientIdFromResultSet)) {
127 return result.toList();
128 }
129 }
130 } catch (SQLException e) {
131 throw new RuntimeException("Failed read from recipient store", e);
132 }
133 }
134
135 @Override
136 public RecipientId resolveRecipient(final long rawRecipientId) {
137 final var sql = (
138 """
139 SELECT r._id
140 FROM %s r
141 WHERE r._id = ?
142 """
143 ).formatted(TABLE_RECIPIENT);
144 try (final var connection = database.getConnection()) {
145 try (final var statement = connection.prepareStatement(sql)) {
146 statement.setLong(1, rawRecipientId);
147 return Utils.executeQueryForOptional(statement, this::getRecipientIdFromResultSet).orElse(null);
148 }
149 } catch (SQLException e) {
150 throw new RuntimeException("Failed read from recipient store", e);
151 }
152 }
153
154 @Override
155 public RecipientId resolveRecipient(final String identifier) {
156 final var serviceId = ServiceId.parseOrNull(identifier);
157 if (serviceId != null) {
158 return resolveRecipient(serviceId);
159 } else {
160 return resolveRecipientByNumber(identifier);
161 }
162 }
163
164 private RecipientId resolveRecipientByNumber(final String number) {
165 synchronized (recipientsLock) {
166 final RecipientId recipientId;
167 try (final var connection = database.getConnection()) {
168 connection.setAutoCommit(false);
169 recipientId = resolveRecipientLocked(connection, number);
170 connection.commit();
171 } catch (SQLException e) {
172 throw new RuntimeException("Failed read recipient store", e);
173 }
174 return recipientId;
175 }
176 }
177
178 @Override
179 public RecipientId resolveRecipient(final ServiceId serviceId) {
180 synchronized (recipientsLock) {
181 final var recipientWithAddress = recipientAddressCache.get(serviceId);
182 if (recipientWithAddress != null) {
183 return recipientWithAddress.id();
184 }
185 try (final var connection = database.getConnection()) {
186 connection.setAutoCommit(false);
187 final var recipientId = resolveRecipientLocked(connection, serviceId);
188 connection.commit();
189 return recipientId;
190 } catch (SQLException e) {
191 throw new RuntimeException("Failed read recipient store", e);
192 }
193 }
194 }
195
196 /**
197 * Should only be used for recipientIds from the database.
198 * Where the foreign key relations ensure a valid recipientId.
199 */
200 @Override
201 public RecipientId create(final long recipientId) {
202 return new RecipientId(recipientId, this);
203 }
204
205 public RecipientId resolveRecipientByNumber(
206 final String number, Supplier<ServiceId> serviceIdSupplier
207 ) throws UnregisteredRecipientException {
208 final Optional<RecipientWithAddress> byNumber;
209 try (final var connection = database.getConnection()) {
210 byNumber = findByNumber(connection, number);
211 } catch (SQLException e) {
212 throw new RuntimeException("Failed read from recipient store", e);
213 }
214 if (byNumber.isEmpty() || byNumber.get().address().serviceId().isEmpty()) {
215 final var serviceId = serviceIdSupplier.get();
216 if (serviceId == null) {
217 throw new UnregisteredRecipientException(new org.asamk.signal.manager.api.RecipientAddress(null,
218 number));
219 }
220
221 return resolveRecipient(serviceId);
222 }
223 return byNumber.get().id();
224 }
225
226 public Optional<RecipientId> resolveRecipientByNumberOptional(final String number) {
227 final Optional<RecipientWithAddress> byNumber;
228 try (final var connection = database.getConnection()) {
229 byNumber = findByNumber(connection, number);
230 } catch (SQLException e) {
231 throw new RuntimeException("Failed read from recipient store", e);
232 }
233 return byNumber.map(RecipientWithAddress::id);
234 }
235
236 public RecipientId resolveRecipientByUsername(
237 final String username, Supplier<ACI> aciSupplier
238 ) throws UnregisteredRecipientException {
239 final Optional<RecipientWithAddress> byUsername;
240 try (final var connection = database.getConnection()) {
241 byUsername = findByUsername(connection, username);
242 } catch (SQLException e) {
243 throw new RuntimeException("Failed read from recipient store", e);
244 }
245 if (byUsername.isEmpty() || byUsername.get().address().serviceId().isEmpty()) {
246 final var aci = aciSupplier.get();
247 if (aci == null) {
248 throw new UnregisteredRecipientException(new org.asamk.signal.manager.api.RecipientAddress(null,
249 null,
250 username));
251 }
252
253 return resolveRecipientTrusted(aci, username);
254 }
255 return byUsername.get().id();
256 }
257
258 public RecipientId resolveRecipient(RecipientAddress address) {
259 synchronized (recipientsLock) {
260 final RecipientId recipientId;
261 try (final var connection = database.getConnection()) {
262 connection.setAutoCommit(false);
263 recipientId = resolveRecipientLocked(connection, address);
264 connection.commit();
265 } catch (SQLException e) {
266 throw new RuntimeException("Failed read recipient store", e);
267 }
268 return recipientId;
269 }
270 }
271
272 @Override
273 public RecipientId resolveSelfRecipientTrusted(RecipientAddress address) {
274 return resolveRecipientTrusted(address, true);
275 }
276
277 public RecipientId resolveRecipientTrusted(RecipientAddress address) {
278 return resolveRecipientTrusted(address, false);
279 }
280
281 @Override
282 public RecipientId resolveRecipientTrusted(SignalServiceAddress address) {
283 return resolveRecipientTrusted(new RecipientAddress(address), false);
284 }
285
286 @Override
287 public RecipientId resolveRecipientTrusted(
288 final Optional<ACI> aci, final Optional<PNI> pni, final Optional<String> number
289 ) {
290 final var serviceId = aci.map(a -> (ServiceId) a).or(() -> pni);
291 return resolveRecipientTrusted(new RecipientAddress(serviceId, pni, number, Optional.empty()), false);
292 }
293
294 @Override
295 public RecipientId resolveRecipientTrusted(final ACI aci, final String username) {
296 return resolveRecipientTrusted(new RecipientAddress(aci, null, null, username), false);
297 }
298
299 @Override
300 public void storeContact(RecipientId recipientId, final Contact contact) {
301 try (final var connection = database.getConnection()) {
302 storeContact(connection, recipientId, contact);
303 } catch (SQLException e) {
304 throw new RuntimeException("Failed update recipient store", e);
305 }
306 }
307
308 @Override
309 public Contact getContact(RecipientId recipientId) {
310 try (final var connection = database.getConnection()) {
311 return getContact(connection, recipientId);
312 } catch (SQLException e) {
313 throw new RuntimeException("Failed read from recipient store", e);
314 }
315 }
316
317 @Override
318 public List<Pair<RecipientId, Contact>> getContacts() {
319 final var sql = (
320 """
321 SELECT r._id, r.given_name, r.family_name, r.expiration_time, r.profile_sharing, r.color, r.blocked, r.archived
322 FROM %s r
323 WHERE (r.number IS NOT NULL OR r.uuid IS NOT NULL) AND %s
324 """
325 ).formatted(TABLE_RECIPIENT, SQL_IS_CONTACT);
326 try (final var connection = database.getConnection()) {
327 try (final var statement = connection.prepareStatement(sql)) {
328 try (var result = Utils.executeQueryForStream(statement,
329 resultSet -> new Pair<>(getRecipientIdFromResultSet(resultSet),
330 getContactFromResultSet(resultSet)))) {
331 return result.toList();
332 }
333 }
334 } catch (SQLException e) {
335 throw new RuntimeException("Failed read from recipient store", e);
336 }
337 }
338
339 public List<Recipient> getRecipients(
340 boolean onlyContacts, Optional<Boolean> blocked, Set<RecipientId> recipientIds, Optional<String> name
341 ) {
342 final var sqlWhere = new ArrayList<String>();
343 if (onlyContacts) {
344 sqlWhere.add("(" + SQL_IS_CONTACT + ")");
345 }
346 if (blocked.isPresent()) {
347 sqlWhere.add("r.blocked = ?");
348 }
349 if (!recipientIds.isEmpty()) {
350 final var recipientIdsCommaSeparated = recipientIds.stream()
351 .map(recipientId -> String.valueOf(recipientId.id()))
352 .collect(Collectors.joining(","));
353 sqlWhere.add("r._id IN (" + recipientIdsCommaSeparated + ")");
354 }
355 final var sql = (
356 """
357 SELECT r._id,
358 r.number, r.uuid, r.pni, r.username,
359 r.profile_key, r.profile_key_credential,
360 r.given_name, r.family_name, r.expiration_time, r.profile_sharing, r.color, r.blocked, r.archived,
361 r.profile_last_update_timestamp, r.profile_given_name, r.profile_family_name, r.profile_about, r.profile_about_emoji, r.profile_avatar_url_path, r.profile_mobile_coin_address, r.profile_unidentified_access_mode, r.profile_capabilities
362 FROM %s r
363 WHERE (r.number IS NOT NULL OR r.uuid IS NOT NULL) AND %s
364 """
365 ).formatted(TABLE_RECIPIENT, sqlWhere.isEmpty() ? "TRUE" : String.join(" AND ", sqlWhere));
366 try (final var connection = database.getConnection()) {
367 try (final var statement = connection.prepareStatement(sql)) {
368 if (blocked.isPresent()) {
369 statement.setBoolean(1, blocked.get());
370 }
371 try (var result = Utils.executeQueryForStream(statement, this::getRecipientFromResultSet)) {
372 return result.filter(r -> name.isEmpty() || (
373 r.getContact() != null && name.get().equals(r.getContact().getName())
374 ) || (r.getProfile() != null && name.get().equals(r.getProfile().getDisplayName()))).toList();
375 }
376 }
377 } catch (SQLException e) {
378 throw new RuntimeException("Failed read from recipient store", e);
379 }
380 }
381
382 public Set<String> getAllNumbers() {
383 final var sql = (
384 """
385 SELECT r.number
386 FROM %s r
387 WHERE r.number IS NOT NULL
388 """
389 ).formatted(TABLE_RECIPIENT);
390 try (final var connection = database.getConnection()) {
391 try (final var statement = connection.prepareStatement(sql)) {
392 return Utils.executeQueryForStream(statement, resultSet -> resultSet.getString("number"))
393 .filter(Objects::nonNull)
394 .filter(n -> {
395 try {
396 Long.parseLong(n);
397 return true;
398 } catch (NumberFormatException e) {
399 return false;
400 }
401 })
402 .collect(Collectors.toSet());
403 }
404 } catch (SQLException e) {
405 throw new RuntimeException("Failed read from recipient store", e);
406 }
407 }
408
409 public Map<ServiceId, ProfileKey> getServiceIdToProfileKeyMap() {
410 final var sql = (
411 """
412 SELECT r.uuid, r.profile_key
413 FROM %s r
414 WHERE r.uuid IS NOT NULL AND r.profile_key IS NOT NULL
415 """
416 ).formatted(TABLE_RECIPIENT);
417 try (final var connection = database.getConnection()) {
418 try (final var statement = connection.prepareStatement(sql)) {
419 return Utils.executeQueryForStream(statement, resultSet -> {
420 final var serviceId = ServiceId.parseOrThrow(resultSet.getBytes("uuid"));
421 final var profileKey = getProfileKeyFromResultSet(resultSet);
422 return new Pair<>(serviceId, profileKey);
423 }).filter(Objects::nonNull).collect(Collectors.toMap(Pair::first, Pair::second));
424 }
425 } catch (SQLException e) {
426 throw new RuntimeException("Failed read from recipient store", e);
427 }
428 }
429
430 @Override
431 public void deleteContact(RecipientId recipientId) {
432 storeContact(recipientId, null);
433 }
434
435 public void deleteRecipientData(RecipientId recipientId) {
436 logger.debug("Deleting recipient data for {}", recipientId);
437 synchronized (recipientsLock) {
438 recipientAddressCache.entrySet()
439 .stream()
440 .filter(e -> e.getValue().id().equals(recipientId))
441 .forEach(e -> recipientAddressCache.remove(e.getKey()));
442 try (final var connection = database.getConnection()) {
443 connection.setAutoCommit(false);
444 storeContact(connection, recipientId, null);
445 storeProfile(connection, recipientId, null);
446 storeProfileKey(connection, recipientId, null, false);
447 storeExpiringProfileKeyCredential(connection, recipientId, null);
448 deleteRecipient(connection, recipientId);
449 connection.commit();
450 } catch (SQLException e) {
451 throw new RuntimeException("Failed update recipient store", e);
452 }
453 }
454 }
455
456 @Override
457 public Profile getProfile(final RecipientId recipientId) {
458 try (final var connection = database.getConnection()) {
459 return getProfile(connection, recipientId);
460 } catch (SQLException e) {
461 throw new RuntimeException("Failed read from recipient store", e);
462 }
463 }
464
465 @Override
466 public ProfileKey getProfileKey(final RecipientId recipientId) {
467 try (final var connection = database.getConnection()) {
468 return getProfileKey(connection, recipientId);
469 } catch (SQLException e) {
470 throw new RuntimeException("Failed read from recipient store", e);
471 }
472 }
473
474 @Override
475 public ExpiringProfileKeyCredential getExpiringProfileKeyCredential(final RecipientId recipientId) {
476 try (final var connection = database.getConnection()) {
477 return getExpiringProfileKeyCredential(connection, recipientId);
478 } catch (SQLException e) {
479 throw new RuntimeException("Failed read from recipient store", e);
480 }
481 }
482
483 @Override
484 public void storeProfile(RecipientId recipientId, final Profile profile) {
485 try (final var connection = database.getConnection()) {
486 storeProfile(connection, recipientId, profile);
487 } catch (SQLException e) {
488 throw new RuntimeException("Failed update recipient store", e);
489 }
490 }
491
492 @Override
493 public void storeSelfProfileKey(final RecipientId recipientId, final ProfileKey profileKey) {
494 try (final var connection = database.getConnection()) {
495 storeProfileKey(connection, recipientId, profileKey, false);
496 } catch (SQLException e) {
497 throw new RuntimeException("Failed update recipient store", e);
498 }
499 }
500
501 @Override
502 public void storeProfileKey(RecipientId recipientId, final ProfileKey profileKey) {
503 try (final var connection = database.getConnection()) {
504 storeProfileKey(connection, recipientId, profileKey, true);
505 } catch (SQLException e) {
506 throw new RuntimeException("Failed update recipient store", e);
507 }
508 }
509
510 @Override
511 public void storeExpiringProfileKeyCredential(
512 RecipientId recipientId, final ExpiringProfileKeyCredential profileKeyCredential
513 ) {
514 try (final var connection = database.getConnection()) {
515 storeExpiringProfileKeyCredential(connection, recipientId, profileKeyCredential);
516 } catch (SQLException e) {
517 throw new RuntimeException("Failed update recipient store", e);
518 }
519 }
520
521 void addLegacyRecipients(final Map<RecipientId, Recipient> recipients) {
522 logger.debug("Migrating legacy recipients to database");
523 long start = System.nanoTime();
524 final var sql = (
525 """
526 INSERT INTO %s (_id, number, uuid)
527 VALUES (?, ?, ?)
528 """
529 ).formatted(TABLE_RECIPIENT);
530 try (final var connection = database.getConnection()) {
531 connection.setAutoCommit(false);
532 try (final var statement = connection.prepareStatement("DELETE FROM %s".formatted(TABLE_RECIPIENT))) {
533 statement.executeUpdate();
534 }
535 try (final var statement = connection.prepareStatement(sql)) {
536 for (final var recipient : recipients.values()) {
537 statement.setLong(1, recipient.getRecipientId().id());
538 statement.setString(2, recipient.getAddress().number().orElse(null));
539 statement.setBytes(3,
540 recipient.getAddress()
541 .serviceId()
542 .map(ServiceId::getRawUuid)
543 .map(UuidUtil::toByteArray)
544 .orElse(null));
545 statement.executeUpdate();
546 }
547 }
548 logger.debug("Initial inserts took {}ms", (System.nanoTime() - start) / 1000000);
549
550 for (final var recipient : recipients.values()) {
551 if (recipient.getContact() != null) {
552 storeContact(connection, recipient.getRecipientId(), recipient.getContact());
553 }
554 if (recipient.getProfile() != null) {
555 storeProfile(connection, recipient.getRecipientId(), recipient.getProfile());
556 }
557 if (recipient.getProfileKey() != null) {
558 storeProfileKey(connection, recipient.getRecipientId(), recipient.getProfileKey(), false);
559 }
560 if (recipient.getExpiringProfileKeyCredential() != null) {
561 storeExpiringProfileKeyCredential(connection,
562 recipient.getRecipientId(),
563 recipient.getExpiringProfileKeyCredential());
564 }
565 }
566 connection.commit();
567 } catch (SQLException e) {
568 throw new RuntimeException("Failed update recipient store", e);
569 }
570 logger.debug("Complete recipients migration took {}ms", (System.nanoTime() - start) / 1000000);
571 }
572
573 long getActualRecipientId(long recipientId) {
574 while (recipientsMerged.containsKey(recipientId)) {
575 final var newRecipientId = recipientsMerged.get(recipientId);
576 logger.debug("Using {} instead of {}, because recipients have been merged", newRecipientId, recipientId);
577 recipientId = newRecipientId;
578 }
579 return recipientId;
580 }
581
582 private void storeContact(
583 final Connection connection, final RecipientId recipientId, final Contact contact
584 ) throws SQLException {
585 final var sql = (
586 """
587 UPDATE %s
588 SET given_name = ?, family_name = ?, expiration_time = ?, profile_sharing = ?, color = ?, blocked = ?, archived = ?
589 WHERE _id = ?
590 """
591 ).formatted(TABLE_RECIPIENT);
592 try (final var statement = connection.prepareStatement(sql)) {
593 statement.setString(1, contact == null ? null : contact.getGivenName());
594 statement.setString(2, contact == null ? null : contact.getFamilyName());
595 statement.setInt(3, contact == null ? 0 : contact.getMessageExpirationTime());
596 statement.setBoolean(4, contact != null && contact.isProfileSharingEnabled());
597 statement.setString(5, contact == null ? null : contact.getColor());
598 statement.setBoolean(6, contact != null && contact.isBlocked());
599 statement.setBoolean(7, contact != null && contact.isArchived());
600 statement.setLong(8, recipientId.id());
601 statement.executeUpdate();
602 }
603 }
604
605 private void storeExpiringProfileKeyCredential(
606 final Connection connection,
607 final RecipientId recipientId,
608 final ExpiringProfileKeyCredential profileKeyCredential
609 ) throws SQLException {
610 final var sql = (
611 """
612 UPDATE %s
613 SET profile_key_credential = ?
614 WHERE _id = ?
615 """
616 ).formatted(TABLE_RECIPIENT);
617 try (final var statement = connection.prepareStatement(sql)) {
618 statement.setBytes(1, profileKeyCredential == null ? null : profileKeyCredential.serialize());
619 statement.setLong(2, recipientId.id());
620 statement.executeUpdate();
621 }
622 }
623
624 private void storeProfile(
625 final Connection connection, final RecipientId recipientId, final Profile profile
626 ) throws SQLException {
627 final var sql = (
628 """
629 UPDATE %s
630 SET profile_last_update_timestamp = ?, profile_given_name = ?, profile_family_name = ?, profile_about = ?, profile_about_emoji = ?, profile_avatar_url_path = ?, profile_mobile_coin_address = ?, profile_unidentified_access_mode = ?, profile_capabilities = ?
631 WHERE _id = ?
632 """
633 ).formatted(TABLE_RECIPIENT);
634 try (final var statement = connection.prepareStatement(sql)) {
635 statement.setLong(1, profile == null ? 0 : profile.getLastUpdateTimestamp());
636 statement.setString(2, profile == null ? null : profile.getGivenName());
637 statement.setString(3, profile == null ? null : profile.getFamilyName());
638 statement.setString(4, profile == null ? null : profile.getAbout());
639 statement.setString(5, profile == null ? null : profile.getAboutEmoji());
640 statement.setString(6, profile == null ? null : profile.getAvatarUrlPath());
641 statement.setBytes(7, profile == null ? null : profile.getMobileCoinAddress());
642 statement.setString(8, profile == null ? null : profile.getUnidentifiedAccessMode().name());
643 statement.setString(9,
644 profile == null
645 ? null
646 : profile.getCapabilities().stream().map(Enum::name).collect(Collectors.joining(",")));
647 statement.setLong(10, recipientId.id());
648 statement.executeUpdate();
649 }
650 }
651
652 private void storeProfileKey(
653 Connection connection, RecipientId recipientId, final ProfileKey profileKey, boolean resetProfile
654 ) throws SQLException {
655 if (profileKey != null) {
656 final var recipientProfileKey = getProfileKey(recipientId);
657 if (profileKey.equals(recipientProfileKey)) {
658 final var recipientProfile = getProfile(recipientId);
659 if (recipientProfile == null || (
660 recipientProfile.getUnidentifiedAccessMode() != Profile.UnidentifiedAccessMode.UNKNOWN
661 && recipientProfile.getUnidentifiedAccessMode()
662 != Profile.UnidentifiedAccessMode.DISABLED
663 )) {
664 return;
665 }
666 }
667 }
668
669 final var sql = (
670 """
671 UPDATE %s
672 SET profile_key = ?, profile_key_credential = NULL%s
673 WHERE _id = ?
674 """
675 ).formatted(TABLE_RECIPIENT, resetProfile ? ", profile_last_update_timestamp = 0" : "");
676 try (final var statement = connection.prepareStatement(sql)) {
677 statement.setBytes(1, profileKey == null ? null : profileKey.serialize());
678 statement.setLong(2, recipientId.id());
679 statement.executeUpdate();
680 }
681 }
682
683 private RecipientId resolveRecipientTrusted(RecipientAddress address, boolean isSelf) {
684 final Pair<RecipientId, List<RecipientId>> pair;
685 synchronized (recipientsLock) {
686 try (final var connection = database.getConnection()) {
687 connection.setAutoCommit(false);
688 if (address.hasSingleIdentifier() || (
689 !isSelf && selfAddressProvider.getSelfAddress().matches(address)
690 )) {
691 pair = new Pair<>(resolveRecipientLocked(connection, address), List.of());
692 } else {
693 pair = MergeRecipientHelper.resolveRecipientTrustedLocked(new HelperStore(connection), address);
694
695 for (final var toBeMergedRecipientId : pair.second()) {
696 mergeRecipientsLocked(connection, pair.first(), toBeMergedRecipientId);
697 }
698 }
699 connection.commit();
700 } catch (SQLException e) {
701 throw new RuntimeException("Failed update recipient store", e);
702 }
703 }
704
705 if (!pair.second().isEmpty()) {
706 try (final var connection = database.getConnection()) {
707 for (final var toBeMergedRecipientId : pair.second()) {
708 recipientMergeHandler.mergeRecipients(connection, pair.first(), toBeMergedRecipientId);
709 deleteRecipient(connection, toBeMergedRecipientId);
710 synchronized (recipientsLock) {
711 recipientAddressCache.entrySet()
712 .stream()
713 .filter(e -> e.getValue().id().equals(toBeMergedRecipientId))
714 .forEach(e -> recipientAddressCache.remove(e.getKey()));
715 }
716 }
717 } catch (SQLException e) {
718 throw new RuntimeException("Failed update recipient store", e);
719 }
720 }
721 return pair.first();
722 }
723
724 private RecipientId resolveRecipientLocked(
725 Connection connection, RecipientAddress address
726 ) throws SQLException {
727 final var byServiceId = address.serviceId().isEmpty()
728 ? Optional.<RecipientWithAddress>empty()
729 : findByServiceId(connection, address.serviceId().get());
730
731 if (byServiceId.isPresent()) {
732 return byServiceId.get().id();
733 }
734
735 final var byPni = address.pni().isEmpty()
736 ? Optional.<RecipientWithAddress>empty()
737 : findByServiceId(connection, address.pni().get());
738
739 if (byPni.isPresent()) {
740 return byPni.get().id();
741 }
742
743 final var byNumber = address.number().isEmpty()
744 ? Optional.<RecipientWithAddress>empty()
745 : findByNumber(connection, address.number().get());
746
747 if (byNumber.isPresent()) {
748 return byNumber.get().id();
749 }
750
751 logger.debug("Got new recipient, both serviceId and number are unknown");
752
753 if (address.serviceId().isEmpty()) {
754 return addNewRecipient(connection, address);
755 }
756
757 return addNewRecipient(connection, new RecipientAddress(address.serviceId().get()));
758 }
759
760 private RecipientId resolveRecipientLocked(Connection connection, ServiceId serviceId) throws SQLException {
761 final var recipient = findByServiceId(connection, serviceId);
762
763 if (recipient.isEmpty()) {
764 logger.debug("Got new recipient, serviceId is unknown");
765 return addNewRecipient(connection, new RecipientAddress(serviceId));
766 }
767
768 return recipient.get().id();
769 }
770
771 private RecipientId resolveRecipientLocked(Connection connection, String number) throws SQLException {
772 final var recipient = findByNumber(connection, number);
773
774 if (recipient.isEmpty()) {
775 logger.debug("Got new recipient, number is unknown");
776 return addNewRecipient(connection, new RecipientAddress(null, number));
777 }
778
779 return recipient.get().id();
780 }
781
782 private RecipientId addNewRecipient(
783 final Connection connection, final RecipientAddress address
784 ) throws SQLException {
785 final var sql = (
786 """
787 INSERT INTO %s (number, uuid, pni)
788 VALUES (?, ?, ?)
789 RETURNING _id
790 """
791 ).formatted(TABLE_RECIPIENT);
792 try (final var statement = connection.prepareStatement(sql)) {
793 statement.setString(1, address.number().orElse(null));
794 statement.setBytes(2,
795 address.serviceId().map(ServiceId::getRawUuid).map(UuidUtil::toByteArray).orElse(null));
796 statement.setBytes(3, address.pni().map(PNI::getRawUuid).map(UuidUtil::toByteArray).orElse(null));
797 final var generatedKey = Utils.executeQueryForOptional(statement, Utils::getIdMapper);
798 if (generatedKey.isPresent()) {
799 final var recipientId = new RecipientId(generatedKey.get(), this);
800 logger.debug("Added new recipient {} with address {}", recipientId, address);
801 return recipientId;
802 } else {
803 throw new RuntimeException("Failed to add new recipient to database");
804 }
805 }
806 }
807
808 private void removeRecipientAddress(Connection connection, RecipientId recipientId) throws SQLException {
809 synchronized (recipientsLock) {
810 recipientAddressCache.entrySet()
811 .stream()
812 .filter(e -> e.getValue().id().equals(recipientId))
813 .forEach(e -> recipientAddressCache.remove(e.getKey()));
814 final var sql = (
815 """
816 UPDATE %s
817 SET number = NULL, uuid = NULL, pni = NULL
818 WHERE _id = ?
819 """
820 ).formatted(TABLE_RECIPIENT);
821 try (final var statement = connection.prepareStatement(sql)) {
822 statement.setLong(1, recipientId.id());
823 statement.executeUpdate();
824 }
825 }
826 }
827
828 private void updateRecipientAddress(
829 Connection connection, RecipientId recipientId, final RecipientAddress address
830 ) throws SQLException {
831 synchronized (recipientsLock) {
832 recipientAddressCache.entrySet()
833 .stream()
834 .filter(e -> e.getValue().id().equals(recipientId))
835 .forEach(e -> recipientAddressCache.remove(e.getKey()));
836 final var sql = (
837 """
838 UPDATE %s
839 SET number = ?, uuid = ?, pni = ?, username = ?
840 WHERE _id = ?
841 """
842 ).formatted(TABLE_RECIPIENT);
843 try (final var statement = connection.prepareStatement(sql)) {
844 statement.setString(1, address.number().orElse(null));
845 statement.setBytes(2,
846 address.serviceId().map(ServiceId::getRawUuid).map(UuidUtil::toByteArray).orElse(null));
847 statement.setBytes(3, address.pni().map(PNI::getRawUuid).map(UuidUtil::toByteArray).orElse(null));
848 statement.setString(4, address.username().orElse(null));
849 statement.setLong(5, recipientId.id());
850 statement.executeUpdate();
851 }
852 }
853 }
854
855 private void deleteRecipient(final Connection connection, final RecipientId recipientId) throws SQLException {
856 final var sql = (
857 """
858 DELETE FROM %s
859 WHERE _id = ?
860 """
861 ).formatted(TABLE_RECIPIENT);
862 try (final var statement = connection.prepareStatement(sql)) {
863 statement.setLong(1, recipientId.id());
864 statement.executeUpdate();
865 }
866 }
867
868 private void mergeRecipientsLocked(
869 Connection connection, RecipientId recipientId, RecipientId toBeMergedRecipientId
870 ) throws SQLException {
871 final var contact = getContact(connection, recipientId);
872 if (contact == null) {
873 final var toBeMergedContact = getContact(connection, toBeMergedRecipientId);
874 storeContact(connection, recipientId, toBeMergedContact);
875 }
876
877 final var profileKey = getProfileKey(connection, recipientId);
878 if (profileKey == null) {
879 final var toBeMergedProfileKey = getProfileKey(connection, toBeMergedRecipientId);
880 storeProfileKey(connection, recipientId, toBeMergedProfileKey, false);
881 }
882
883 final var profileKeyCredential = getExpiringProfileKeyCredential(connection, recipientId);
884 if (profileKeyCredential == null) {
885 final var toBeMergedProfileKeyCredential = getExpiringProfileKeyCredential(connection,
886 toBeMergedRecipientId);
887 storeExpiringProfileKeyCredential(connection, recipientId, toBeMergedProfileKeyCredential);
888 }
889
890 final var profile = getProfile(connection, recipientId);
891 if (profile == null) {
892 final var toBeMergedProfile = getProfile(connection, toBeMergedRecipientId);
893 storeProfile(connection, recipientId, toBeMergedProfile);
894 }
895
896 recipientsMerged.put(toBeMergedRecipientId.id(), recipientId.id());
897 }
898
899 private Optional<RecipientWithAddress> findByNumber(
900 final Connection connection, final String number
901 ) throws SQLException {
902 final var sql = """
903 SELECT r._id, r.number, r.uuid, r.pni, r.username
904 FROM %s r
905 WHERE r.number = ?
906 LIMIT 1
907 """.formatted(TABLE_RECIPIENT);
908 try (final var statement = connection.prepareStatement(sql)) {
909 statement.setString(1, number);
910 return Utils.executeQueryForOptional(statement, this::getRecipientWithAddressFromResultSet);
911 }
912 }
913
914 private Optional<RecipientWithAddress> findByUsername(
915 final Connection connection, final String username
916 ) throws SQLException {
917 final var sql = """
918 SELECT r._id, r.number, r.uuid, r.pni, r.username
919 FROM %s r
920 WHERE r.username = ?
921 LIMIT 1
922 """.formatted(TABLE_RECIPIENT);
923 try (final var statement = connection.prepareStatement(sql)) {
924 statement.setString(1, username);
925 return Utils.executeQueryForOptional(statement, this::getRecipientWithAddressFromResultSet);
926 }
927 }
928
929 private Optional<RecipientWithAddress> findByServiceId(
930 final Connection connection, final ServiceId serviceId
931 ) throws SQLException {
932 var recipientWithAddress = Optional.ofNullable(recipientAddressCache.get(serviceId));
933 if (recipientWithAddress.isPresent()) {
934 return recipientWithAddress;
935 }
936 final var sql = """
937 SELECT r._id, r.number, r.uuid, r.pni, r.username
938 FROM %s r
939 WHERE r.uuid = ?1 OR r.pni = ?1
940 LIMIT 1
941 """.formatted(TABLE_RECIPIENT);
942 try (final var statement = connection.prepareStatement(sql)) {
943 statement.setBytes(1, UuidUtil.toByteArray(serviceId.getRawUuid()));
944 recipientWithAddress = Utils.executeQueryForOptional(statement, this::getRecipientWithAddressFromResultSet);
945 recipientWithAddress.ifPresent(r -> recipientAddressCache.put(serviceId, r));
946 return recipientWithAddress;
947 }
948 }
949
950 private Set<RecipientWithAddress> findAllByAddress(
951 final Connection connection, final RecipientAddress address
952 ) throws SQLException {
953 final var sql = """
954 SELECT r._id, r.number, r.uuid, r.pni, r.username
955 FROM %s r
956 WHERE r.uuid = ?1 OR r.pni = ?1 OR
957 r.uuid = ?2 OR r.pni = ?2 OR
958 r.number = ?3 OR
959 r.username = ?4
960 """.formatted(TABLE_RECIPIENT);
961 try (final var statement = connection.prepareStatement(sql)) {
962 statement.setBytes(1,
963 address.serviceId().map(ServiceId::getRawUuid).map(UuidUtil::toByteArray).orElse(null));
964 statement.setBytes(2, address.pni().map(ServiceId::getRawUuid).map(UuidUtil::toByteArray).orElse(null));
965 statement.setString(3, address.number().orElse(null));
966 statement.setString(4, address.username().orElse(null));
967 return Utils.executeQueryForStream(statement, this::getRecipientWithAddressFromResultSet)
968 .collect(Collectors.toSet());
969 }
970 }
971
972 private Contact getContact(final Connection connection, final RecipientId recipientId) throws SQLException {
973 final var sql = (
974 """
975 SELECT r.given_name, r.family_name, r.expiration_time, r.profile_sharing, r.color, r.blocked, r.archived
976 FROM %s r
977 WHERE r._id = ? AND (%s)
978 """
979 ).formatted(TABLE_RECIPIENT, SQL_IS_CONTACT);
980 try (final var statement = connection.prepareStatement(sql)) {
981 statement.setLong(1, recipientId.id());
982 return Utils.executeQueryForOptional(statement, this::getContactFromResultSet).orElse(null);
983 }
984 }
985
986 private ProfileKey getProfileKey(final Connection connection, final RecipientId recipientId) throws SQLException {
987 final var sql = (
988 """
989 SELECT r.profile_key
990 FROM %s r
991 WHERE r._id = ?
992 """
993 ).formatted(TABLE_RECIPIENT);
994 try (final var statement = connection.prepareStatement(sql)) {
995 statement.setLong(1, recipientId.id());
996 return Utils.executeQueryForOptional(statement, this::getProfileKeyFromResultSet).orElse(null);
997 }
998 }
999
1000 private ExpiringProfileKeyCredential getExpiringProfileKeyCredential(
1001 final Connection connection, final RecipientId recipientId
1002 ) throws SQLException {
1003 final var sql = (
1004 """
1005 SELECT r.profile_key_credential
1006 FROM %s r
1007 WHERE r._id = ?
1008 """
1009 ).formatted(TABLE_RECIPIENT);
1010 try (final var statement = connection.prepareStatement(sql)) {
1011 statement.setLong(1, recipientId.id());
1012 return Utils.executeQueryForOptional(statement, this::getExpiringProfileKeyCredentialFromResultSet)
1013 .orElse(null);
1014 }
1015 }
1016
1017 private Profile getProfile(final Connection connection, final RecipientId recipientId) throws SQLException {
1018 final var sql = (
1019 """
1020 SELECT r.profile_last_update_timestamp, r.profile_given_name, r.profile_family_name, r.profile_about, r.profile_about_emoji, r.profile_avatar_url_path, r.profile_mobile_coin_address, r.profile_unidentified_access_mode, r.profile_capabilities
1021 FROM %s r
1022 WHERE r._id = ? AND r.profile_capabilities IS NOT NULL
1023 """
1024 ).formatted(TABLE_RECIPIENT);
1025 try (final var statement = connection.prepareStatement(sql)) {
1026 statement.setLong(1, recipientId.id());
1027 return Utils.executeQueryForOptional(statement, this::getProfileFromResultSet).orElse(null);
1028 }
1029 }
1030
1031 private RecipientAddress getRecipientAddressFromResultSet(ResultSet resultSet) throws SQLException {
1032 final var pni = Optional.ofNullable(resultSet.getBytes("pni")).map(UuidUtil::parseOrNull).map(PNI::from);
1033 final var serviceIdUuid = Optional.ofNullable(resultSet.getBytes("uuid")).map(UuidUtil::parseOrNull);
1034 final var serviceId = serviceIdUuid.isPresent() && pni.isPresent() && serviceIdUuid.get()
1035 .equals(pni.get().getRawUuid()) ? pni.<ServiceId>map(p -> p) : serviceIdUuid.<ServiceId>map(ACI::from);
1036 final var number = Optional.ofNullable(resultSet.getString("number"));
1037 final var username = Optional.ofNullable(resultSet.getString("username"));
1038 return new RecipientAddress(serviceId, pni, number, username);
1039 }
1040
1041 private RecipientId getRecipientIdFromResultSet(ResultSet resultSet) throws SQLException {
1042 return new RecipientId(resultSet.getLong("_id"), this);
1043 }
1044
1045 private RecipientWithAddress getRecipientWithAddressFromResultSet(final ResultSet resultSet) throws SQLException {
1046 return new RecipientWithAddress(getRecipientIdFromResultSet(resultSet),
1047 getRecipientAddressFromResultSet(resultSet));
1048 }
1049
1050 private Recipient getRecipientFromResultSet(final ResultSet resultSet) throws SQLException {
1051 return new Recipient(getRecipientIdFromResultSet(resultSet),
1052 getRecipientAddressFromResultSet(resultSet),
1053 getContactFromResultSet(resultSet),
1054 getProfileKeyFromResultSet(resultSet),
1055 getExpiringProfileKeyCredentialFromResultSet(resultSet),
1056 getProfileFromResultSet(resultSet));
1057 }
1058
1059 private Contact getContactFromResultSet(ResultSet resultSet) throws SQLException {
1060 return new Contact(resultSet.getString("given_name"),
1061 resultSet.getString("family_name"),
1062 resultSet.getString("color"),
1063 resultSet.getInt("expiration_time"),
1064 resultSet.getBoolean("blocked"),
1065 resultSet.getBoolean("archived"),
1066 resultSet.getBoolean("profile_sharing"));
1067 }
1068
1069 private Profile getProfileFromResultSet(ResultSet resultSet) throws SQLException {
1070 final var profileCapabilities = resultSet.getString("profile_capabilities");
1071 final var profileUnidentifiedAccessMode = resultSet.getString("profile_unidentified_access_mode");
1072 return new Profile(resultSet.getLong("profile_last_update_timestamp"),
1073 resultSet.getString("profile_given_name"),
1074 resultSet.getString("profile_family_name"),
1075 resultSet.getString("profile_about"),
1076 resultSet.getString("profile_about_emoji"),
1077 resultSet.getString("profile_avatar_url_path"),
1078 resultSet.getBytes("profile_mobile_coin_address"),
1079 profileUnidentifiedAccessMode == null
1080 ? Profile.UnidentifiedAccessMode.UNKNOWN
1081 : Profile.UnidentifiedAccessMode.valueOfOrUnknown(profileUnidentifiedAccessMode),
1082 profileCapabilities == null
1083 ? Set.of()
1084 : Arrays.stream(profileCapabilities.split(","))
1085 .map(Profile.Capability::valueOfOrNull)
1086 .filter(Objects::nonNull)
1087 .collect(Collectors.toSet()));
1088 }
1089
1090 private ProfileKey getProfileKeyFromResultSet(ResultSet resultSet) throws SQLException {
1091 final var profileKey = resultSet.getBytes("profile_key");
1092
1093 if (profileKey == null) {
1094 return null;
1095 }
1096 try {
1097 return new ProfileKey(profileKey);
1098 } catch (InvalidInputException ignored) {
1099 return null;
1100 }
1101 }
1102
1103 private ExpiringProfileKeyCredential getExpiringProfileKeyCredentialFromResultSet(ResultSet resultSet) throws SQLException {
1104 final var profileKeyCredential = resultSet.getBytes("profile_key_credential");
1105
1106 if (profileKeyCredential == null) {
1107 return null;
1108 }
1109 try {
1110 return new ExpiringProfileKeyCredential(profileKeyCredential);
1111 } catch (Throwable ignored) {
1112 return null;
1113 }
1114 }
1115
1116 public interface RecipientMergeHandler {
1117
1118 void mergeRecipients(
1119 final Connection connection, RecipientId recipientId, RecipientId toBeMergedRecipientId
1120 ) throws SQLException;
1121 }
1122
1123 private class HelperStore implements MergeRecipientHelper.Store {
1124
1125 private final Connection connection;
1126
1127 public HelperStore(final Connection connection) {
1128 this.connection = connection;
1129 }
1130
1131 @Override
1132 public Set<RecipientWithAddress> findAllByAddress(final RecipientAddress address) throws SQLException {
1133 return RecipientStore.this.findAllByAddress(connection, address);
1134 }
1135
1136 @Override
1137 public RecipientId addNewRecipient(final RecipientAddress address) throws SQLException {
1138 return RecipientStore.this.addNewRecipient(connection, address);
1139 }
1140
1141 @Override
1142 public void updateRecipientAddress(
1143 final RecipientId recipientId, final RecipientAddress address
1144 ) throws SQLException {
1145 RecipientStore.this.updateRecipientAddress(connection, recipientId, address);
1146 }
1147
1148 @Override
1149 public void removeRecipientAddress(final RecipientId recipientId) throws SQLException {
1150 RecipientStore.this.removeRecipientAddress(connection, recipientId);
1151 }
1152 }
1153 }