1 package org
.asamk
.signal
.manager
.storage
.recipients
;
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
.asamk
.signal
.manager
.util
.KeyUtils
;
12 import org
.signal
.libsignal
.zkgroup
.InvalidInputException
;
13 import org
.signal
.libsignal
.zkgroup
.profiles
.ExpiringProfileKeyCredential
;
14 import org
.signal
.libsignal
.zkgroup
.profiles
.ProfileKey
;
15 import org
.slf4j
.Logger
;
16 import org
.slf4j
.LoggerFactory
;
17 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
;
18 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
.ACI
;
19 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
.PNI
;
20 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
21 import org
.whispersystems
.signalservice
.api
.storage
.StorageId
;
23 import java
.sql
.Connection
;
24 import java
.sql
.ResultSet
;
25 import java
.sql
.SQLException
;
26 import java
.sql
.Types
;
27 import java
.util
.ArrayList
;
28 import java
.util
.Arrays
;
29 import java
.util
.Collection
;
30 import java
.util
.HashMap
;
31 import java
.util
.List
;
33 import java
.util
.Objects
;
34 import java
.util
.Optional
;
36 import java
.util
.function
.Supplier
;
37 import java
.util
.stream
.Collectors
;
39 public class RecipientStore
implements RecipientIdCreator
, RecipientResolver
, RecipientTrustedResolver
, ContactsStore
, ProfileStore
{
41 private static final Logger logger
= LoggerFactory
.getLogger(RecipientStore
.class);
42 private static final String TABLE_RECIPIENT
= "recipient";
43 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 private final RecipientMergeHandler recipientMergeHandler
;
46 private final SelfAddressProvider selfAddressProvider
;
47 private final SelfProfileKeyProvider selfProfileKeyProvider
;
48 private final Database database
;
50 private final Object recipientsLock
= new Object();
51 private final Map
<Long
, Long
> recipientsMerged
= new HashMap
<>();
53 private final Map
<ServiceId
, RecipientWithAddress
> recipientAddressCache
= new HashMap
<>();
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,
67 unregistered_timestamp INTEGER,
69 profile_key_credential BLOB,
76 expiration_time INTEGER NOT NULL DEFAULT 0,
77 mute_until INTEGER NOT NULL DEFAULT 0,
78 blocked INTEGER NOT NULL DEFAULT FALSE,
79 archived INTEGER NOT NULL DEFAULT FALSE,
80 profile_sharing INTEGER NOT NULL DEFAULT FALSE,
81 hide_story INTEGER NOT NULL DEFAULT FALSE,
82 hidden INTEGER NOT NULL DEFAULT FALSE,
84 profile_last_update_timestamp INTEGER NOT NULL DEFAULT 0,
85 profile_given_name TEXT,
86 profile_family_name TEXT,
88 profile_about_emoji TEXT,
89 profile_avatar_url_path TEXT,
90 profile_mobile_coin_address BLOB,
91 profile_unidentified_access_mode TEXT,
92 profile_capabilities TEXT
98 public RecipientStore(
99 final RecipientMergeHandler recipientMergeHandler
,
100 final SelfAddressProvider selfAddressProvider
,
101 final SelfProfileKeyProvider selfProfileKeyProvider
,
102 final Database database
104 this.recipientMergeHandler
= recipientMergeHandler
;
105 this.selfAddressProvider
= selfAddressProvider
;
106 this.selfProfileKeyProvider
= selfProfileKeyProvider
;
107 this.database
= database
;
110 public RecipientAddress
resolveRecipientAddress(RecipientId recipientId
) {
111 try (final var connection
= database
.getConnection()) {
112 return resolveRecipientAddress(connection
, recipientId
);
113 } catch (SQLException e
) {
114 throw new RuntimeException("Failed read from recipient store", e
);
118 public Collection
<RecipientId
> getRecipientIdsWithEnabledProfileSharing() {
123 WHERE r.blocked = FALSE AND r.profile_sharing = TRUE
125 ).formatted(TABLE_RECIPIENT
);
126 try (final var connection
= database
.getConnection()) {
127 try (final var statement
= connection
.prepareStatement(sql
)) {
128 try (var result
= Utils
.executeQueryForStream(statement
, this::getRecipientIdFromResultSet
)) {
129 return result
.toList();
132 } catch (SQLException e
) {
133 throw new RuntimeException("Failed read from recipient store", e
);
138 public RecipientId
resolveRecipient(final long rawRecipientId
) {
145 ).formatted(TABLE_RECIPIENT
);
146 try (final var connection
= database
.getConnection()) {
147 try (final var statement
= connection
.prepareStatement(sql
)) {
148 statement
.setLong(1, rawRecipientId
);
149 return Utils
.executeQueryForOptional(statement
, this::getRecipientIdFromResultSet
).orElse(null);
151 } catch (SQLException e
) {
152 throw new RuntimeException("Failed read from recipient store", e
);
157 public RecipientId
resolveRecipient(final String identifier
) {
158 final var serviceId
= ServiceId
.parseOrNull(identifier
);
159 if (serviceId
!= null) {
160 return resolveRecipient(serviceId
);
162 return resolveRecipientByNumber(identifier
);
166 private RecipientId
resolveRecipientByNumber(final String number
) {
167 synchronized (recipientsLock
) {
168 final RecipientId recipientId
;
169 try (final var connection
= database
.getConnection()) {
170 connection
.setAutoCommit(false);
171 recipientId
= resolveRecipientLocked(connection
, number
);
173 } catch (SQLException e
) {
174 throw new RuntimeException("Failed read recipient store", e
);
181 public RecipientId
resolveRecipient(final ServiceId serviceId
) {
182 synchronized (recipientsLock
) {
183 final var recipientWithAddress
= recipientAddressCache
.get(serviceId
);
184 if (recipientWithAddress
!= null) {
185 return recipientWithAddress
.id();
187 try (final var connection
= database
.getConnection()) {
188 connection
.setAutoCommit(false);
189 final var recipientId
= resolveRecipientLocked(connection
, serviceId
);
192 } catch (SQLException e
) {
193 throw new RuntimeException("Failed read recipient store", e
);
199 * Should only be used for recipientIds from the database.
200 * Where the foreign key relations ensure a valid recipientId.
203 public RecipientId
create(final long recipientId
) {
204 return new RecipientId(recipientId
, this);
207 public RecipientId
resolveRecipientByNumber(
208 final String number
, Supplier
<ServiceId
> serviceIdSupplier
209 ) throws UnregisteredRecipientException
{
210 final Optional
<RecipientWithAddress
> byNumber
;
211 try (final var connection
= database
.getConnection()) {
212 byNumber
= findByNumber(connection
, number
);
213 } catch (SQLException e
) {
214 throw new RuntimeException("Failed read from recipient store", e
);
216 if (byNumber
.isEmpty() || byNumber
.get().address().serviceId().isEmpty()) {
217 final var serviceId
= serviceIdSupplier
.get();
218 if (serviceId
== null) {
219 throw new UnregisteredRecipientException(new org
.asamk
.signal
.manager
.api
.RecipientAddress(null,
223 return resolveRecipient(serviceId
);
225 return byNumber
.get().id();
228 public Optional
<RecipientId
> resolveRecipientByNumberOptional(final String number
) {
229 final Optional
<RecipientWithAddress
> byNumber
;
230 try (final var connection
= database
.getConnection()) {
231 byNumber
= findByNumber(connection
, number
);
232 } catch (SQLException e
) {
233 throw new RuntimeException("Failed read from recipient store", e
);
235 return byNumber
.map(RecipientWithAddress
::id
);
238 public RecipientId
resolveRecipientByUsername(
239 final String username
, Supplier
<ACI
> aciSupplier
240 ) throws UnregisteredRecipientException
{
241 final Optional
<RecipientWithAddress
> byUsername
;
242 try (final var connection
= database
.getConnection()) {
243 byUsername
= findByUsername(connection
, username
);
244 } catch (SQLException e
) {
245 throw new RuntimeException("Failed read from recipient store", e
);
247 if (byUsername
.isEmpty() || byUsername
.get().address().serviceId().isEmpty()) {
248 final var aci
= aciSupplier
.get();
250 throw new UnregisteredRecipientException(new org
.asamk
.signal
.manager
.api
.RecipientAddress(null,
255 return resolveRecipientTrusted(aci
, username
);
257 return byUsername
.get().id();
260 public RecipientId
resolveRecipient(RecipientAddress address
) {
261 synchronized (recipientsLock
) {
262 final RecipientId recipientId
;
263 try (final var connection
= database
.getConnection()) {
264 connection
.setAutoCommit(false);
265 recipientId
= resolveRecipientLocked(connection
, address
);
267 } catch (SQLException e
) {
268 throw new RuntimeException("Failed read recipient store", e
);
274 public RecipientId
resolveRecipient(Connection connection
, RecipientAddress address
) throws SQLException
{
275 return resolveRecipientLocked(connection
, address
);
279 public RecipientId
resolveSelfRecipientTrusted(RecipientAddress address
) {
280 return resolveRecipientTrusted(address
, true);
284 public RecipientId
resolveRecipientTrusted(RecipientAddress address
) {
285 return resolveRecipientTrusted(address
, false);
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());
297 public RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
298 return resolveRecipientTrusted(new RecipientAddress(address
));
302 public RecipientId
resolveRecipientTrusted(
303 final Optional
<ACI
> aci
, final Optional
<PNI
> pni
, final Optional
<String
> number
305 return resolveRecipientTrusted(new RecipientAddress(aci
, pni
, number
, Optional
.empty()));
309 public RecipientId
resolveRecipientTrusted(final ACI aci
, final String username
) {
310 return resolveRecipientTrusted(new RecipientAddress(aci
, null, null, username
));
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
);
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
);
332 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
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
337 WHERE (r.number IS NOT NULL OR r.aci IS NOT NULL) AND %s AND r.hidden = FALSE
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();
348 } catch (SQLException e
) {
349 throw new RuntimeException("Failed read from recipient store", e
);
353 public Recipient
getRecipient(Connection connection
, RecipientId recipientId
) throws SQLException
{
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,
365 ).formatted(TABLE_RECIPIENT
);
366 try (final var statement
= connection
.prepareStatement(sql
)) {
367 statement
.setLong(1, recipientId
.id());
368 return Utils
.executeQuerySingleRow(statement
, this::getRecipientFromResultSet
);
372 public Recipient
getRecipient(Connection connection
, StorageId storageId
) throws SQLException
{
376 r.number, r.aci, r.pni, r.username,
377 r.profile_key, r.profile_key_credential,
378 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,
379 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,
382 WHERE r.storage_id = ?
384 ).formatted(TABLE_RECIPIENT
);
385 try (final var statement
= connection
.prepareStatement(sql
)) {
386 statement
.setBytes(1, storageId
.getRaw());
387 return Utils
.executeQuerySingleRow(statement
, this::getRecipientFromResultSet
);
391 public List
<Recipient
> getRecipients(
392 boolean onlyContacts
, Optional
<Boolean
> blocked
, Set
<RecipientId
> recipientIds
, Optional
<String
> name
394 final var sqlWhere
= new ArrayList
<String
>();
396 sqlWhere
.add("(" + SQL_IS_CONTACT
+ ")");
397 sqlWhere
.add("r.hidden = FALSE");
399 if (blocked
.isPresent()) {
400 sqlWhere
.add("r.blocked = ?");
402 if (!recipientIds
.isEmpty()) {
403 final var recipientIdsCommaSeparated
= recipientIds
.stream()
404 .map(recipientId
-> String
.valueOf(recipientId
.id()))
405 .collect(Collectors
.joining(","));
406 sqlWhere
.add("r._id IN (" + recipientIdsCommaSeparated
+ ")");
411 r.number, r.aci, r.pni, r.username,
412 r.profile_key, r.profile_key_credential,
413 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,
414 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,
417 WHERE (r.number IS NOT NULL OR r.aci IS NOT NULL) AND %s
419 ).formatted(TABLE_RECIPIENT
, sqlWhere
.isEmpty() ?
"TRUE" : String
.join(" AND ", sqlWhere
));
420 final var selfAddress
= selfAddressProvider
.getSelfAddress();
421 try (final var connection
= database
.getConnection()) {
422 try (final var statement
= connection
.prepareStatement(sql
)) {
423 if (blocked
.isPresent()) {
424 statement
.setBoolean(1, blocked
.get());
426 try (var result
= Utils
.executeQueryForStream(statement
, this::getRecipientFromResultSet
)) {
427 return result
.filter(r
-> name
.isEmpty() || (
428 r
.getContact() != null && name
.get().equals(r
.getContact().getName())
429 ) || (r
.getProfile() != null && name
.get().equals(r
.getProfile().getDisplayName()))).map(r
-> {
430 if (r
.getAddress().matches(selfAddress
)) {
431 return Recipient
.newBuilder(r
)
432 .withProfileKey(selfProfileKeyProvider
.getSelfProfileKey())
439 } catch (SQLException e
) {
440 throw new RuntimeException("Failed read from recipient store", e
);
444 public Set
<String
> getAllNumbers() {
449 WHERE r.number IS NOT NULL
451 ).formatted(TABLE_RECIPIENT
);
452 final var selfNumber
= selfAddressProvider
.getSelfAddress().number().orElse(null);
453 try (final var connection
= database
.getConnection()) {
454 try (final var statement
= connection
.prepareStatement(sql
)) {
455 return Utils
.executeQueryForStream(statement
, resultSet
-> resultSet
.getString("number"))
456 .filter(Objects
::nonNull
)
457 .filter(n
-> !n
.equals(selfNumber
))
462 } catch (NumberFormatException e
) {
466 .collect(Collectors
.toSet());
468 } catch (SQLException e
) {
469 throw new RuntimeException("Failed read from recipient store", e
);
473 public Map
<ServiceId
, ProfileKey
> getServiceIdToProfileKeyMap() {
476 SELECT r.aci, r.profile_key
478 WHERE r.aci IS NOT NULL AND r.profile_key IS NOT NULL
480 ).formatted(TABLE_RECIPIENT
);
481 final var selfAci
= selfAddressProvider
.getSelfAddress().aci().orElse(null);
482 try (final var connection
= database
.getConnection()) {
483 try (final var statement
= connection
.prepareStatement(sql
)) {
484 return Utils
.executeQueryForStream(statement
, resultSet
-> {
485 final var aci
= ACI
.parseOrThrow(resultSet
.getString("aci"));
486 if (aci
.equals(selfAci
)) {
487 return new Pair
<>(aci
, selfProfileKeyProvider
.getSelfProfileKey());
489 final var profileKey
= getProfileKeyFromResultSet(resultSet
);
490 return new Pair
<>(aci
, profileKey
);
491 }).filter(Objects
::nonNull
).collect(Collectors
.toMap(Pair
::first
, Pair
::second
));
493 } catch (SQLException e
) {
494 throw new RuntimeException("Failed read from recipient store", e
);
498 public List
<RecipientId
> getRecipientIds(Connection connection
) throws SQLException
{
503 WHERE (r.number IS NOT NULL OR r.aci IS NOT NULL)
505 ).formatted(TABLE_RECIPIENT
);
506 try (final var statement
= connection
.prepareStatement(sql
)) {
507 return Utils
.executeQueryForStream(statement
, this::getRecipientIdFromResultSet
).toList();
511 public void setMissingStorageIds() {
512 final var selectSql
= (
516 WHERE r.storage_id IS NULL AND r.unregistered_timestamp IS NULL
518 ).formatted(TABLE_RECIPIENT
);
519 final var updateSql
= (
525 ).formatted(TABLE_RECIPIENT
);
526 try (final var connection
= database
.getConnection()) {
527 connection
.setAutoCommit(false);
528 try (final var selectStmt
= connection
.prepareStatement(selectSql
)) {
529 final var recipientIds
= Utils
.executeQueryForStream(selectStmt
, this::getRecipientIdFromResultSet
)
531 try (final var updateStmt
= connection
.prepareStatement(updateSql
)) {
532 for (final var recipientId
: recipientIds
) {
533 updateStmt
.setBytes(1, KeyUtils
.createRawStorageId());
534 updateStmt
.setLong(2, recipientId
.id());
535 updateStmt
.executeUpdate();
540 } catch (SQLException e
) {
541 throw new RuntimeException("Failed update recipient store", e
);
546 public void deleteContact(RecipientId recipientId
) {
547 storeContact(recipientId
, null);
550 public void deleteRecipientData(RecipientId recipientId
) {
551 logger
.debug("Deleting recipient data for {}", recipientId
);
552 synchronized (recipientsLock
) {
553 recipientAddressCache
.entrySet().removeIf(e
-> e
.getValue().id().equals(recipientId
));
554 try (final var connection
= database
.getConnection()) {
555 connection
.setAutoCommit(false);
556 storeContact(connection
, recipientId
, null);
557 storeProfile(connection
, recipientId
, null);
558 storeProfileKey(connection
, recipientId
, null, false);
559 storeExpiringProfileKeyCredential(connection
, recipientId
, null);
560 deleteRecipient(connection
, recipientId
);
562 } catch (SQLException e
) {
563 throw new RuntimeException("Failed update recipient store", e
);
569 public Profile
getProfile(final RecipientId recipientId
) {
570 try (final var connection
= database
.getConnection()) {
571 return getProfile(connection
, recipientId
);
572 } catch (SQLException e
) {
573 throw new RuntimeException("Failed read from recipient store", e
);
578 public ProfileKey
getProfileKey(final RecipientId recipientId
) {
579 try (final var connection
= database
.getConnection()) {
580 return getProfileKey(connection
, recipientId
);
581 } catch (SQLException e
) {
582 throw new RuntimeException("Failed read from recipient store", e
);
587 public ExpiringProfileKeyCredential
getExpiringProfileKeyCredential(final RecipientId recipientId
) {
588 try (final var connection
= database
.getConnection()) {
589 return getExpiringProfileKeyCredential(connection
, recipientId
);
590 } catch (SQLException e
) {
591 throw new RuntimeException("Failed read from recipient store", e
);
596 public void storeProfile(RecipientId recipientId
, final Profile profile
) {
597 try (final var connection
= database
.getConnection()) {
598 storeProfile(connection
, recipientId
, profile
);
599 } catch (SQLException e
) {
600 throw new RuntimeException("Failed update recipient store", e
);
605 public void storeProfileKey(RecipientId recipientId
, final ProfileKey profileKey
) {
606 try (final var connection
= database
.getConnection()) {
607 storeProfileKey(connection
, recipientId
, profileKey
);
608 } catch (SQLException e
) {
609 throw new RuntimeException("Failed update recipient store", e
);
613 public void storeProfileKey(
614 Connection connection
, RecipientId recipientId
, final ProfileKey profileKey
615 ) throws SQLException
{
616 storeProfileKey(connection
, recipientId
, profileKey
, true);
620 public void storeExpiringProfileKeyCredential(
621 RecipientId recipientId
, final ExpiringProfileKeyCredential profileKeyCredential
623 try (final var connection
= database
.getConnection()) {
624 storeExpiringProfileKeyCredential(connection
, recipientId
, profileKeyCredential
);
625 } catch (SQLException e
) {
626 throw new RuntimeException("Failed update recipient store", e
);
630 public void rotateSelfStorageId() {
631 try (final var connection
= database
.getConnection()) {
632 rotateSelfStorageId(connection
);
633 } catch (SQLException e
) {
634 throw new RuntimeException("Failed update recipient store", e
);
638 public void rotateSelfStorageId(final Connection connection
) throws SQLException
{
639 final var selfRecipientId
= resolveRecipient(connection
, selfAddressProvider
.getSelfAddress());
640 rotateStorageId(connection
, selfRecipientId
);
643 public StorageId
rotateStorageId(final Connection connection
, final ServiceId serviceId
) throws SQLException
{
644 final var selfRecipientId
= resolveRecipient(connection
, new RecipientAddress(serviceId
));
645 return rotateStorageId(connection
, selfRecipientId
);
648 public List
<StorageId
> getStorageIds(Connection connection
) throws SQLException
{
651 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)
652 """.formatted(TABLE_RECIPIENT
);
653 final var selfRecipientId
= resolveRecipient(connection
, selfAddressProvider
.getSelfAddress());
654 try (final var statement
= connection
.prepareStatement(sql
)) {
655 statement
.setLong(1, selfRecipientId
.id());
656 return Utils
.executeQueryForStream(statement
, this::getContactStorageIdFromResultSet
).toList();
660 public void updateStorageId(
661 Connection connection
, RecipientId recipientId
, StorageId storageId
662 ) throws SQLException
{
669 ).formatted(TABLE_RECIPIENT
);
670 try (final var statement
= connection
.prepareStatement(sql
)) {
671 statement
.setBytes(1, storageId
.getRaw());
672 statement
.setLong(2, recipientId
.id());
673 statement
.executeUpdate();
677 public void updateStorageIds(Connection connection
, Map
<RecipientId
, StorageId
> storageIdMap
) throws SQLException
{
684 ).formatted(TABLE_RECIPIENT
);
685 try (final var statement
= connection
.prepareStatement(sql
)) {
686 for (final var entry
: storageIdMap
.entrySet()) {
687 statement
.setBytes(1, entry
.getValue().getRaw());
688 statement
.setLong(2, entry
.getKey().id());
689 statement
.executeUpdate();
694 public StorageId
getSelfStorageId(final Connection connection
) throws SQLException
{
695 final var selfRecipientId
= resolveRecipient(connection
, selfAddressProvider
.getSelfAddress());
696 return StorageId
.forAccount(getStorageId(connection
, selfRecipientId
).getRaw());
699 public StorageId
getStorageId(final Connection connection
, final RecipientId recipientId
) throws SQLException
{
702 FROM %s r WHERE r._id = ? AND r.storage_id IS NOT NULL
703 """.formatted(TABLE_RECIPIENT
);
704 try (final var statement
= connection
.prepareStatement(sql
)) {
705 statement
.setLong(1, recipientId
.id());
706 final var storageId
= Utils
.executeQueryForOptional(statement
, this::getContactStorageIdFromResultSet
);
707 if (storageId
.isPresent()) {
708 return storageId
.get();
711 return rotateStorageId(connection
, recipientId
);
714 private StorageId
rotateStorageId(final Connection connection
, final RecipientId recipientId
) throws SQLException
{
715 final var newStorageId
= StorageId
.forAccount(KeyUtils
.createRawStorageId());
716 updateStorageId(connection
, recipientId
, newStorageId
);
720 public void storeStorageRecord(
721 final Connection connection
,
722 final RecipientId recipientId
,
723 final StorageId storageId
,
724 final byte[] storageRecord
725 ) throws SQLException
{
726 final var deleteSql
= (
729 SET storage_id = NULL
732 ).formatted(TABLE_RECIPIENT
);
733 try (final var statement
= connection
.prepareStatement(deleteSql
)) {
734 statement
.setBytes(1, storageId
.getRaw());
735 statement
.executeUpdate();
737 final var insertSql
= (
740 SET storage_id = ?, storage_record = ?
743 ).formatted(TABLE_RECIPIENT
);
744 try (final var statement
= connection
.prepareStatement(insertSql
)) {
745 statement
.setBytes(1, storageId
.getRaw());
746 if (storageRecord
== null) {
747 statement
.setNull(2, Types
.BLOB
);
749 statement
.setBytes(2, storageRecord
);
751 statement
.setLong(3, recipientId
.id());
752 statement
.executeUpdate();
756 void addLegacyRecipients(final Map
<RecipientId
, Recipient
> recipients
) {
757 logger
.debug("Migrating legacy recipients to database");
758 long start
= System
.nanoTime();
761 INSERT INTO %s (_id, number, aci)
764 ).formatted(TABLE_RECIPIENT
);
765 try (final var connection
= database
.getConnection()) {
766 connection
.setAutoCommit(false);
767 try (final var statement
= connection
.prepareStatement("DELETE FROM %s".formatted(TABLE_RECIPIENT
))) {
768 statement
.executeUpdate();
770 try (final var statement
= connection
.prepareStatement(sql
)) {
771 for (final var recipient
: recipients
.values()) {
772 statement
.setLong(1, recipient
.getRecipientId().id());
773 statement
.setString(2, recipient
.getAddress().number().orElse(null));
774 statement
.setString(3, recipient
.getAddress().aci().map(ACI
::toString
).orElse(null));
775 statement
.executeUpdate();
778 logger
.debug("Initial inserts took {}ms", (System
.nanoTime() - start
) / 1000000);
780 for (final var recipient
: recipients
.values()) {
781 if (recipient
.getContact() != null) {
782 storeContact(connection
, recipient
.getRecipientId(), recipient
.getContact());
784 if (recipient
.getProfile() != null) {
785 storeProfile(connection
, recipient
.getRecipientId(), recipient
.getProfile());
787 if (recipient
.getProfileKey() != null) {
788 storeProfileKey(connection
, recipient
.getRecipientId(), recipient
.getProfileKey(), false);
790 if (recipient
.getExpiringProfileKeyCredential() != null) {
791 storeExpiringProfileKeyCredential(connection
,
792 recipient
.getRecipientId(),
793 recipient
.getExpiringProfileKeyCredential());
797 } catch (SQLException e
) {
798 throw new RuntimeException("Failed update recipient store", e
);
800 logger
.debug("Complete recipients migration took {}ms", (System
.nanoTime() - start
) / 1000000);
803 long getActualRecipientId(long recipientId
) {
804 while (recipientsMerged
.containsKey(recipientId
)) {
805 final var newRecipientId
= recipientsMerged
.get(recipientId
);
806 logger
.debug("Using {} instead of {}, because recipients have been merged", newRecipientId
, recipientId
);
807 recipientId
= newRecipientId
;
812 public void storeContact(
813 final Connection connection
, final RecipientId recipientId
, final Contact contact
814 ) throws SQLException
{
818 SET given_name = ?, family_name = ?, nick_name = ?, expiration_time = ?, mute_until = ?, hide_story = ?, profile_sharing = ?, color = ?, blocked = ?, archived = ?, unregistered_timestamp = ?
821 ).formatted(TABLE_RECIPIENT
);
822 try (final var statement
= connection
.prepareStatement(sql
)) {
823 statement
.setString(1, contact
== null ?
null : contact
.givenName());
824 statement
.setString(2, contact
== null ?
null : contact
.familyName());
825 statement
.setString(3, contact
== null ?
null : contact
.nickName());
826 statement
.setInt(4, contact
== null ?
0 : contact
.messageExpirationTime());
827 statement
.setLong(5, contact
== null ?
0 : contact
.muteUntil());
828 statement
.setBoolean(6, contact
!= null && contact
.hideStory());
829 statement
.setBoolean(7, contact
!= null && contact
.isProfileSharingEnabled());
830 statement
.setString(8, contact
== null ?
null : contact
.color());
831 statement
.setBoolean(9, contact
!= null && contact
.isBlocked());
832 statement
.setBoolean(10, contact
!= null && contact
.isArchived());
833 if (contact
== null || contact
.unregisteredTimestamp() == null) {
834 statement
.setNull(11, Types
.INTEGER
);
836 statement
.setLong(11, contact
.unregisteredTimestamp());
838 statement
.setLong(12, recipientId
.id());
839 statement
.executeUpdate();
841 if (contact
!= null && contact
.unregisteredTimestamp() != null) {
842 markUnregisteredAndSplitIfNecessary(connection
, recipientId
);
844 rotateStorageId(connection
, recipientId
);
847 public int removeStorageIdsFromLocalOnlyUnregisteredRecipients(
848 final Connection connection
, final List
<StorageId
> storageIds
849 ) throws SQLException
{
853 SET storage_id = NULL
854 WHERE storage_id = ? AND unregistered_timestamp IS NOT NULL
856 ).formatted(TABLE_RECIPIENT
);
858 try (final var statement
= connection
.prepareStatement(sql
)) {
859 for (final var storageId
: storageIds
) {
860 statement
.setBytes(1, storageId
.getRaw());
861 count
+= statement
.executeUpdate();
867 public void markUnregistered(final Set
<String
> unregisteredUsers
) {
868 logger
.debug("Marking {} numbers as unregistered", unregisteredUsers
.size());
869 try (final var connection
= database
.getConnection()) {
870 connection
.setAutoCommit(false);
871 for (final var number
: unregisteredUsers
) {
872 final var recipient
= findByNumber(connection
, number
);
873 if (recipient
.isPresent()) {
874 final var recipientId
= recipient
.get().id();
875 markUnregisteredAndSplitIfNecessary(connection
, recipientId
);
879 } catch (SQLException e
) {
880 throw new RuntimeException("Failed update recipient store", e
);
884 private void markUnregisteredAndSplitIfNecessary(
885 final Connection connection
, final RecipientId recipientId
886 ) throws SQLException
{
887 markUnregistered(connection
, recipientId
);
888 final var address
= resolveRecipientAddress(connection
, recipientId
);
889 if (address
.aci().isPresent() && address
.pni().isPresent()) {
890 final var numberAddress
= new RecipientAddress(address
.pni().get(), address
.number().orElse(null));
891 updateRecipientAddress(connection
, recipientId
, address
.removeIdentifiersFrom(numberAddress
));
892 addNewRecipient(connection
, numberAddress
);
896 private void markRegistered(
897 final Connection connection
, final RecipientId recipientId
898 ) throws SQLException
{
902 SET unregistered_timestamp = ?
905 ).formatted(TABLE_RECIPIENT
);
906 try (final var statement
= connection
.prepareStatement(sql
)) {
907 statement
.setNull(1, Types
.INTEGER
);
908 statement
.setLong(2, recipientId
.id());
909 statement
.executeUpdate();
913 private void markUnregistered(
914 final Connection connection
, final RecipientId recipientId
915 ) throws SQLException
{
919 SET unregistered_timestamp = ?
920 WHERE _id = ? AND unregistered_timestamp IS NULL
922 ).formatted(TABLE_RECIPIENT
);
923 try (final var statement
= connection
.prepareStatement(sql
)) {
924 statement
.setLong(1, System
.currentTimeMillis());
925 statement
.setLong(2, recipientId
.id());
926 statement
.executeUpdate();
930 private void storeExpiringProfileKeyCredential(
931 final Connection connection
,
932 final RecipientId recipientId
,
933 final ExpiringProfileKeyCredential profileKeyCredential
934 ) throws SQLException
{
938 SET profile_key_credential = ?
941 ).formatted(TABLE_RECIPIENT
);
942 try (final var statement
= connection
.prepareStatement(sql
)) {
943 statement
.setBytes(1, profileKeyCredential
== null ?
null : profileKeyCredential
.serialize());
944 statement
.setLong(2, recipientId
.id());
945 statement
.executeUpdate();
949 public void storeProfile(
950 final Connection connection
, final RecipientId recipientId
, final Profile profile
951 ) throws SQLException
{
955 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 = ?
958 ).formatted(TABLE_RECIPIENT
);
959 try (final var statement
= connection
.prepareStatement(sql
)) {
960 statement
.setLong(1, profile
== null ?
0 : profile
.getLastUpdateTimestamp());
961 statement
.setString(2, profile
== null ?
null : profile
.getGivenName());
962 statement
.setString(3, profile
== null ?
null : profile
.getFamilyName());
963 statement
.setString(4, profile
== null ?
null : profile
.getAbout());
964 statement
.setString(5, profile
== null ?
null : profile
.getAboutEmoji());
965 statement
.setString(6, profile
== null ?
null : profile
.getAvatarUrlPath());
966 statement
.setBytes(7, profile
== null ?
null : profile
.getMobileCoinAddress());
967 statement
.setString(8, profile
== null ?
null : profile
.getUnidentifiedAccessMode().name());
968 statement
.setString(9,
971 : profile
.getCapabilities().stream().map(Enum
::name
).collect(Collectors
.joining(",")));
972 statement
.setLong(10, recipientId
.id());
973 statement
.executeUpdate();
975 rotateStorageId(connection
, recipientId
);
978 private void storeProfileKey(
979 Connection connection
, RecipientId recipientId
, final ProfileKey profileKey
, boolean resetProfile
980 ) throws SQLException
{
981 if (profileKey
!= null) {
982 final var recipientProfileKey
= getProfileKey(connection
, recipientId
);
983 if (profileKey
.equals(recipientProfileKey
)) {
984 final var recipientProfile
= getProfile(connection
, recipientId
);
985 if (recipientProfile
== null || (
986 recipientProfile
.getUnidentifiedAccessMode() != Profile
.UnidentifiedAccessMode
.UNKNOWN
987 && recipientProfile
.getUnidentifiedAccessMode()
988 != Profile
.UnidentifiedAccessMode
.DISABLED
998 SET profile_key = ?, profile_key_credential = NULL%s
1001 ).formatted(TABLE_RECIPIENT
, resetProfile ?
", profile_last_update_timestamp = 0" : "");
1002 try (final var statement
= connection
.prepareStatement(sql
)) {
1003 statement
.setBytes(1, profileKey
== null ?
null : profileKey
.serialize());
1004 statement
.setLong(2, recipientId
.id());
1005 statement
.executeUpdate();
1007 rotateStorageId(connection
, recipientId
);
1010 private RecipientAddress
resolveRecipientAddress(
1011 final Connection connection
, final RecipientId recipientId
1012 ) throws SQLException
{
1015 SELECT r.number, r.aci, r.pni, r.username
1019 ).formatted(TABLE_RECIPIENT
);
1020 try (final var statement
= connection
.prepareStatement(sql
)) {
1021 statement
.setLong(1, recipientId
.id());
1022 return Utils
.executeQuerySingleRow(statement
, this::getRecipientAddressFromResultSet
);
1026 private RecipientId
resolveRecipientTrusted(RecipientAddress address
, boolean isSelf
) {
1027 final Pair
<RecipientId
, List
<RecipientId
>> pair
;
1028 synchronized (recipientsLock
) {
1029 try (final var connection
= database
.getConnection()) {
1030 connection
.setAutoCommit(false);
1031 pair
= resolveRecipientTrustedLocked(connection
, address
, isSelf
);
1032 connection
.commit();
1033 } catch (SQLException e
) {
1034 throw new RuntimeException("Failed update recipient store", e
);
1038 if (!pair
.second().isEmpty()) {
1039 logger
.debug("Resolved address {}, merging {} other recipients", address
, pair
.second().size());
1040 try (final var connection
= database
.getConnection()) {
1041 connection
.setAutoCommit(false);
1042 mergeRecipients(connection
, pair
.first(), pair
.second());
1043 connection
.commit();
1044 } catch (SQLException e
) {
1045 throw new RuntimeException("Failed update recipient store", e
);
1048 return pair
.first();
1051 private Pair
<RecipientId
, List
<RecipientId
>> resolveRecipientTrustedLocked(
1052 final Connection connection
, final RecipientAddress address
, final boolean isSelf
1053 ) throws SQLException
{
1054 if (address
.hasSingleIdentifier() || (
1055 !isSelf
&& selfAddressProvider
.getSelfAddress().matches(address
)
1057 return new Pair
<>(resolveRecipientLocked(connection
, address
), List
.of());
1059 final var pair
= MergeRecipientHelper
.resolveRecipientTrustedLocked(new HelperStore(connection
), address
);
1060 markRegistered(connection
, pair
.first());
1062 for (final var toBeMergedRecipientId
: pair
.second()) {
1063 mergeRecipientsLocked(connection
, pair
.first(), toBeMergedRecipientId
);
1069 private void mergeRecipients(
1070 final Connection connection
, final RecipientId recipientId
, final List
<RecipientId
> toBeMergedRecipientIds
1071 ) throws SQLException
{
1072 for (final var toBeMergedRecipientId
: toBeMergedRecipientIds
) {
1073 recipientMergeHandler
.mergeRecipients(connection
, recipientId
, toBeMergedRecipientId
);
1074 deleteRecipient(connection
, toBeMergedRecipientId
);
1075 synchronized (recipientsLock
) {
1076 recipientAddressCache
.entrySet().removeIf(e
-> e
.getValue().id().equals(toBeMergedRecipientId
));
1081 private RecipientId
resolveRecipientLocked(
1082 Connection connection
, RecipientAddress address
1083 ) throws SQLException
{
1084 final var byAci
= address
.aci().isEmpty()
1085 ? Optional
.<RecipientWithAddress
>empty()
1086 : findByServiceId(connection
, address
.aci().get());
1088 if (byAci
.isPresent()) {
1089 return byAci
.get().id();
1092 final var byPni
= address
.pni().isEmpty()
1093 ? Optional
.<RecipientWithAddress
>empty()
1094 : findByServiceId(connection
, address
.pni().get());
1096 if (byPni
.isPresent()) {
1097 return byPni
.get().id();
1100 final var byNumber
= address
.number().isEmpty()
1101 ? Optional
.<RecipientWithAddress
>empty()
1102 : findByNumber(connection
, address
.number().get());
1104 if (byNumber
.isPresent()) {
1105 return byNumber
.get().id();
1108 logger
.debug("Got new recipient, both serviceId and number are unknown");
1110 if (address
.serviceId().isEmpty()) {
1111 return addNewRecipient(connection
, address
);
1114 return addNewRecipient(connection
, new RecipientAddress(address
.serviceId().get()));
1117 private RecipientId
resolveRecipientLocked(Connection connection
, ServiceId serviceId
) throws SQLException
{
1118 final var recipient
= findByServiceId(connection
, serviceId
);
1120 if (recipient
.isEmpty()) {
1121 logger
.debug("Got new recipient, serviceId is unknown");
1122 return addNewRecipient(connection
, new RecipientAddress(serviceId
));
1125 return recipient
.get().id();
1128 private RecipientId
resolveRecipientLocked(Connection connection
, String number
) throws SQLException
{
1129 final var recipient
= findByNumber(connection
, number
);
1131 if (recipient
.isEmpty()) {
1132 logger
.debug("Got new recipient, number is unknown");
1133 return addNewRecipient(connection
, new RecipientAddress(number
));
1136 return recipient
.get().id();
1139 private RecipientId
addNewRecipient(
1140 final Connection connection
, final RecipientAddress address
1141 ) throws SQLException
{
1144 INSERT INTO %s (number, aci, pni, username)
1148 ).formatted(TABLE_RECIPIENT
);
1149 try (final var statement
= connection
.prepareStatement(sql
)) {
1150 statement
.setString(1, address
.number().orElse(null));
1151 statement
.setString(2, address
.aci().map(ACI
::toString
).orElse(null));
1152 statement
.setString(3, address
.pni().map(PNI
::toString
).orElse(null));
1153 statement
.setString(4, address
.username().orElse(null));
1154 final var generatedKey
= Utils
.executeQueryForOptional(statement
, Utils
::getIdMapper
);
1155 if (generatedKey
.isPresent()) {
1156 final var recipientId
= new RecipientId(generatedKey
.get(), this);
1157 logger
.debug("Added new recipient {} with address {}", recipientId
, address
);
1160 throw new RuntimeException("Failed to add new recipient to database");
1165 private void removeRecipientAddress(Connection connection
, RecipientId recipientId
) throws SQLException
{
1166 synchronized (recipientsLock
) {
1167 recipientAddressCache
.entrySet().removeIf(e
-> e
.getValue().id().equals(recipientId
));
1171 SET number = NULL, aci = NULL, pni = NULL, username = NULL, storage_id = NULL
1174 ).formatted(TABLE_RECIPIENT
);
1175 try (final var statement
= connection
.prepareStatement(sql
)) {
1176 statement
.setLong(1, recipientId
.id());
1177 statement
.executeUpdate();
1182 private void updateRecipientAddress(
1183 Connection connection
, RecipientId recipientId
, final RecipientAddress address
1184 ) throws SQLException
{
1185 synchronized (recipientsLock
) {
1186 recipientAddressCache
.entrySet().removeIf(e
-> e
.getValue().id().equals(recipientId
));
1190 SET number = ?, aci = ?, pni = ?, username = ?
1193 ).formatted(TABLE_RECIPIENT
);
1194 try (final var statement
= connection
.prepareStatement(sql
)) {
1195 statement
.setString(1, address
.number().orElse(null));
1196 statement
.setString(2, address
.aci().map(ACI
::toString
).orElse(null));
1197 statement
.setString(3, address
.pni().map(PNI
::toString
).orElse(null));
1198 statement
.setString(4, address
.username().orElse(null));
1199 statement
.setLong(5, recipientId
.id());
1200 statement
.executeUpdate();
1202 rotateStorageId(connection
, recipientId
);
1206 private void deleteRecipient(final Connection connection
, final RecipientId recipientId
) throws SQLException
{
1212 ).formatted(TABLE_RECIPIENT
);
1213 try (final var statement
= connection
.prepareStatement(sql
)) {
1214 statement
.setLong(1, recipientId
.id());
1215 statement
.executeUpdate();
1219 private void mergeRecipientsLocked(
1220 Connection connection
, RecipientId recipientId
, RecipientId toBeMergedRecipientId
1221 ) throws SQLException
{
1222 final var contact
= getContact(connection
, recipientId
);
1223 if (contact
== null) {
1224 final var toBeMergedContact
= getContact(connection
, toBeMergedRecipientId
);
1225 storeContact(connection
, recipientId
, toBeMergedContact
);
1228 final var profileKey
= getProfileKey(connection
, recipientId
);
1229 if (profileKey
== null) {
1230 final var toBeMergedProfileKey
= getProfileKey(connection
, toBeMergedRecipientId
);
1231 storeProfileKey(connection
, recipientId
, toBeMergedProfileKey
, false);
1234 final var profileKeyCredential
= getExpiringProfileKeyCredential(connection
, recipientId
);
1235 if (profileKeyCredential
== null) {
1236 final var toBeMergedProfileKeyCredential
= getExpiringProfileKeyCredential(connection
,
1237 toBeMergedRecipientId
);
1238 storeExpiringProfileKeyCredential(connection
, recipientId
, toBeMergedProfileKeyCredential
);
1241 final var profile
= getProfile(connection
, recipientId
);
1242 if (profile
== null) {
1243 final var toBeMergedProfile
= getProfile(connection
, toBeMergedRecipientId
);
1244 storeProfile(connection
, recipientId
, toBeMergedProfile
);
1247 recipientsMerged
.put(toBeMergedRecipientId
.id(), recipientId
.id());
1250 private Optional
<RecipientWithAddress
> findByNumber(
1251 final Connection connection
, final String number
1252 ) throws SQLException
{
1254 SELECT r._id, r.number, r.aci, r.pni, r.username
1258 """.formatted(TABLE_RECIPIENT
);
1259 try (final var statement
= connection
.prepareStatement(sql
)) {
1260 statement
.setString(1, number
);
1261 return Utils
.executeQueryForOptional(statement
, this::getRecipientWithAddressFromResultSet
);
1265 private Optional
<RecipientWithAddress
> findByUsername(
1266 final Connection connection
, final String username
1267 ) throws SQLException
{
1269 SELECT r._id, r.number, r.aci, r.pni, r.username
1271 WHERE r.username = ?
1273 """.formatted(TABLE_RECIPIENT
);
1274 try (final var statement
= connection
.prepareStatement(sql
)) {
1275 statement
.setString(1, username
);
1276 return Utils
.executeQueryForOptional(statement
, this::getRecipientWithAddressFromResultSet
);
1280 private Optional
<RecipientWithAddress
> findByServiceId(
1281 final Connection connection
, final ServiceId serviceId
1282 ) throws SQLException
{
1283 var recipientWithAddress
= Optional
.ofNullable(recipientAddressCache
.get(serviceId
));
1284 if (recipientWithAddress
.isPresent()) {
1285 return recipientWithAddress
;
1288 SELECT r._id, r.number, r.aci, r.pni, r.username
1292 """.formatted(TABLE_RECIPIENT
, serviceId
instanceof ACI ?
"r.aci" : "r.pni");
1293 try (final var statement
= connection
.prepareStatement(sql
)) {
1294 statement
.setString(1, serviceId
.toString());
1295 recipientWithAddress
= Utils
.executeQueryForOptional(statement
, this::getRecipientWithAddressFromResultSet
);
1296 recipientWithAddress
.ifPresent(r
-> recipientAddressCache
.put(serviceId
, r
));
1297 return recipientWithAddress
;
1301 private Set
<RecipientWithAddress
> findAllByAddress(
1302 final Connection connection
, final RecipientAddress address
1303 ) throws SQLException
{
1305 SELECT r._id, r.number, r.aci, r.pni, r.username
1311 """.formatted(TABLE_RECIPIENT
);
1312 try (final var statement
= connection
.prepareStatement(sql
)) {
1313 statement
.setString(1, address
.aci().map(ServiceId
::toString
).orElse(null));
1314 statement
.setString(2, address
.pni().map(ServiceId
::toString
).orElse(null));
1315 statement
.setString(3, address
.number().orElse(null));
1316 statement
.setString(4, address
.username().orElse(null));
1317 return Utils
.executeQueryForStream(statement
, this::getRecipientWithAddressFromResultSet
)
1318 .collect(Collectors
.toSet());
1322 private Contact
getContact(final Connection connection
, final RecipientId recipientId
) throws SQLException
{
1325 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
1327 WHERE r._id = ? AND (%s)
1329 ).formatted(TABLE_RECIPIENT
, SQL_IS_CONTACT
);
1330 try (final var statement
= connection
.prepareStatement(sql
)) {
1331 statement
.setLong(1, recipientId
.id());
1332 return Utils
.executeQueryForOptional(statement
, this::getContactFromResultSet
).orElse(null);
1336 private ProfileKey
getProfileKey(final Connection connection
, final RecipientId recipientId
) throws SQLException
{
1337 final var selfRecipientId
= resolveRecipientLocked(connection
, selfAddressProvider
.getSelfAddress());
1338 if (recipientId
.equals(selfRecipientId
)) {
1339 return selfProfileKeyProvider
.getSelfProfileKey();
1343 SELECT r.profile_key
1347 ).formatted(TABLE_RECIPIENT
);
1348 try (final var statement
= connection
.prepareStatement(sql
)) {
1349 statement
.setLong(1, recipientId
.id());
1350 return Utils
.executeQueryForOptional(statement
, this::getProfileKeyFromResultSet
).orElse(null);
1354 private ExpiringProfileKeyCredential
getExpiringProfileKeyCredential(
1355 final Connection connection
, final RecipientId recipientId
1356 ) throws SQLException
{
1359 SELECT r.profile_key_credential
1363 ).formatted(TABLE_RECIPIENT
);
1364 try (final var statement
= connection
.prepareStatement(sql
)) {
1365 statement
.setLong(1, recipientId
.id());
1366 return Utils
.executeQueryForOptional(statement
, this::getExpiringProfileKeyCredentialFromResultSet
)
1371 public Profile
getProfile(final Connection connection
, final RecipientId recipientId
) throws SQLException
{
1374 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
1376 WHERE r._id = ? AND r.profile_capabilities IS NOT NULL
1378 ).formatted(TABLE_RECIPIENT
);
1379 try (final var statement
= connection
.prepareStatement(sql
)) {
1380 statement
.setLong(1, recipientId
.id());
1381 return Utils
.executeQueryForOptional(statement
, this::getProfileFromResultSet
).orElse(null);
1385 private RecipientAddress
getRecipientAddressFromResultSet(ResultSet resultSet
) throws SQLException
{
1386 final var aci
= Optional
.ofNullable(resultSet
.getString("aci")).map(ACI
::parseOrThrow
);
1387 final var pni
= Optional
.ofNullable(resultSet
.getString("pni")).map(PNI
::parseOrThrow
);
1388 final var number
= Optional
.ofNullable(resultSet
.getString("number"));
1389 final var username
= Optional
.ofNullable(resultSet
.getString("username"));
1390 return new RecipientAddress(aci
, pni
, number
, username
);
1393 private RecipientId
getRecipientIdFromResultSet(ResultSet resultSet
) throws SQLException
{
1394 return new RecipientId(resultSet
.getLong("_id"), this);
1397 private RecipientWithAddress
getRecipientWithAddressFromResultSet(final ResultSet resultSet
) throws SQLException
{
1398 return new RecipientWithAddress(getRecipientIdFromResultSet(resultSet
),
1399 getRecipientAddressFromResultSet(resultSet
));
1402 private Recipient
getRecipientFromResultSet(final ResultSet resultSet
) throws SQLException
{
1403 return new Recipient(getRecipientIdFromResultSet(resultSet
),
1404 getRecipientAddressFromResultSet(resultSet
),
1405 getContactFromResultSet(resultSet
),
1406 getProfileKeyFromResultSet(resultSet
),
1407 getExpiringProfileKeyCredentialFromResultSet(resultSet
),
1408 getProfileFromResultSet(resultSet
),
1409 getStorageRecordFromResultSet(resultSet
));
1412 private Contact
getContactFromResultSet(ResultSet resultSet
) throws SQLException
{
1413 final var unregisteredTimestamp
= resultSet
.getLong("unregistered_timestamp");
1414 return new Contact(resultSet
.getString("given_name"),
1415 resultSet
.getString("family_name"),
1416 resultSet
.getString("nick_name"),
1417 resultSet
.getString("color"),
1418 resultSet
.getInt("expiration_time"),
1419 resultSet
.getLong("mute_until"),
1420 resultSet
.getBoolean("hide_story"),
1421 resultSet
.getBoolean("blocked"),
1422 resultSet
.getBoolean("archived"),
1423 resultSet
.getBoolean("profile_sharing"),
1424 resultSet
.getBoolean("hidden"),
1425 unregisteredTimestamp
== 0 ?
null : unregisteredTimestamp
);
1428 private Profile
getProfileFromResultSet(ResultSet resultSet
) throws SQLException
{
1429 final var profileCapabilities
= resultSet
.getString("profile_capabilities");
1430 final var profileUnidentifiedAccessMode
= resultSet
.getString("profile_unidentified_access_mode");
1431 return new Profile(resultSet
.getLong("profile_last_update_timestamp"),
1432 resultSet
.getString("profile_given_name"),
1433 resultSet
.getString("profile_family_name"),
1434 resultSet
.getString("profile_about"),
1435 resultSet
.getString("profile_about_emoji"),
1436 resultSet
.getString("profile_avatar_url_path"),
1437 resultSet
.getBytes("profile_mobile_coin_address"),
1438 profileUnidentifiedAccessMode
== null
1439 ? Profile
.UnidentifiedAccessMode
.UNKNOWN
1440 : Profile
.UnidentifiedAccessMode
.valueOfOrUnknown(profileUnidentifiedAccessMode
),
1441 profileCapabilities
== null
1443 : Arrays
.stream(profileCapabilities
.split(","))
1444 .map(Profile
.Capability
::valueOfOrNull
)
1445 .filter(Objects
::nonNull
)
1446 .collect(Collectors
.toSet()));
1449 private ProfileKey
getProfileKeyFromResultSet(ResultSet resultSet
) throws SQLException
{
1450 final var profileKey
= resultSet
.getBytes("profile_key");
1452 if (profileKey
== null) {
1456 return new ProfileKey(profileKey
);
1457 } catch (InvalidInputException ignored
) {
1462 private ExpiringProfileKeyCredential
getExpiringProfileKeyCredentialFromResultSet(ResultSet resultSet
) throws SQLException
{
1463 final var profileKeyCredential
= resultSet
.getBytes("profile_key_credential");
1465 if (profileKeyCredential
== null) {
1469 return new ExpiringProfileKeyCredential(profileKeyCredential
);
1470 } catch (Throwable ignored
) {
1475 private StorageId
getContactStorageIdFromResultSet(ResultSet resultSet
) throws SQLException
{
1476 final var storageId
= resultSet
.getBytes("storage_id");
1477 return StorageId
.forContact(storageId
);
1480 private byte[] getStorageRecordFromResultSet(ResultSet resultSet
) throws SQLException
{
1481 return resultSet
.getBytes("storage_record");
1484 public interface RecipientMergeHandler
{
1486 void mergeRecipients(
1487 final Connection connection
, RecipientId recipientId
, RecipientId toBeMergedRecipientId
1488 ) throws SQLException
;
1491 private class HelperStore
implements MergeRecipientHelper
.Store
{
1493 private final Connection connection
;
1495 public HelperStore(final Connection connection
) {
1496 this.connection
= connection
;
1500 public Set
<RecipientWithAddress
> findAllByAddress(final RecipientAddress address
) throws SQLException
{
1501 return RecipientStore
.this.findAllByAddress(connection
, address
);
1505 public RecipientId
addNewRecipient(final RecipientAddress address
) throws SQLException
{
1506 return RecipientStore
.this.addNewRecipient(connection
, address
);
1510 public void updateRecipientAddress(
1511 final RecipientId recipientId
, final RecipientAddress address
1512 ) throws SQLException
{
1513 RecipientStore
.this.updateRecipientAddress(connection
, recipientId
, address
);
1517 public void removeRecipientAddress(final RecipientId recipientId
) throws SQLException
{
1518 RecipientStore
.this.removeRecipientAddress(connection
, recipientId
);