/
UserRepository.java
514 lines (409 loc) · 17.1 KB
/
UserRepository.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
package io.muun.apollo.data.preferences;
import io.muun.apollo.data.preferences.adapter.JsonPreferenceAdapter;
import io.muun.apollo.data.preferences.rx.Preference;
import io.muun.apollo.data.serialization.SerializationUtils;
import io.muun.apollo.domain.model.ContactsPermissionState;
import io.muun.apollo.domain.model.CurrencyDisplayMode;
import io.muun.apollo.domain.model.User;
import io.muun.apollo.domain.model.UserPhoneNumber;
import io.muun.apollo.domain.model.UserProfile;
import io.muun.common.Optional;
import io.muun.common.model.PhoneNumber;
import io.muun.common.utils.Preconditions;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import androidx.annotation.NonNull;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import rx.Observable;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Singleton;
@Singleton
public class UserRepository extends BaseRepository {
private static final String KEY_USER = "user";
private static final String KEY_LAST_COPIED_ADDRESS = "key_last_copied_address";
private static final String PENDING_PROFILE_PICTURE_URI_KEY = "pending_profile_picture_uri_key";
private static final String PASSWORD_CHANGE_AUTHORIZED_UUID = "password_change_authorized_uuid";
private static final String CONTACTS_PERMISSION_STATE_KEY = "contacts_permission_state_key";
private static final String INITIAL_SYNC_COMPLETED_KEY = "initial_sync_completed_key";
private static final String RC_SETUP_IN_PROCESS = "rc_setup_in_process";
private static final String DISPLAY_SATS = "use_sats_as_currency";
private static final String PENDING_EMAIL_LINK = "pending_email_link";
private static final String EMAIL_SETUP_SKIPPED_KEY = "email_setup_skipped_key";
private static final String BALANCE_HIDDEN_KEY = "balance_hidden_key";
private final Preference<String> lastCopiedAddress;
private final Preference<String> pendingProfilePictureUriPreference;
private final Preference<String> passwordChangeAuthorizedUuidPreference;
private final Preference<ContactsPermissionState> conctactsPermissionStatePreference;
private final Preference<Boolean> initialSyncCompletedPreference;
private final Preference<Boolean> recoveryCodeSetupInProcessPreference;
private final Preference<CurrencyDisplayMode> displaySatsPreference;
private final Preference<StoredUserJson> userPreference;
private final Preference<String> pendingEmailLinkPreference;
// Only meaningful until 1st RecoveryMethod is setup. Afterward, user tracks its RecoveryMethods
private final Preference<Boolean> emailSetupSkippedPreference;
private final Preference<Boolean> balanceHiddenPreference;
/**
* Creates a user preference repository.
*/
@Inject
public UserRepository(Context context) {
super(context);
userPreference = rxSharedPreferences
.getObject(KEY_USER, new UserPreferenceDebugAdapter());
lastCopiedAddress = rxSharedPreferences.getString(KEY_LAST_COPIED_ADDRESS);
pendingProfilePictureUriPreference = rxSharedPreferences.getString(
PENDING_PROFILE_PICTURE_URI_KEY
);
passwordChangeAuthorizedUuidPreference = rxSharedPreferences.getString(
PASSWORD_CHANGE_AUTHORIZED_UUID
);
conctactsPermissionStatePreference = rxSharedPreferences.getEnum(
CONTACTS_PERMISSION_STATE_KEY,
ContactsPermissionState.DENIED,
ContactsPermissionState.class
);
initialSyncCompletedPreference = rxSharedPreferences.getBoolean(
INITIAL_SYNC_COMPLETED_KEY,
false
);
recoveryCodeSetupInProcessPreference = rxSharedPreferences.getBoolean(RC_SETUP_IN_PROCESS);
displaySatsPreference = rxSharedPreferences.getEnum(
DISPLAY_SATS,
CurrencyDisplayMode.BTC,
CurrencyDisplayMode.class
);
// Non-nullable default to assure non-nullability of values
pendingEmailLinkPreference = rxSharedPreferences.getString(PENDING_EMAIL_LINK, "default");
emailSetupSkippedPreference = rxSharedPreferences.getBoolean(
EMAIL_SETUP_SKIPPED_KEY,
false
);
balanceHiddenPreference = rxSharedPreferences.getBoolean(
BALANCE_HIDDEN_KEY,
false
);
}
@Override
protected String getFileName() {
return "user";
}
/**
* Stores the user.
*/
public synchronized void store(User user) {
userPreference.set(StoredUserJson.fromUser(user));
if (user.hasPassword) {
emailSetupSkippedPreference.set(false);
}
}
/**
* Fetches the user, throws NoSuchElementException if not present.
*/
public Observable<User> fetch() {
return fetchOptional().map(Optional::get);
}
/**
* Fetches the user, throws NPE if not present.
*/
public Observable<Optional<User>> fetchOptional() {
return userPreference.asObservable()
.map(storedUser -> {
if (storedUser != null) {
return Optional.of(storedUser.toUser());
} else {
return Optional.empty();
}
});
}
public Optional<User> fetchOneOptional() {
return fetchOptional().toBlocking().first();
}
/**
* Execute the migration that ends the multi-preference hell.
*/
public void migrateCthulhuToJsonPreference() {
final long hid = sharedPreferences.getLong("hid", -1L);
if (hid == -1L) {
return; // If no logged in user, then avoid setting any preferences.
}
final StoredUserJson value = new StoredUserJson(
hid,
sharedPreferences.getString("email", null),
sharedPreferences.getString("created_at", null),
sharedPreferences.getString("phone_number", null),
sharedPreferences.getBoolean("phone_number_verified", false),
sharedPreferences.getString("first_name", null),
sharedPreferences.getString("last_name", null),
sharedPreferences.getString("profile_picture_url", null),
sharedPreferences.getBoolean("email_verified_key", false),
sharedPreferences.getBoolean("has_recovery_code", false),
true, // all users had passwords before this feature
sharedPreferences.getBoolean("has_p2p_enabled", false),
false, // non-existent at migration time. This is a good default
null, // non-existent at migration time
sharedPreferences.getString("primary_currency_key", "USD")
);
userPreference.set(value);
}
public User fetchOne() {
return fetch().toBlocking().first();
}
/**
* Stores a user Profile.
*/
public synchronized void storeProfile(@Nullable UserProfile profile) {
final StoredUserJson value = Preconditions.checkNotNull(userPreference.get());
value.setProfileFrom(profile);
userPreference.set(value);
}
/**
* Stores a user PhoneNumber.
*/
public synchronized void storePhoneNumber(@Nullable UserPhoneNumber phoneNumber) {
final StoredUserJson value = Preconditions.checkNotNull(userPreference.get());
value.setPhoneNumberFrom(phoneNumber);
userPreference.set(value);
}
/**
* Returns the Uri of a profile picture that needs to be uploaded.
*/
@Nullable
public Uri getPendingProfilePictureUri() {
final String uriString = pendingProfilePictureUriPreference.get();
if (uriString == null) {
return null;
}
return Uri.parse(uriString);
}
/**
* Enqueues a profile picture to be uploaded in the future.
*/
public void setPendingProfilePictureUri(@Nullable Uri uri) {
if (uri == null) {
pendingProfilePictureUriPreference.delete();
return;
}
pendingProfilePictureUriPreference.set(uri.toString());
}
/**
* Note: no longer necessary a bitcoin address, can be a Ln invoice.
*/
@Nullable
public String getLastCopiedAddress() {
return lastCopiedAddress.get();
}
/**
* Note: no longer necessary a bitcoin address, can be a Ln invoice.
*/
public void setLastCopiedAddress(String address) {
lastCopiedAddress.set(address);
}
/**
* Store the fact that the user has verified their email.
*/
public void storeEmailVerified() {
final StoredUserJson value = Preconditions.checkNotNull(userPreference.get());
value.isEmailVerified = true;
userPreference.set(value);
}
/**
* Wait for the authorized email notification.
*/
public Observable<String> awaitForAuthorizedPasswordChange() {
return passwordChangeAuthorizedUuidPreference.asObservable()
.filter(uuid -> uuid != null && !uuid.isEmpty());
}
public void storePasswordChangeStatus(String uuid) {
passwordChangeAuthorizedUuidPreference.set(uuid);
}
public void storeContactsPermissionState(ContactsPermissionState state) {
conctactsPermissionStatePreference.set(state);
}
public ContactsPermissionState getContactsPermissionState() {
return conctactsPermissionStatePreference.get();
}
public Observable<ContactsPermissionState> watchContactsPermissionState() {
return conctactsPermissionStatePreference.asObservable();
}
public void storeInitialSyncCompleted() {
initialSyncCompletedPreference.set(true);
}
public boolean isInitialSyncCompleted() {
return initialSyncCompletedPreference.get();
}
public void setRecoveryCodeSetupInProcess(boolean isInProcess) {
recoveryCodeSetupInProcessPreference.set(isInProcess);
}
public CurrencyDisplayMode getCurrencyDisplayMode() {
return displaySatsPreference.get();
}
public Observable<CurrencyDisplayMode> watchCurrencyDisplayMode() {
return displaySatsPreference.asObservable();
}
public void setCurrencyDisplayMode(CurrencyDisplayMode value) {
displaySatsPreference.set(value);
}
public void setPendingEmailLink(String emailLink) {
pendingEmailLinkPreference.set(emailLink);
}
public String getPendingEmailLink() {
return pendingEmailLinkPreference.get();
}
public void setEmailSetupSkipped() {
emailSetupSkippedPreference.set(true);
}
public boolean getEmailSetupSkipped() {
return Preconditions.checkNotNull(emailSetupSkippedPreference.get());
}
public void setBalanceHidden(boolean hidden) {
balanceHiddenPreference.set(hidden);
}
public Observable<Boolean> watchBalanceHidden() {
return balanceHiddenPreference.asObservable();
}
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public static class StoredUserJson {
// WAIT
// WARNING
// CAREFUL
// READ THIS, I MEAN IT:
// We forgot to exclude this class from Proguard rules. This means that the order of
// declaration of this attributes is important -- until we remove this class from proguard
// and migrate the preference to a non-minified JSON this class is APPEND-ONLY.
public long hid;
public String email;
public String createdAt;
public String phoneNumber;
public boolean isPhoneNumberVerified;
public String firstName;
public String lastName;
public String profilePictureUrl;
public boolean isEmailVerified;
public boolean hasRecoveryCode;
public boolean hasPassword;
public boolean hasP2PEnabled;
public boolean hasExportedKeys;
public String currency;
public String emergencyKitLastExportedAt;
static StoredUserJson fromUser(User user) {
return new StoredUserJson(
user.hid,
user.email.orElse(null),
user.createdAt.map(SerializationUtils::serializeDate).orElse(null),
user.phoneNumber.map(PhoneNumber::toE164String).orElse(null),
user.phoneNumber.map(UserPhoneNumber::isVerified).orElse(false),
user.profile.map(UserProfile::getFirstName).orElse(null),
user.profile.map(UserProfile::getLastName).orElse(null),
user.profile.map(UserProfile::getPictureUrl).orElse(null),
user.isEmailVerified,
user.hasRecoveryCode,
user.hasPassword,
user.hasP2PEnabled,
user.hasExportedKeys,
user.emergencyKitLastExportedAt
.map(SerializationUtils::serializeDate)
.orElse(null),
SerializationUtils.serializeCurrencyUnit(user.unsafeGetPrimaryCurrency())
);
}
/**
* Json constructor.
*/
public StoredUserJson() {
}
/**
* Manual constructor.
*/
public StoredUserJson(long hid,
String email,
String createdAt,
String phoneNumber,
boolean isPhoneNumberVerified,
String firstName,
String lastName,
String profilePictureUrl,
boolean isEmailVerified,
boolean hasRecoveryCode,
boolean hasPassword,
boolean hasP2PEnabled,
boolean hasExportedKeys,
String emergencyKitLastExportedAt,
String currency) {
this.hid = hid;
this.email = email;
this.createdAt = createdAt;
this.phoneNumber = phoneNumber;
this.isPhoneNumberVerified = isPhoneNumberVerified;
this.firstName = firstName;
this.lastName = lastName;
this.profilePictureUrl = profilePictureUrl;
this.isEmailVerified = isEmailVerified;
this.hasRecoveryCode = hasRecoveryCode;
this.hasPassword = hasPassword;
this.hasP2PEnabled = hasP2PEnabled;
this.hasExportedKeys = hasExportedKeys;
this.emergencyKitLastExportedAt = emergencyKitLastExportedAt;
this.currency = currency;
}
User toUser() {
return new User(
hid,
Optional.ofNullable(email),
isEmailVerified,
phoneNumber != null
? Optional.of(new UserPhoneNumber(phoneNumber, isPhoneNumberVerified))
: Optional.empty(),
firstName != null
? Optional.of(new UserProfile(firstName, lastName, profilePictureUrl))
: Optional.empty(),
SerializationUtils.deserializeCurrencyUnit(currency != null ? currency : "USD"),
hasRecoveryCode,
hasPassword,
hasP2PEnabled,
hasExportedKeys,
Optional.ofNullable(emergencyKitLastExportedAt)
.map(SerializationUtils::deserializeDate),
Optional.ofNullable(createdAt).map(SerializationUtils::deserializeDate)
);
}
void setProfileFrom(@Nullable UserProfile newValue) {
if (newValue != null) {
firstName = newValue.getFirstName();
lastName = newValue.getLastName();
profilePictureUrl = newValue.getPictureUrl();
} else {
firstName = null;
lastName = null;
profilePictureUrl = null;
}
}
void setPhoneNumberFrom(@Nullable UserPhoneNumber newValue) {
if (newValue != null) {
phoneNumber = newValue.toE164String();
isPhoneNumberVerified = newValue.isVerified();
} else {
phoneNumber = null;
isPhoneNumberVerified = false;
}
}
}
private static class UserPreferenceDebugAdapter extends JsonPreferenceAdapter<StoredUserJson> {
public UserPreferenceDebugAdapter() {
super(StoredUserJson.class);
}
@Override
public StoredUserJson get(@NonNull String key, @NonNull SharedPreferences preferences) {
return super.get(key, preferences);
}
@Override
public void set(@NonNull String key,
@NonNull StoredUserJson value,
@NonNull SharedPreferences.Editor editor) {
super.set(key, value, editor);
}
}
}