]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/storage/recipients/RecipientStore.java
6428d20216187cb61a60522748b9378998bd7066
[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.PhoneNumberSharingMode;
6 import org.asamk.signal.manager.api.Profile;
7 import org.asamk.signal.manager.api.UnregisteredRecipientException;
8 import org.asamk.signal.manager.storage.Database;
9 import org.asamk.signal.manager.storage.Utils;
10 import org.asamk.signal.manager.storage.contacts.ContactsStore;
11 import org.asamk.signal.manager.storage.profiles.ProfileStore;
12 import org.asamk.signal.manager.util.KeyUtils;
13 import org.signal.libsignal.zkgroup.InvalidInputException;
14 import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredential;
15 import org.signal.libsignal.zkgroup.profiles.ProfileKey;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
18 import org.whispersystems.signalservice.api.push.ServiceId;
19 import org.whispersystems.signalservice.api.push.ServiceId.ACI;
20 import org.whispersystems.signalservice.api.push.ServiceId.PNI;
21 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
22 import org.whispersystems.signalservice.api.storage.StorageId;
23
24 import java.sql.Connection;
25 import java.sql.ResultSet;
26 import java.sql.SQLException;
27 import java.sql.Types;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Collection;
31 import java.util.HashMap;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Objects;
35 import java.util.Optional;
36 import java.util.Set;
37 import java.util.function.Supplier;
38 import java.util.stream.Collectors;
39
40 public class RecipientStore implements RecipientIdCreator, RecipientResolver, RecipientTrustedResolver, ContactsStore, ProfileStore {
41
42 private static final Logger logger = LoggerFactory.getLogger(RecipientStore.class);
43 private static final String TABLE_RECIPIENT = "recipient";
44 private static final String SQL_IS_CONTACT = "r.given_name IS NOT NULL OR r.family_name IS NOT NULL OR r.nick_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";
45
46 private final RecipientMergeHandler recipientMergeHandler;
47 private final SelfAddressProvider selfAddressProvider;
48 private final SelfProfileKeyProvider selfProfileKeyProvider;
49 private final Database database;
50
51 private final Map<Long, Long> recipientsMerged = new HashMap<>();
52
53 private final Map<ServiceId, RecipientWithAddress> recipientAddressCache = new HashMap<>();
54
55 public static void createSql(Connection connection) throws SQLException {
56 // When modifying the CREATE statement here, also add a migration in AccountDatabase.java
57 try (final var statement = connection.createStatement()) {
58 statement.executeUpdate("""
59 CREATE TABLE recipient (
60 _id INTEGER PRIMARY KEY AUTOINCREMENT,
61 storage_id BLOB UNIQUE,
62 storage_record BLOB,
63 number TEXT UNIQUE,
64 username TEXT UNIQUE,
65 aci TEXT UNIQUE,
66 pni TEXT UNIQUE,
67 unregistered_timestamp INTEGER,
68 discoverable INTEGER,
69 profile_key BLOB,
70 profile_key_credential BLOB,
71 needs_pni_signature INTEGER NOT NULL DEFAULT FALSE,
72
73 given_name TEXT,
74 family_name TEXT,
75 nick_name TEXT,
76 nick_name_given_name TEXT,
77 nick_name_family_name TEXT,
78 note TEXT,
79 color TEXT,
80
81 expiration_time INTEGER NOT NULL DEFAULT 0,
82 mute_until INTEGER NOT NULL DEFAULT 0,
83 blocked INTEGER NOT NULL DEFAULT FALSE,
84 archived INTEGER NOT NULL DEFAULT FALSE,
85 profile_sharing INTEGER NOT NULL DEFAULT FALSE,
86 hide_story INTEGER NOT NULL DEFAULT FALSE,
87 hidden INTEGER NOT NULL DEFAULT FALSE,
88
89 profile_last_update_timestamp INTEGER NOT NULL DEFAULT 0,
90 profile_given_name TEXT,
91 profile_family_name TEXT,
92 profile_about TEXT,
93 profile_about_emoji TEXT,
94 profile_avatar_url_path TEXT,
95 profile_mobile_coin_address BLOB,
96 profile_unidentified_access_mode TEXT,
97 profile_capabilities TEXT,
98 profile_phone_number_sharing TEXT
99 ) STRICT;
100 """);
101 }
102 }
103
104 public RecipientStore(
105 final RecipientMergeHandler recipientMergeHandler,
106 final SelfAddressProvider selfAddressProvider,
107 final SelfProfileKeyProvider selfProfileKeyProvider,
108 final Database database
109 ) {
110 this.recipientMergeHandler = recipientMergeHandler;
111 this.selfAddressProvider = selfAddressProvider;
112 this.selfProfileKeyProvider = selfProfileKeyProvider;
113 this.database = database;
114 }
115
116 public RecipientAddress resolveRecipientAddress(RecipientId recipientId) {
117 try (final var connection = database.getConnection()) {
118 return resolveRecipientAddress(connection, recipientId);
119 } catch (SQLException e) {
120 throw new RuntimeException("Failed read from recipient store", e);
121 }
122 }
123
124 public Collection<RecipientId> getRecipientIdsWithEnabledProfileSharing() {
125 final var sql = (
126 """
127 SELECT r._id
128 FROM %s r
129 WHERE r.blocked = FALSE AND r.profile_sharing = TRUE
130 """
131 ).formatted(TABLE_RECIPIENT);
132 try (final var connection = database.getConnection()) {
133 try (final var statement = connection.prepareStatement(sql)) {
134 try (var result = Utils.executeQueryForStream(statement, this::getRecipientIdFromResultSet)) {
135 return result.toList();
136 }
137 }
138 } catch (SQLException e) {
139 throw new RuntimeException("Failed read from recipient store", e);
140 }
141 }
142
143 @Override
144 public RecipientId resolveRecipient(final long rawRecipientId) {
145 final var sql = (
146 """
147 SELECT r._id
148 FROM %s r
149 WHERE r._id = ?
150 """
151 ).formatted(TABLE_RECIPIENT);
152 try (final var connection = database.getConnection()) {
153 try (final var statement = connection.prepareStatement(sql)) {
154 statement.setLong(1, rawRecipientId);
155 return Utils.executeQueryForOptional(statement, this::getRecipientIdFromResultSet).orElse(null);
156 }
157 } catch (SQLException e) {
158 throw new RuntimeException("Failed read from recipient store", e);
159 }
160 }
161
162 @Override
163 public RecipientId resolveRecipient(final String identifier) {
164 final var serviceId = ServiceId.parseOrNull(identifier);
165 if (serviceId != null) {
166 return resolveRecipient(serviceId);
167 } else {
168 return resolveRecipientByNumber(identifier);
169 }
170 }
171
172 private RecipientId resolveRecipientByNumber(final String number) {
173 final RecipientId recipientId;
174 try (final var connection = database.getConnection()) {
175 connection.setAutoCommit(false);
176 recipientId = resolveRecipientLocked(connection, number);
177 connection.commit();
178 } catch (SQLException e) {
179 throw new RuntimeException("Failed read recipient store", e);
180 }
181 return recipientId;
182 }
183
184 @Override
185 public RecipientId resolveRecipient(final ServiceId serviceId) {
186 try (final var connection = database.getConnection()) {
187 connection.setAutoCommit(false);
188 final var recipientWithAddress = recipientAddressCache.get(serviceId);
189 if (recipientWithAddress != null) {
190 return recipientWithAddress.id();
191 }
192 final var recipientId = resolveRecipientLocked(connection, serviceId);
193 connection.commit();
194 return recipientId;
195 } catch (SQLException e) {
196 throw new RuntimeException("Failed read recipient store", e);
197 }
198 }
199
200 /**
201 * Should only be used for recipientIds from the database.
202 * Where the foreign key relations ensure a valid recipientId.
203 */
204 @Override
205 public RecipientId create(final long recipientId) {
206 return new RecipientId(recipientId, this);
207 }
208
209 public RecipientId resolveRecipientByNumber(
210 final String number, Supplier<ServiceId> serviceIdSupplier
211 ) throws UnregisteredRecipientException {
212 final Optional<RecipientWithAddress> byNumber;
213 try (final var connection = database.getConnection()) {
214 byNumber = findByNumber(connection, number);
215 } catch (SQLException e) {
216 throw new RuntimeException("Failed read from recipient store", e);
217 }
218 if (byNumber.isEmpty() || byNumber.get().address().serviceId().isEmpty()) {
219 final var serviceId = serviceIdSupplier.get();
220 if (serviceId == null) {
221 throw new UnregisteredRecipientException(new org.asamk.signal.manager.api.RecipientAddress(number));
222 }
223
224 return resolveRecipient(serviceId);
225 }
226 return byNumber.get().id();
227 }
228
229 public Optional<RecipientId> resolveRecipientByNumberOptional(final String number) {
230 final Optional<RecipientWithAddress> byNumber;
231 try (final var connection = database.getConnection()) {
232 byNumber = findByNumber(connection, number);
233 } catch (SQLException e) {
234 throw new RuntimeException("Failed read from recipient store", e);
235 }
236 return byNumber.map(RecipientWithAddress::id);
237 }
238
239 public RecipientId resolveRecipientByUsername(
240 final String username, Supplier<ACI> aciSupplier
241 ) throws UnregisteredRecipientException {
242 final Optional<RecipientWithAddress> byUsername;
243 try (final var connection = database.getConnection()) {
244 byUsername = findByUsername(connection, username);
245 } catch (SQLException e) {
246 throw new RuntimeException("Failed read from recipient store", e);
247 }
248 if (byUsername.isEmpty() || byUsername.get().address().serviceId().isEmpty()) {
249 final var aci = aciSupplier.get();
250 if (aci == null) {
251 throw new UnregisteredRecipientException(new org.asamk.signal.manager.api.RecipientAddress(null,
252 null,
253 null,
254 username));
255 }
256
257 return resolveRecipientTrusted(aci, username);
258 }
259 return byUsername.get().id();
260 }
261
262 public RecipientId resolveRecipient(RecipientAddress address) {
263 final RecipientId recipientId;
264 try (final var connection = database.getConnection()) {
265 connection.setAutoCommit(false);
266 recipientId = resolveRecipientLocked(connection, address);
267 connection.commit();
268 } catch (SQLException e) {
269 throw new RuntimeException("Failed read recipient store", e);
270 }
271 return recipientId;
272 }
273
274 public RecipientId resolveRecipient(Connection connection, RecipientAddress address) throws SQLException {
275 return resolveRecipientLocked(connection, address);
276 }
277
278 @Override
279 public RecipientId resolveSelfRecipientTrusted(RecipientAddress address) {
280 return resolveRecipientTrusted(address, true);
281 }
282
283 @Override
284 public RecipientId resolveRecipientTrusted(RecipientAddress address) {
285 return resolveRecipientTrusted(address, false);
286 }
287
288 public RecipientId resolveRecipientTrusted(Connection connection, RecipientAddress address) throws SQLException {
289 final var pair = resolveRecipientTrustedLocked(connection, address, false);
290 if (!pair.second().isEmpty()) {
291 mergeRecipients(connection, pair.first(), pair.second());
292 }
293 return pair.first();
294 }
295
296 @Override
297 public RecipientId resolveRecipientTrusted(SignalServiceAddress address) {
298 return resolveRecipientTrusted(new RecipientAddress(address));
299 }
300
301 @Override
302 public RecipientId resolveRecipientTrusted(
303 final Optional<ACI> aci, final Optional<PNI> pni, final Optional<String> number
304 ) {
305 return resolveRecipientTrusted(new RecipientAddress(aci, pni, number, Optional.empty()));
306 }
307
308 @Override
309 public RecipientId resolveRecipientTrusted(final ACI aci, final String username) {
310 return resolveRecipientTrusted(new RecipientAddress(aci, null, null, username));
311 }
312
313 @Override
314 public void storeContact(RecipientId recipientId, final Contact contact) {
315 try (final var connection = database.getConnection()) {
316 storeContact(connection, recipientId, contact);
317 } catch (SQLException e) {
318 throw new RuntimeException("Failed update recipient store", e);
319 }
320 }
321
322 @Override
323 public Contact getContact(RecipientId recipientId) {
324 try (final var connection = database.getConnection()) {
325 return getContact(connection, recipientId);
326 } catch (SQLException e) {
327 throw new RuntimeException("Failed read from recipient store", e);
328 }
329 }
330
331 @Override
332 public List<Pair<RecipientId, Contact>> getContacts() {
333 final var sql = (
334 """
335 SELECT r._id, r.given_name, r.family_name, r.nick_name, r.expiration_time, r.mute_until, r.hide_story, r.profile_sharing, r.color, r.blocked, r.archived, r.hidden, r.unregistered_timestamp
336 FROM %s r
337 WHERE (r.number IS NOT NULL OR r.aci IS NOT NULL) AND %s AND r.hidden = FALSE
338 """
339 ).formatted(TABLE_RECIPIENT, SQL_IS_CONTACT);
340 try (final var connection = database.getConnection()) {
341 try (final var statement = connection.prepareStatement(sql)) {
342 try (var result = Utils.executeQueryForStream(statement,
343 resultSet -> new Pair<>(getRecipientIdFromResultSet(resultSet),
344 getContactFromResultSet(resultSet)))) {
345 return result.toList();
346 }
347 }
348 } catch (SQLException e) {
349 throw new RuntimeException("Failed read from recipient store", e);
350 }
351 }
352
353 public Recipient getRecipient(Connection connection, RecipientId recipientId) throws SQLException {
354 final var sql = (
355 """
356 SELECT r._id,
357 r.number, r.aci, r.pni, r.username,
358 r.profile_key, r.profile_key_credential,
359 r.given_name, r.family_name, r.nick_name, r.expiration_time, r.mute_until, r.hide_story, r.profile_sharing, r.color, r.blocked, r.archived, r.hidden, r.unregistered_timestamp,
360 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, r.profile_phone_number_sharing,
361 r.discoverable,
362 r.storage_record
363 FROM %s r
364 WHERE r._id = ?
365 """
366 ).formatted(TABLE_RECIPIENT);
367 try (final var statement = connection.prepareStatement(sql)) {
368 statement.setLong(1, recipientId.id());
369 return Utils.executeQuerySingleRow(statement, this::getRecipientFromResultSet);
370 }
371 }
372
373 public Recipient getRecipient(Connection connection, StorageId storageId) throws SQLException {
374 final var sql = (
375 """
376 SELECT r._id,
377 r.number, r.aci, r.pni, r.username,
378 r.profile_key, r.profile_key_credential,
379 r.given_name, r.family_name, r.nick_name, r.expiration_time, r.mute_until, r.hide_story, r.profile_sharing, r.color, r.blocked, r.archived, r.hidden, r.unregistered_timestamp,
380 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, r.profile_phone_number_sharing,
381 r.discoverable,
382 r.storage_record
383 FROM %s r
384 WHERE r.storage_id = ?
385 """
386 ).formatted(TABLE_RECIPIENT);
387 try (final var statement = connection.prepareStatement(sql)) {
388 statement.setBytes(1, storageId.getRaw());
389 return Utils.executeQuerySingleRow(statement, this::getRecipientFromResultSet);
390 }
391 }
392
393 public List<Recipient> getRecipients(
394 boolean onlyContacts, Optional<Boolean> blocked, Set<RecipientId> recipientIds, Optional<String> name
395 ) {
396 final var sqlWhere = new ArrayList<String>();
397 if (onlyContacts) {
398 sqlWhere.add("r.unregistered_timestamp IS NULL");
399 sqlWhere.add("(" + SQL_IS_CONTACT + ")");
400 sqlWhere.add("r.hidden = FALSE");
401 }
402 if (blocked.isPresent()) {
403 sqlWhere.add("r.blocked = ?");
404 }
405 if (!recipientIds.isEmpty()) {
406 final var recipientIdsCommaSeparated = recipientIds.stream()
407 .map(recipientId -> String.valueOf(recipientId.id()))
408 .collect(Collectors.joining(","));
409 sqlWhere.add("r._id IN (" + recipientIdsCommaSeparated + ")");
410 }
411 final var sql = (
412 """
413 SELECT r._id,
414 r.number, r.aci, r.pni, r.username,
415 r.profile_key, r.profile_key_credential,
416 r.given_name, r.family_name, r.nick_name, r.expiration_time, r.mute_until, r.hide_story, r.profile_sharing, r.color, r.blocked, r.archived, r.hidden, r.unregistered_timestamp,
417 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, r.profile_phone_number_sharing,
418 r.discoverable,
419 r.storage_record
420 FROM %s r
421 WHERE (r.number IS NOT NULL OR r.aci IS NOT NULL) AND %s
422 """
423 ).formatted(TABLE_RECIPIENT, sqlWhere.isEmpty() ? "TRUE" : String.join(" AND ", sqlWhere));
424 final var selfAddress = selfAddressProvider.getSelfAddress();
425 try (final var connection = database.getConnection()) {
426 try (final var statement = connection.prepareStatement(sql)) {
427 if (blocked.isPresent()) {
428 statement.setBoolean(1, blocked.get());
429 }
430 try (var result = Utils.executeQueryForStream(statement, this::getRecipientFromResultSet)) {
431 return result.filter(r -> name.isEmpty() || (
432 r.getContact() != null && name.get().equals(r.getContact().getName())
433 ) || (r.getProfile() != null && name.get().equals(r.getProfile().getDisplayName()))).map(r -> {
434 if (r.getAddress().matches(selfAddress)) {
435 return Recipient.newBuilder(r)
436 .withProfileKey(selfProfileKeyProvider.getSelfProfileKey())
437 .build();
438 }
439 return r;
440 }).toList();
441 }
442 }
443 } catch (SQLException e) {
444 throw new RuntimeException("Failed read from recipient store", e);
445 }
446 }
447
448 public Set<String> getAllNumbers() {
449 final var sql = (
450 """
451 SELECT r.number
452 FROM %s r
453 WHERE r.number IS NOT NULL
454 """
455 ).formatted(TABLE_RECIPIENT);
456 final var selfNumber = selfAddressProvider.getSelfAddress().number().orElse(null);
457 try (final var connection = database.getConnection()) {
458 try (final var statement = connection.prepareStatement(sql)) {
459 return Utils.executeQueryForStream(statement, resultSet -> resultSet.getString("number"))
460 .filter(Objects::nonNull)
461 .filter(n -> !n.equals(selfNumber))
462 .filter(n -> {
463 try {
464 Long.parseLong(n);
465 return true;
466 } catch (NumberFormatException e) {
467 return false;
468 }
469 })
470 .collect(Collectors.toSet());
471 }
472 } catch (SQLException e) {
473 throw new RuntimeException("Failed read from recipient store", e);
474 }
475 }
476
477 public Map<ServiceId, ProfileKey> getServiceIdToProfileKeyMap() {
478 final var sql = (
479 """
480 SELECT r.aci, r.profile_key
481 FROM %s r
482 WHERE r.aci IS NOT NULL AND r.profile_key IS NOT NULL
483 """
484 ).formatted(TABLE_RECIPIENT);
485 final var selfAci = selfAddressProvider.getSelfAddress().aci().orElse(null);
486 try (final var connection = database.getConnection()) {
487 try (final var statement = connection.prepareStatement(sql)) {
488 return Utils.executeQueryForStream(statement, resultSet -> {
489 final var aci = ACI.parseOrThrow(resultSet.getString("aci"));
490 if (aci.equals(selfAci)) {
491 return new Pair<>(aci, selfProfileKeyProvider.getSelfProfileKey());
492 }
493 final var profileKey = getProfileKeyFromResultSet(resultSet);
494 return new Pair<>(aci, profileKey);
495 }).filter(Objects::nonNull).collect(Collectors.toMap(Pair::first, Pair::second));
496 }
497 } catch (SQLException e) {
498 throw new RuntimeException("Failed read from recipient store", e);
499 }
500 }
501
502 public List<RecipientId> getRecipientIds(Connection connection) throws SQLException {
503 final var sql = (
504 """
505 SELECT r._id
506 FROM %s r
507 WHERE (r.number IS NOT NULL OR r.aci IS NOT NULL)
508 """
509 ).formatted(TABLE_RECIPIENT);
510 try (final var statement = connection.prepareStatement(sql)) {
511 return Utils.executeQueryForStream(statement, this::getRecipientIdFromResultSet).toList();
512 }
513 }
514
515 public void setMissingStorageIds() {
516 final var selectSql = (
517 """
518 SELECT r._id
519 FROM %s r
520 WHERE r.storage_id IS NULL AND r.unregistered_timestamp IS NULL
521 """
522 ).formatted(TABLE_RECIPIENT);
523 final var updateSql = (
524 """
525 UPDATE %s
526 SET storage_id = ?
527 WHERE _id = ?
528 """
529 ).formatted(TABLE_RECIPIENT);
530 try (final var connection = database.getConnection()) {
531 connection.setAutoCommit(false);
532 try (final var selectStmt = connection.prepareStatement(selectSql)) {
533 final var recipientIds = Utils.executeQueryForStream(selectStmt, this::getRecipientIdFromResultSet)
534 .toList();
535 try (final var updateStmt = connection.prepareStatement(updateSql)) {
536 for (final var recipientId : recipientIds) {
537 updateStmt.setBytes(1, KeyUtils.createRawStorageId());
538 updateStmt.setLong(2, recipientId.id());
539 updateStmt.executeUpdate();
540 }
541 }
542 }
543 connection.commit();
544 } catch (SQLException e) {
545 throw new RuntimeException("Failed update recipient store", e);
546 }
547 }
548
549 @Override
550 public void deleteContact(RecipientId recipientId) {
551 storeContact(recipientId, null);
552 }
553
554 public void deleteRecipientData(RecipientId recipientId) {
555 logger.debug("Deleting recipient data for {}", recipientId);
556 try (final var connection = database.getConnection()) {
557 connection.setAutoCommit(false);
558 recipientAddressCache.entrySet().removeIf(e -> e.getValue().id().equals(recipientId));
559 storeContact(connection, recipientId, null);
560 storeProfile(connection, recipientId, null);
561 storeProfileKey(connection, recipientId, null, false);
562 storeExpiringProfileKeyCredential(connection, recipientId, null);
563 deleteRecipient(connection, recipientId);
564 connection.commit();
565 } catch (SQLException e) {
566 throw new RuntimeException("Failed update recipient store", e);
567 }
568 }
569
570 @Override
571 public Profile getProfile(final RecipientId recipientId) {
572 try (final var connection = database.getConnection()) {
573 return getProfile(connection, recipientId);
574 } catch (SQLException e) {
575 throw new RuntimeException("Failed read from recipient store", e);
576 }
577 }
578
579 @Override
580 public ProfileKey getProfileKey(final RecipientId recipientId) {
581 try (final var connection = database.getConnection()) {
582 return getProfileKey(connection, recipientId);
583 } catch (SQLException e) {
584 throw new RuntimeException("Failed read from recipient store", e);
585 }
586 }
587
588 @Override
589 public ExpiringProfileKeyCredential getExpiringProfileKeyCredential(final RecipientId recipientId) {
590 try (final var connection = database.getConnection()) {
591 return getExpiringProfileKeyCredential(connection, recipientId);
592 } catch (SQLException e) {
593 throw new RuntimeException("Failed read from recipient store", e);
594 }
595 }
596
597 @Override
598 public void storeProfile(RecipientId recipientId, final Profile profile) {
599 try (final var connection = database.getConnection()) {
600 storeProfile(connection, recipientId, profile);
601 } catch (SQLException e) {
602 throw new RuntimeException("Failed update recipient store", e);
603 }
604 }
605
606 @Override
607 public void storeProfileKey(RecipientId recipientId, final ProfileKey profileKey) {
608 try (final var connection = database.getConnection()) {
609 storeProfileKey(connection, recipientId, profileKey);
610 } catch (SQLException e) {
611 throw new RuntimeException("Failed update recipient store", e);
612 }
613 }
614
615 public void storeProfileKey(
616 Connection connection, RecipientId recipientId, final ProfileKey profileKey
617 ) throws SQLException {
618 storeProfileKey(connection, recipientId, profileKey, true);
619 }
620
621 @Override
622 public void storeExpiringProfileKeyCredential(
623 RecipientId recipientId, final ExpiringProfileKeyCredential profileKeyCredential
624 ) {
625 try (final var connection = database.getConnection()) {
626 storeExpiringProfileKeyCredential(connection, recipientId, profileKeyCredential);
627 } catch (SQLException e) {
628 throw new RuntimeException("Failed update recipient store", e);
629 }
630 }
631
632 public void rotateSelfStorageId() {
633 try (final var connection = database.getConnection()) {
634 rotateSelfStorageId(connection);
635 } catch (SQLException e) {
636 throw new RuntimeException("Failed update recipient store", e);
637 }
638 }
639
640 public void rotateSelfStorageId(final Connection connection) throws SQLException {
641 final var selfRecipientId = resolveRecipient(connection, selfAddressProvider.getSelfAddress());
642 rotateStorageId(connection, selfRecipientId);
643 }
644
645 public StorageId rotateStorageId(final Connection connection, final ServiceId serviceId) throws SQLException {
646 final var selfRecipientId = resolveRecipient(connection, new RecipientAddress(serviceId));
647 return rotateStorageId(connection, selfRecipientId);
648 }
649
650 public List<StorageId> getStorageIds(Connection connection) throws SQLException {
651 final var sql = """
652 SELECT r.storage_id
653 FROM %s r WHERE r.storage_id IS NOT NULL AND r._id != ? AND (r.aci IS NOT NULL OR r.pni IS NOT NULL)
654 """.formatted(TABLE_RECIPIENT);
655 final var selfRecipientId = resolveRecipient(connection, selfAddressProvider.getSelfAddress());
656 try (final var statement = connection.prepareStatement(sql)) {
657 statement.setLong(1, selfRecipientId.id());
658 return Utils.executeQueryForStream(statement, this::getContactStorageIdFromResultSet).toList();
659 }
660 }
661
662 public void updateStorageId(
663 Connection connection, RecipientId recipientId, StorageId storageId
664 ) throws SQLException {
665 final var sql = (
666 """
667 UPDATE %s
668 SET storage_id = ?
669 WHERE _id = ?
670 """
671 ).formatted(TABLE_RECIPIENT);
672 try (final var statement = connection.prepareStatement(sql)) {
673 statement.setBytes(1, storageId.getRaw());
674 statement.setLong(2, recipientId.id());
675 statement.executeUpdate();
676 }
677 }
678
679 public void updateStorageIds(Connection connection, Map<RecipientId, StorageId> storageIdMap) throws SQLException {
680 final var sql = (
681 """
682 UPDATE %s
683 SET storage_id = ?
684 WHERE _id = ?
685 """
686 ).formatted(TABLE_RECIPIENT);
687 try (final var statement = connection.prepareStatement(sql)) {
688 for (final var entry : storageIdMap.entrySet()) {
689 statement.setBytes(1, entry.getValue().getRaw());
690 statement.setLong(2, entry.getKey().id());
691 statement.executeUpdate();
692 }
693 }
694 }
695
696 public StorageId getSelfStorageId(final Connection connection) throws SQLException {
697 final var selfRecipientId = resolveRecipient(connection, selfAddressProvider.getSelfAddress());
698 return StorageId.forAccount(getStorageId(connection, selfRecipientId).getRaw());
699 }
700
701 public StorageId getStorageId(final Connection connection, final RecipientId recipientId) throws SQLException {
702 final var sql = """
703 SELECT r.storage_id
704 FROM %s r WHERE r._id = ? AND r.storage_id IS NOT NULL
705 """.formatted(TABLE_RECIPIENT);
706 try (final var statement = connection.prepareStatement(sql)) {
707 statement.setLong(1, recipientId.id());
708 final var storageId = Utils.executeQueryForOptional(statement, this::getContactStorageIdFromResultSet);
709 if (storageId.isPresent()) {
710 return storageId.get();
711 }
712 }
713 return rotateStorageId(connection, recipientId);
714 }
715
716 private StorageId rotateStorageId(final Connection connection, final RecipientId recipientId) throws SQLException {
717 final var newStorageId = StorageId.forAccount(KeyUtils.createRawStorageId());
718 updateStorageId(connection, recipientId, newStorageId);
719 return newStorageId;
720 }
721
722 public void storeStorageRecord(
723 final Connection connection,
724 final RecipientId recipientId,
725 final StorageId storageId,
726 final byte[] storageRecord
727 ) throws SQLException {
728 final var deleteSql = (
729 """
730 UPDATE %s
731 SET storage_id = NULL
732 WHERE storage_id = ?
733 """
734 ).formatted(TABLE_RECIPIENT);
735 try (final var statement = connection.prepareStatement(deleteSql)) {
736 statement.setBytes(1, storageId.getRaw());
737 statement.executeUpdate();
738 }
739 final var insertSql = (
740 """
741 UPDATE %s
742 SET storage_id = ?, storage_record = ?
743 WHERE _id = ?
744 """
745 ).formatted(TABLE_RECIPIENT);
746 try (final var statement = connection.prepareStatement(insertSql)) {
747 statement.setBytes(1, storageId.getRaw());
748 if (storageRecord == null) {
749 statement.setNull(2, Types.BLOB);
750 } else {
751 statement.setBytes(2, storageRecord);
752 }
753 statement.setLong(3, recipientId.id());
754 statement.executeUpdate();
755 }
756 }
757
758 void addLegacyRecipients(final Map<RecipientId, Recipient> recipients) {
759 logger.debug("Migrating legacy recipients to database");
760 long start = System.nanoTime();
761 final var sql = (
762 """
763 INSERT INTO %s (_id, number, aci)
764 VALUES (?, ?, ?)
765 """
766 ).formatted(TABLE_RECIPIENT);
767 try (final var connection = database.getConnection()) {
768 connection.setAutoCommit(false);
769 try (final var statement = connection.prepareStatement("DELETE FROM %s".formatted(TABLE_RECIPIENT))) {
770 statement.executeUpdate();
771 }
772 try (final var statement = connection.prepareStatement(sql)) {
773 for (final var recipient : recipients.values()) {
774 statement.setLong(1, recipient.getRecipientId().id());
775 statement.setString(2, recipient.getAddress().number().orElse(null));
776 statement.setString(3, recipient.getAddress().aci().map(ACI::toString).orElse(null));
777 statement.executeUpdate();
778 }
779 }
780 logger.debug("Initial inserts took {}ms", (System.nanoTime() - start) / 1000000);
781
782 for (final var recipient : recipients.values()) {
783 if (recipient.getContact() != null) {
784 storeContact(connection, recipient.getRecipientId(), recipient.getContact());
785 }
786 if (recipient.getProfile() != null) {
787 storeProfile(connection, recipient.getRecipientId(), recipient.getProfile());
788 }
789 if (recipient.getProfileKey() != null) {
790 storeProfileKey(connection, recipient.getRecipientId(), recipient.getProfileKey(), false);
791 }
792 if (recipient.getExpiringProfileKeyCredential() != null) {
793 storeExpiringProfileKeyCredential(connection,
794 recipient.getRecipientId(),
795 recipient.getExpiringProfileKeyCredential());
796 }
797 }
798 connection.commit();
799 } catch (SQLException e) {
800 throw new RuntimeException("Failed update recipient store", e);
801 }
802 logger.debug("Complete recipients migration took {}ms", (System.nanoTime() - start) / 1000000);
803 }
804
805 long getActualRecipientId(long recipientId) {
806 while (recipientsMerged.containsKey(recipientId)) {
807 final var newRecipientId = recipientsMerged.get(recipientId);
808 logger.debug("Using {} instead of {}, because recipients have been merged", newRecipientId, recipientId);
809 recipientId = newRecipientId;
810 }
811 return recipientId;
812 }
813
814 public void storeContact(
815 final Connection connection, final RecipientId recipientId, final Contact contact
816 ) throws SQLException {
817 final var sql = (
818 """
819 UPDATE %s
820 SET given_name = ?, family_name = ?, nick_name = ?, expiration_time = ?, mute_until = ?, hide_story = ?, profile_sharing = ?, color = ?, blocked = ?, archived = ?, unregistered_timestamp = ?
821 WHERE _id = ?
822 """
823 ).formatted(TABLE_RECIPIENT);
824 try (final var statement = connection.prepareStatement(sql)) {
825 statement.setString(1, contact == null ? null : contact.givenName());
826 statement.setString(2, contact == null ? null : contact.familyName());
827 statement.setString(3, contact == null ? null : contact.nickName());
828 statement.setInt(4, contact == null ? 0 : contact.messageExpirationTime());
829 statement.setLong(5, contact == null ? 0 : contact.muteUntil());
830 statement.setBoolean(6, contact != null && contact.hideStory());
831 statement.setBoolean(7, contact != null && contact.isProfileSharingEnabled());
832 statement.setString(8, contact == null ? null : contact.color());
833 statement.setBoolean(9, contact != null && contact.isBlocked());
834 statement.setBoolean(10, contact != null && contact.isArchived());
835 if (contact == null || contact.unregisteredTimestamp() == null) {
836 statement.setNull(11, Types.INTEGER);
837 } else {
838 statement.setLong(11, contact.unregisteredTimestamp());
839 }
840 statement.setLong(12, recipientId.id());
841 statement.executeUpdate();
842 }
843 if (contact != null && contact.unregisteredTimestamp() != null) {
844 markUnregisteredAndSplitIfNecessary(connection, recipientId);
845 }
846 rotateStorageId(connection, recipientId);
847 }
848
849 public int removeStorageIdsFromLocalOnlyUnregisteredRecipients(
850 final Connection connection, final List<StorageId> storageIds
851 ) throws SQLException {
852 final var sql = (
853 """
854 UPDATE %s
855 SET storage_id = NULL
856 WHERE storage_id = ? AND unregistered_timestamp IS NOT NULL
857 """
858 ).formatted(TABLE_RECIPIENT);
859 var count = 0;
860 try (final var statement = connection.prepareStatement(sql)) {
861 for (final var storageId : storageIds) {
862 statement.setBytes(1, storageId.getRaw());
863 count += statement.executeUpdate();
864 }
865 }
866 return count;
867 }
868
869 public void markNeedsPniSignature(final RecipientId recipientId, final boolean value) {
870 logger.debug("Marking {} numbers as need pni signature = {}", recipientId, value);
871 try (final var connection = database.getConnection()) {
872 final var sql = (
873 """
874 UPDATE %s
875 SET needs_pni_signature = ?
876 WHERE _id = ?
877 """
878 ).formatted(TABLE_RECIPIENT);
879 try (final var statement = connection.prepareStatement(sql)) {
880 statement.setBoolean(1, value);
881 statement.setLong(2, recipientId.id());
882 statement.executeUpdate();
883 }
884 } catch (SQLException e) {
885 throw new RuntimeException("Failed update recipient store", e);
886 }
887 }
888
889 public boolean needsPniSignature(final RecipientId recipientId) {
890 try (final var connection = database.getConnection()) {
891 final var sql = (
892 """
893 SELECT needs_pni_signature
894 FROM %s
895 WHERE _id = ?
896 """
897 ).formatted(TABLE_RECIPIENT);
898 try (final var statement = connection.prepareStatement(sql)) {
899 statement.setLong(1, recipientId.id());
900 return Utils.executeQuerySingleRow(statement, resultSet -> resultSet.getBoolean("needs_pni_signature"));
901 }
902 } catch (SQLException e) {
903 throw new RuntimeException("Failed read recipient store", e);
904 }
905 }
906
907 public void markUndiscoverablePossiblyUnregistered(final Set<String> numbers) {
908 logger.debug("Marking {} numbers as unregistered", numbers.size());
909 try (final var connection = database.getConnection()) {
910 connection.setAutoCommit(false);
911 for (final var number : numbers) {
912 final var recipientAddress = findByNumber(connection, number);
913 if (recipientAddress.isPresent()) {
914 final var recipientId = recipientAddress.get().id();
915 markDiscoverable(connection, recipientId, false);
916 final var contact = getContact(connection, recipientId);
917 if (recipientAddress.get().address().aci().isEmpty() || contact.unregisteredTimestamp() != null) {
918 markUnregisteredAndSplitIfNecessary(connection, recipientId);
919 }
920 }
921 }
922 connection.commit();
923 } catch (SQLException e) {
924 throw new RuntimeException("Failed update recipient store", e);
925 }
926 }
927
928 public void markDiscoverable(final Set<String> numbers) {
929 logger.debug("Marking {} numbers as discoverable", numbers.size());
930 try (final var connection = database.getConnection()) {
931 connection.setAutoCommit(false);
932 for (final var number : numbers) {
933 final var recipientAddress = findByNumber(connection, number);
934 if (recipientAddress.isPresent()) {
935 final var recipientId = recipientAddress.get().id();
936 markDiscoverable(connection, recipientId, true);
937 }
938 }
939 connection.commit();
940 } catch (SQLException e) {
941 throw new RuntimeException("Failed update recipient store", e);
942 }
943 }
944
945 public void markRegistered(final RecipientId recipientId, final boolean registered) {
946 logger.debug("Marking {} as registered={}", recipientId, registered);
947 try (final var connection = database.getConnection()) {
948 connection.setAutoCommit(false);
949 if (registered) {
950 markRegistered(connection, recipientId);
951 } else {
952 markUnregistered(connection, recipientId);
953 }
954 connection.commit();
955 } catch (SQLException e) {
956 throw new RuntimeException("Failed update recipient store", e);
957 }
958 }
959
960 private void markUnregisteredAndSplitIfNecessary(
961 final Connection connection, final RecipientId recipientId
962 ) throws SQLException {
963 markUnregistered(connection, recipientId);
964 final var address = resolveRecipientAddress(connection, recipientId);
965 if (address.aci().isPresent() && address.pni().isPresent()) {
966 final var numberAddress = new RecipientAddress(address.pni().get(), address.number().orElse(null));
967 updateRecipientAddress(connection, recipientId, address.removeIdentifiersFrom(numberAddress));
968 addNewRecipient(connection, numberAddress);
969 }
970 }
971
972 private void markDiscoverable(
973 final Connection connection, final RecipientId recipientId, final boolean discoverable
974 ) throws SQLException {
975 final var sql = (
976 """
977 UPDATE %s
978 SET discoverable = ?
979 WHERE _id = ?
980 """
981 ).formatted(TABLE_RECIPIENT);
982 try (final var statement = connection.prepareStatement(sql)) {
983 statement.setBoolean(1, discoverable);
984 statement.setLong(2, recipientId.id());
985 statement.executeUpdate();
986 }
987 }
988
989 private void markRegistered(
990 final Connection connection, final RecipientId recipientId
991 ) throws SQLException {
992 final var sql = (
993 """
994 UPDATE %s
995 SET unregistered_timestamp = NULL
996 WHERE _id = ?
997 """
998 ).formatted(TABLE_RECIPIENT);
999 try (final var statement = connection.prepareStatement(sql)) {
1000 statement.setLong(1, recipientId.id());
1001 statement.executeUpdate();
1002 }
1003 }
1004
1005 private void markUnregistered(
1006 final Connection connection, final RecipientId recipientId
1007 ) throws SQLException {
1008 final var sql = (
1009 """
1010 UPDATE %s
1011 SET unregistered_timestamp = ?, discoverable = FALSE
1012 WHERE _id = ?
1013 """
1014 ).formatted(TABLE_RECIPIENT);
1015 try (final var statement = connection.prepareStatement(sql)) {
1016 statement.setLong(1, System.currentTimeMillis());
1017 statement.setLong(2, recipientId.id());
1018 statement.executeUpdate();
1019 }
1020 }
1021
1022 private void storeExpiringProfileKeyCredential(
1023 final Connection connection,
1024 final RecipientId recipientId,
1025 final ExpiringProfileKeyCredential profileKeyCredential
1026 ) throws SQLException {
1027 final var sql = (
1028 """
1029 UPDATE %s
1030 SET profile_key_credential = ?
1031 WHERE _id = ?
1032 """
1033 ).formatted(TABLE_RECIPIENT);
1034 try (final var statement = connection.prepareStatement(sql)) {
1035 statement.setBytes(1, profileKeyCredential == null ? null : profileKeyCredential.serialize());
1036 statement.setLong(2, recipientId.id());
1037 statement.executeUpdate();
1038 }
1039 }
1040
1041 public void storeProfile(
1042 final Connection connection, final RecipientId recipientId, final Profile profile
1043 ) throws SQLException {
1044 final var sql = (
1045 """
1046 UPDATE %s
1047 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 = ?, profile_phone_number_sharing = ?
1048 WHERE _id = ?
1049 """
1050 ).formatted(TABLE_RECIPIENT);
1051 try (final var statement = connection.prepareStatement(sql)) {
1052 statement.setLong(1, profile == null ? 0 : profile.getLastUpdateTimestamp());
1053 statement.setString(2, profile == null ? null : profile.getGivenName());
1054 statement.setString(3, profile == null ? null : profile.getFamilyName());
1055 statement.setString(4, profile == null ? null : profile.getAbout());
1056 statement.setString(5, profile == null ? null : profile.getAboutEmoji());
1057 statement.setString(6, profile == null ? null : profile.getAvatarUrlPath());
1058 statement.setBytes(7, profile == null ? null : profile.getMobileCoinAddress());
1059 statement.setString(8, profile == null ? null : profile.getUnidentifiedAccessMode().name());
1060 statement.setString(9,
1061 profile == null
1062 ? null
1063 : profile.getCapabilities().stream().map(Enum::name).collect(Collectors.joining(",")));
1064 statement.setString(10,
1065 profile == null || profile.getPhoneNumberSharingMode() == null
1066 ? null
1067 : profile.getPhoneNumberSharingMode().name());
1068 statement.setLong(11, recipientId.id());
1069 statement.executeUpdate();
1070 }
1071 rotateStorageId(connection, recipientId);
1072 }
1073
1074 private void storeProfileKey(
1075 Connection connection, RecipientId recipientId, final ProfileKey profileKey, boolean resetProfile
1076 ) throws SQLException {
1077 if (profileKey != null) {
1078 final var recipientProfileKey = getProfileKey(connection, recipientId);
1079 if (profileKey.equals(recipientProfileKey)) {
1080 final var recipientProfile = getProfile(connection, recipientId);
1081 if (recipientProfile == null || (
1082 recipientProfile.getUnidentifiedAccessMode() != Profile.UnidentifiedAccessMode.UNKNOWN
1083 && recipientProfile.getUnidentifiedAccessMode()
1084 != Profile.UnidentifiedAccessMode.DISABLED
1085 )) {
1086 return;
1087 }
1088 }
1089 }
1090
1091 final var sql = (
1092 """
1093 UPDATE %s
1094 SET profile_key = ?, profile_key_credential = NULL%s
1095 WHERE _id = ?
1096 """
1097 ).formatted(TABLE_RECIPIENT, resetProfile ? ", profile_last_update_timestamp = 0" : "");
1098 try (final var statement = connection.prepareStatement(sql)) {
1099 statement.setBytes(1, profileKey == null ? null : profileKey.serialize());
1100 statement.setLong(2, recipientId.id());
1101 statement.executeUpdate();
1102 }
1103 rotateStorageId(connection, recipientId);
1104 }
1105
1106 private RecipientAddress resolveRecipientAddress(
1107 final Connection connection, final RecipientId recipientId
1108 ) throws SQLException {
1109 final var sql = (
1110 """
1111 SELECT r.number, r.aci, r.pni, r.username
1112 FROM %s r
1113 WHERE r._id = ?
1114 """
1115 ).formatted(TABLE_RECIPIENT);
1116 try (final var statement = connection.prepareStatement(sql)) {
1117 statement.setLong(1, recipientId.id());
1118 return Utils.executeQuerySingleRow(statement, this::getRecipientAddressFromResultSet);
1119 }
1120 }
1121
1122 private RecipientId resolveRecipientTrusted(RecipientAddress address, boolean isSelf) {
1123 final Pair<RecipientId, List<RecipientId>> pair;
1124 try (final var connection = database.getConnection()) {
1125 connection.setAutoCommit(false);
1126 pair = resolveRecipientTrustedLocked(connection, address, isSelf);
1127 connection.commit();
1128 } catch (SQLException e) {
1129 throw new RuntimeException("Failed update recipient store", e);
1130 }
1131
1132 if (!pair.second().isEmpty()) {
1133 logger.debug("Resolved address {}, merging {} other recipients", address, pair.second().size());
1134 try (final var connection = database.getConnection()) {
1135 connection.setAutoCommit(false);
1136 mergeRecipients(connection, pair.first(), pair.second());
1137 connection.commit();
1138 } catch (SQLException e) {
1139 throw new RuntimeException("Failed update recipient store", e);
1140 }
1141 }
1142 return pair.first();
1143 }
1144
1145 private Pair<RecipientId, List<RecipientId>> resolveRecipientTrustedLocked(
1146 final Connection connection, final RecipientAddress address, final boolean isSelf
1147 ) throws SQLException {
1148 if (address.hasSingleIdentifier() || (
1149 !isSelf && selfAddressProvider.getSelfAddress().matches(address)
1150 )) {
1151 return new Pair<>(resolveRecipientLocked(connection, address), List.of());
1152 } else {
1153 final var pair = MergeRecipientHelper.resolveRecipientTrustedLocked(new HelperStore(connection), address);
1154 markRegistered(connection, pair.first());
1155
1156 for (final var toBeMergedRecipientId : pair.second()) {
1157 mergeRecipientsLocked(connection, pair.first(), toBeMergedRecipientId);
1158 }
1159 return pair;
1160 }
1161 }
1162
1163 private void mergeRecipients(
1164 final Connection connection, final RecipientId recipientId, final List<RecipientId> toBeMergedRecipientIds
1165 ) throws SQLException {
1166 for (final var toBeMergedRecipientId : toBeMergedRecipientIds) {
1167 recipientMergeHandler.mergeRecipients(connection, recipientId, toBeMergedRecipientId);
1168 deleteRecipient(connection, toBeMergedRecipientId);
1169 recipientAddressCache.entrySet().removeIf(e -> e.getValue().id().equals(toBeMergedRecipientId));
1170 }
1171 }
1172
1173 private RecipientId resolveRecipientLocked(
1174 Connection connection, RecipientAddress address
1175 ) throws SQLException {
1176 final var byAci = address.aci().isEmpty()
1177 ? Optional.<RecipientWithAddress>empty()
1178 : findByServiceId(connection, address.aci().get());
1179
1180 if (byAci.isPresent()) {
1181 return byAci.get().id();
1182 }
1183
1184 final var byPni = address.pni().isEmpty()
1185 ? Optional.<RecipientWithAddress>empty()
1186 : findByServiceId(connection, address.pni().get());
1187
1188 if (byPni.isPresent()) {
1189 return byPni.get().id();
1190 }
1191
1192 final var byNumber = address.number().isEmpty()
1193 ? Optional.<RecipientWithAddress>empty()
1194 : findByNumber(connection, address.number().get());
1195
1196 if (byNumber.isPresent()) {
1197 return byNumber.get().id();
1198 }
1199
1200 logger.debug("Got new recipient, both serviceId and number are unknown");
1201
1202 if (address.serviceId().isEmpty()) {
1203 return addNewRecipient(connection, address);
1204 }
1205
1206 return addNewRecipient(connection, new RecipientAddress(address.serviceId().get()));
1207 }
1208
1209 private RecipientId resolveRecipientLocked(Connection connection, ServiceId serviceId) throws SQLException {
1210 final var recipient = findByServiceId(connection, serviceId);
1211
1212 if (recipient.isEmpty()) {
1213 logger.debug("Got new recipient, serviceId is unknown");
1214 return addNewRecipient(connection, new RecipientAddress(serviceId));
1215 }
1216
1217 return recipient.get().id();
1218 }
1219
1220 private RecipientId resolveRecipientLocked(Connection connection, String number) throws SQLException {
1221 final var recipient = findByNumber(connection, number);
1222
1223 if (recipient.isEmpty()) {
1224 logger.debug("Got new recipient, number is unknown");
1225 return addNewRecipient(connection, new RecipientAddress(number));
1226 }
1227
1228 return recipient.get().id();
1229 }
1230
1231 private RecipientId addNewRecipient(
1232 final Connection connection, final RecipientAddress address
1233 ) throws SQLException {
1234 final var sql = (
1235 """
1236 INSERT INTO %s (number, aci, pni, username)
1237 VALUES (?, ?, ?, ?)
1238 RETURNING _id
1239 """
1240 ).formatted(TABLE_RECIPIENT);
1241 try (final var statement = connection.prepareStatement(sql)) {
1242 statement.setString(1, address.number().orElse(null));
1243 statement.setString(2, address.aci().map(ACI::toString).orElse(null));
1244 statement.setString(3, address.pni().map(PNI::toString).orElse(null));
1245 statement.setString(4, address.username().orElse(null));
1246 final var generatedKey = Utils.executeQueryForOptional(statement, Utils::getIdMapper);
1247 if (generatedKey.isPresent()) {
1248 final var recipientId = new RecipientId(generatedKey.get(), this);
1249 logger.debug("Added new recipient {} with address {}", recipientId, address);
1250 return recipientId;
1251 } else {
1252 throw new RuntimeException("Failed to add new recipient to database");
1253 }
1254 }
1255 }
1256
1257 private void removeRecipientAddress(Connection connection, RecipientId recipientId) throws SQLException {
1258 recipientAddressCache.entrySet().removeIf(e -> e.getValue().id().equals(recipientId));
1259 final var sql = (
1260 """
1261 UPDATE %s
1262 SET number = NULL, aci = NULL, pni = NULL, username = NULL, storage_id = NULL
1263 WHERE _id = ?
1264 """
1265 ).formatted(TABLE_RECIPIENT);
1266 try (final var statement = connection.prepareStatement(sql)) {
1267 statement.setLong(1, recipientId.id());
1268 statement.executeUpdate();
1269 }
1270 }
1271
1272 private void updateRecipientAddress(
1273 Connection connection, RecipientId recipientId, final RecipientAddress address
1274 ) throws SQLException {
1275 recipientAddressCache.entrySet().removeIf(e -> e.getValue().id().equals(recipientId));
1276 final var sql = (
1277 """
1278 UPDATE %s
1279 SET number = ?, aci = ?, pni = ?, username = ?
1280 WHERE _id = ?
1281 """
1282 ).formatted(TABLE_RECIPIENT);
1283 try (final var statement = connection.prepareStatement(sql)) {
1284 statement.setString(1, address.number().orElse(null));
1285 statement.setString(2, address.aci().map(ACI::toString).orElse(null));
1286 statement.setString(3, address.pni().map(PNI::toString).orElse(null));
1287 statement.setString(4, address.username().orElse(null));
1288 statement.setLong(5, recipientId.id());
1289 statement.executeUpdate();
1290 }
1291 rotateStorageId(connection, recipientId);
1292 }
1293
1294 private void deleteRecipient(final Connection connection, final RecipientId recipientId) throws SQLException {
1295 final var sql = (
1296 """
1297 DELETE FROM %s
1298 WHERE _id = ?
1299 """
1300 ).formatted(TABLE_RECIPIENT);
1301 try (final var statement = connection.prepareStatement(sql)) {
1302 statement.setLong(1, recipientId.id());
1303 statement.executeUpdate();
1304 }
1305 }
1306
1307 private void mergeRecipientsLocked(
1308 Connection connection, RecipientId recipientId, RecipientId toBeMergedRecipientId
1309 ) throws SQLException {
1310 final var contact = getContact(connection, recipientId);
1311 if (contact == null) {
1312 final var toBeMergedContact = getContact(connection, toBeMergedRecipientId);
1313 storeContact(connection, recipientId, toBeMergedContact);
1314 }
1315
1316 final var profileKey = getProfileKey(connection, recipientId);
1317 if (profileKey == null) {
1318 final var toBeMergedProfileKey = getProfileKey(connection, toBeMergedRecipientId);
1319 storeProfileKey(connection, recipientId, toBeMergedProfileKey, false);
1320 }
1321
1322 final var profileKeyCredential = getExpiringProfileKeyCredential(connection, recipientId);
1323 if (profileKeyCredential == null) {
1324 final var toBeMergedProfileKeyCredential = getExpiringProfileKeyCredential(connection,
1325 toBeMergedRecipientId);
1326 storeExpiringProfileKeyCredential(connection, recipientId, toBeMergedProfileKeyCredential);
1327 }
1328
1329 final var profile = getProfile(connection, recipientId);
1330 if (profile == null) {
1331 final var toBeMergedProfile = getProfile(connection, toBeMergedRecipientId);
1332 storeProfile(connection, recipientId, toBeMergedProfile);
1333 }
1334
1335 recipientsMerged.put(toBeMergedRecipientId.id(), recipientId.id());
1336 }
1337
1338 private Optional<RecipientWithAddress> findByNumber(
1339 final Connection connection, final String number
1340 ) throws SQLException {
1341 final var sql = """
1342 SELECT r._id, r.number, r.aci, r.pni, r.username
1343 FROM %s r
1344 WHERE r.number = ?
1345 LIMIT 1
1346 """.formatted(TABLE_RECIPIENT);
1347 try (final var statement = connection.prepareStatement(sql)) {
1348 statement.setString(1, number);
1349 return Utils.executeQueryForOptional(statement, this::getRecipientWithAddressFromResultSet);
1350 }
1351 }
1352
1353 private Optional<RecipientWithAddress> findByUsername(
1354 final Connection connection, final String username
1355 ) throws SQLException {
1356 final var sql = """
1357 SELECT r._id, r.number, r.aci, r.pni, r.username
1358 FROM %s r
1359 WHERE r.username = ?
1360 LIMIT 1
1361 """.formatted(TABLE_RECIPIENT);
1362 try (final var statement = connection.prepareStatement(sql)) {
1363 statement.setString(1, username);
1364 return Utils.executeQueryForOptional(statement, this::getRecipientWithAddressFromResultSet);
1365 }
1366 }
1367
1368 private Optional<RecipientWithAddress> findByServiceId(
1369 final Connection connection, final ServiceId serviceId
1370 ) throws SQLException {
1371 var recipientWithAddress = Optional.ofNullable(recipientAddressCache.get(serviceId));
1372 if (recipientWithAddress.isPresent()) {
1373 return recipientWithAddress;
1374 }
1375 final var sql = """
1376 SELECT r._id, r.number, r.aci, r.pni, r.username
1377 FROM %s r
1378 WHERE %s = ?1
1379 LIMIT 1
1380 """.formatted(TABLE_RECIPIENT, serviceId instanceof ACI ? "r.aci" : "r.pni");
1381 try (final var statement = connection.prepareStatement(sql)) {
1382 statement.setString(1, serviceId.toString());
1383 recipientWithAddress = Utils.executeQueryForOptional(statement, this::getRecipientWithAddressFromResultSet);
1384 recipientWithAddress.ifPresent(r -> recipientAddressCache.put(serviceId, r));
1385 return recipientWithAddress;
1386 }
1387 }
1388
1389 private Set<RecipientWithAddress> findAllByAddress(
1390 final Connection connection, final RecipientAddress address
1391 ) throws SQLException {
1392 final var sql = """
1393 SELECT r._id, r.number, r.aci, r.pni, r.username
1394 FROM %s r
1395 WHERE r.aci = ?1 OR
1396 r.pni = ?2 OR
1397 r.number = ?3 OR
1398 r.username = ?4
1399 """.formatted(TABLE_RECIPIENT);
1400 try (final var statement = connection.prepareStatement(sql)) {
1401 statement.setString(1, address.aci().map(ServiceId::toString).orElse(null));
1402 statement.setString(2, address.pni().map(ServiceId::toString).orElse(null));
1403 statement.setString(3, address.number().orElse(null));
1404 statement.setString(4, address.username().orElse(null));
1405 return Utils.executeQueryForStream(statement, this::getRecipientWithAddressFromResultSet)
1406 .collect(Collectors.toSet());
1407 }
1408 }
1409
1410 private Contact getContact(final Connection connection, final RecipientId recipientId) throws SQLException {
1411 final var sql = (
1412 """
1413 SELECT r.given_name, r.family_name, r.nick_name, r.expiration_time, r.mute_until, r.hide_story, r.profile_sharing, r.color, r.blocked, r.archived, r.hidden, r.unregistered_timestamp
1414 FROM %s r
1415 WHERE r._id = ? AND (%s)
1416 """
1417 ).formatted(TABLE_RECIPIENT, SQL_IS_CONTACT);
1418 try (final var statement = connection.prepareStatement(sql)) {
1419 statement.setLong(1, recipientId.id());
1420 return Utils.executeQueryForOptional(statement, this::getContactFromResultSet).orElse(null);
1421 }
1422 }
1423
1424 private ProfileKey getProfileKey(final Connection connection, final RecipientId recipientId) throws SQLException {
1425 final var selfRecipientId = resolveRecipientLocked(connection, selfAddressProvider.getSelfAddress());
1426 if (recipientId.equals(selfRecipientId)) {
1427 return selfProfileKeyProvider.getSelfProfileKey();
1428 }
1429 final var sql = (
1430 """
1431 SELECT r.profile_key
1432 FROM %s r
1433 WHERE r._id = ?
1434 """
1435 ).formatted(TABLE_RECIPIENT);
1436 try (final var statement = connection.prepareStatement(sql)) {
1437 statement.setLong(1, recipientId.id());
1438 return Utils.executeQueryForOptional(statement, this::getProfileKeyFromResultSet).orElse(null);
1439 }
1440 }
1441
1442 private ExpiringProfileKeyCredential getExpiringProfileKeyCredential(
1443 final Connection connection, final RecipientId recipientId
1444 ) throws SQLException {
1445 final var sql = (
1446 """
1447 SELECT r.profile_key_credential
1448 FROM %s r
1449 WHERE r._id = ?
1450 """
1451 ).formatted(TABLE_RECIPIENT);
1452 try (final var statement = connection.prepareStatement(sql)) {
1453 statement.setLong(1, recipientId.id());
1454 return Utils.executeQueryForOptional(statement, this::getExpiringProfileKeyCredentialFromResultSet)
1455 .orElse(null);
1456 }
1457 }
1458
1459 public Profile getProfile(final Connection connection, final RecipientId recipientId) throws SQLException {
1460 final var sql = (
1461 """
1462 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, r.profile_phone_number_sharing
1463 FROM %s r
1464 WHERE r._id = ? AND r.profile_capabilities IS NOT NULL
1465 """
1466 ).formatted(TABLE_RECIPIENT);
1467 try (final var statement = connection.prepareStatement(sql)) {
1468 statement.setLong(1, recipientId.id());
1469 return Utils.executeQueryForOptional(statement, this::getProfileFromResultSet).orElse(null);
1470 }
1471 }
1472
1473 private RecipientAddress getRecipientAddressFromResultSet(ResultSet resultSet) throws SQLException {
1474 final var aci = Optional.ofNullable(resultSet.getString("aci")).map(ACI::parseOrNull);
1475 final var pni = Optional.ofNullable(resultSet.getString("pni")).map(PNI::parseOrNull);
1476 final var number = Optional.ofNullable(resultSet.getString("number"));
1477 final var username = Optional.ofNullable(resultSet.getString("username"));
1478 return new RecipientAddress(aci, pni, number, username);
1479 }
1480
1481 private RecipientId getRecipientIdFromResultSet(ResultSet resultSet) throws SQLException {
1482 return new RecipientId(resultSet.getLong("_id"), this);
1483 }
1484
1485 private RecipientWithAddress getRecipientWithAddressFromResultSet(final ResultSet resultSet) throws SQLException {
1486 return new RecipientWithAddress(getRecipientIdFromResultSet(resultSet),
1487 getRecipientAddressFromResultSet(resultSet));
1488 }
1489
1490 private Recipient getRecipientFromResultSet(final ResultSet resultSet) throws SQLException {
1491 return new Recipient(getRecipientIdFromResultSet(resultSet),
1492 getRecipientAddressFromResultSet(resultSet),
1493 getContactFromResultSet(resultSet),
1494 getProfileKeyFromResultSet(resultSet),
1495 getExpiringProfileKeyCredentialFromResultSet(resultSet),
1496 getProfileFromResultSet(resultSet),
1497 getDiscoverableFromResultSet(resultSet),
1498 getStorageRecordFromResultSet(resultSet));
1499 }
1500
1501 private Contact getContactFromResultSet(ResultSet resultSet) throws SQLException {
1502 final var unregisteredTimestamp = resultSet.getLong("unregistered_timestamp");
1503 return new Contact(resultSet.getString("given_name"),
1504 resultSet.getString("family_name"),
1505 resultSet.getString("nick_name"),
1506 resultSet.getString("nick_name_given_name"),
1507 resultSet.getString("nick_name_family_name"),
1508 resultSet.getString("note"),
1509 resultSet.getString("color"),
1510 resultSet.getInt("expiration_time"),
1511 resultSet.getLong("mute_until"),
1512 resultSet.getBoolean("hide_story"),
1513 resultSet.getBoolean("blocked"),
1514 resultSet.getBoolean("archived"),
1515 resultSet.getBoolean("profile_sharing"),
1516 resultSet.getBoolean("hidden"),
1517 unregisteredTimestamp == 0 ? null : unregisteredTimestamp);
1518 }
1519
1520 private static Boolean getDiscoverableFromResultSet(final ResultSet resultSet) throws SQLException {
1521 final var discoverable = resultSet.getBoolean("discoverable");
1522 if (resultSet.wasNull()) {
1523 return null;
1524 }
1525 return discoverable;
1526 }
1527
1528 private Profile getProfileFromResultSet(ResultSet resultSet) throws SQLException {
1529 final var profileCapabilities = resultSet.getString("profile_capabilities");
1530 final var profileUnidentifiedAccessMode = resultSet.getString("profile_unidentified_access_mode");
1531 return new Profile(resultSet.getLong("profile_last_update_timestamp"),
1532 resultSet.getString("profile_given_name"),
1533 resultSet.getString("profile_family_name"),
1534 resultSet.getString("profile_about"),
1535 resultSet.getString("profile_about_emoji"),
1536 resultSet.getString("profile_avatar_url_path"),
1537 resultSet.getBytes("profile_mobile_coin_address"),
1538 profileUnidentifiedAccessMode == null
1539 ? Profile.UnidentifiedAccessMode.UNKNOWN
1540 : Profile.UnidentifiedAccessMode.valueOfOrUnknown(profileUnidentifiedAccessMode),
1541 profileCapabilities == null
1542 ? Set.of()
1543 : Arrays.stream(profileCapabilities.split(","))
1544 .map(Profile.Capability::valueOfOrNull)
1545 .filter(Objects::nonNull)
1546 .collect(Collectors.toSet()),
1547 PhoneNumberSharingMode.valueOfOrNull(resultSet.getString("profile_phone_number_sharing")));
1548 }
1549
1550 private ProfileKey getProfileKeyFromResultSet(ResultSet resultSet) throws SQLException {
1551 final var profileKey = resultSet.getBytes("profile_key");
1552
1553 if (profileKey == null) {
1554 return null;
1555 }
1556 try {
1557 return new ProfileKey(profileKey);
1558 } catch (InvalidInputException ignored) {
1559 return null;
1560 }
1561 }
1562
1563 private ExpiringProfileKeyCredential getExpiringProfileKeyCredentialFromResultSet(ResultSet resultSet) throws SQLException {
1564 final var profileKeyCredential = resultSet.getBytes("profile_key_credential");
1565
1566 if (profileKeyCredential == null) {
1567 return null;
1568 }
1569 try {
1570 return new ExpiringProfileKeyCredential(profileKeyCredential);
1571 } catch (Throwable ignored) {
1572 return null;
1573 }
1574 }
1575
1576 private StorageId getContactStorageIdFromResultSet(ResultSet resultSet) throws SQLException {
1577 final var storageId = resultSet.getBytes("storage_id");
1578 return StorageId.forContact(storageId);
1579 }
1580
1581 private byte[] getStorageRecordFromResultSet(ResultSet resultSet) throws SQLException {
1582 return resultSet.getBytes("storage_record");
1583 }
1584
1585 public interface RecipientMergeHandler {
1586
1587 void mergeRecipients(
1588 final Connection connection, RecipientId recipientId, RecipientId toBeMergedRecipientId
1589 ) throws SQLException;
1590 }
1591
1592 private class HelperStore implements MergeRecipientHelper.Store {
1593
1594 private final Connection connection;
1595
1596 public HelperStore(final Connection connection) {
1597 this.connection = connection;
1598 }
1599
1600 @Override
1601 public Set<RecipientWithAddress> findAllByAddress(final RecipientAddress address) throws SQLException {
1602 return RecipientStore.this.findAllByAddress(connection, address);
1603 }
1604
1605 @Override
1606 public RecipientId addNewRecipient(final RecipientAddress address) throws SQLException {
1607 return RecipientStore.this.addNewRecipient(connection, address);
1608 }
1609
1610 @Override
1611 public void updateRecipientAddress(
1612 final RecipientId recipientId, final RecipientAddress address
1613 ) throws SQLException {
1614 RecipientStore.this.updateRecipientAddress(connection, recipientId, address);
1615 }
1616
1617 @Override
1618 public void removeRecipientAddress(final RecipientId recipientId) throws SQLException {
1619 RecipientStore.this.removeRecipientAddress(connection, recipientId);
1620 }
1621 }
1622 }