Compare commits

...

246 Commits

Author SHA1 Message Date
ameba23
1eb6be2407 Only add Tor transport properties to our social backup 2021-06-29 16:40:05 +02:00
ameba23
53c4ba184d Improve logging for DuplexSyncConnection 2021-06-29 16:09:08 +02:00
ameba23
4b9c3a1a96 Call KeyManager#AddContact when restoring contacts 2021-06-29 11:43:14 +02:00
ameba23
eb66a13ded Implement message validator for handshake key exchange 2021-06-29 09:48:19 +02:00
ameba23
b860e73bdc Return an empty list when getting headers 2021-06-28 17:34:38 +02:00
ameba23
851bbb293e Rm logging 2021-06-28 17:20:17 +02:00
ameba23
36aaea40bd Register the client and hooks 2021-06-28 17:18:12 +02:00
ameba23
7563172121 Logging 2021-06-28 17:04:53 +02:00
ameba23
fad9257066 Set a contacts handshake public key on receiving one 2021-06-28 13:46:52 +02:00
ameba23
873b088a42 Add a method to set a contacts handshake public key in the database 2021-06-28 13:46:19 +02:00
ameba23
c7bca253fe Inject HandshakeKeyExchangeModule as an eager singleton 2021-06-28 09:58:39 +02:00
ameba23
47f136904c Create HandshakeKeyExchange client and module 2021-06-28 09:55:41 +02:00
ameba23
0a0b79ad9b Check for null when adding local properties to fix integration test 2021-06-25 21:07:44 +02:00
ameba23
e9f4f084dd Fix incorrect key for shared prefs 2021-06-25 13:36:03 +02:00
ameba23
3484892628 Use hex encoding for storing shards in shared preferences 2021-06-25 13:20:20 +02:00
ameba23
f67d2f0157 Include local tor properties in backup and check for remote handshake public keys 2021-06-25 13:03:45 +02:00
ameba23
ef05ecc342 Clear partially recovered shards from shared preferences when recovered 2021-06-25 09:03:58 +02:00
ameba23
3d807d9950 Save recovered shards in sharedPreferences 2021-06-25 08:44:37 +02:00
ameba23
4cf9ca9c3e Handle transport properties correctly in backup and recovery 2021-06-24 09:34:39 +02:00
ameba23
95d540644b Dont accept shards from mismatched sets - all muss match the first shard received 2021-06-22 16:26:48 +02:00
ameba23
3b4988c109 Change wording on shard notification messages 2021-06-22 09:49:33 +02:00
ameba23
9b7b583e8a Change message on success fragments 2021-06-21 16:28:10 +02:00
ameba23
21f3634050 Catch NoSuchGroupException when deleting contacts 2021-06-21 12:56:39 +02:00
ameba23
33549bcbe1 Implement deleteMessages in SocialBackupManagerImpl 2021-06-21 12:25:14 +02:00
ameba23
d975d1dbdd Implement deleteAllMessages in SocialBackupManagerImpl 2021-06-21 12:20:09 +02:00
ameba23
af64bb056d Add delete all messages to integration test 2021-06-21 12:19:32 +02:00
ameba23
ca54566ce0 SecretOwnerTask also passes a provider of AuthenticatedCipher 2021-06-16 08:34:40 +02:00
ameba23
85683a57f1 Use a provider to instantiate AuthenticatedCipher on each use, to prevent concurrency problems 2021-06-15 21:10:33 +02:00
ameba23
f524af893d Fix bug with qrCodeRead flag 2021-06-15 16:29:39 +02:00
ameba23
7b63471205 Fix bug with qrCodeRead flag 2021-06-15 16:29:06 +02:00
ameba23
4db1c4cc6b Improve strings for ui for displaying existing social backup 2021-05-18 12:06:09 +02:00
ameba23
71e63fb6f1 Tidy SocialBackupManagerImpl 2021-05-18 11:52:28 +02:00
ameba23
cae655b020 JavaDoc comments 2021-05-18 11:50:50 +02:00
ameba23
f601e2945b Improve error handling when creating backups, minor UI changes 2021-05-18 11:50:10 +02:00
ameba23
55e0ba8888 Rm logging 2021-05-05 10:34:32 +02:00
ameba23
3b4a20ce01 on retrying after fail, restart task 2021-05-04 15:10:41 +02:00
ameba23
e5eb82a5a8 Rm unused classes 2021-05-04 15:09:22 +02:00
ameba23
26a35b3212 Dont use onBackPressed when retrying after error 2021-04-27 13:07:45 +02:00
ameba23
68f135adad Additional logging in In/out DuplexSyncConnection 2021-04-27 13:06:55 +02:00
peg
7ecd952f49 Merge branch 'social-backup-restore-activity' into 'social-backup-poc'
Social backup restore activity

See merge request briar/briar!1444
2021-04-27 08:10:18 +00:00
ameba23
4b30b50329 Fix ReturnShardIntegrationTest 2021-04-27 10:05:43 +02:00
ameba23
c2b7657041 Improve UI for showing qr code 2021-04-26 13:03:42 +02:00
ameba23
61a052fc65 QR code display fragment 2021-04-26 12:43:37 +02:00
ameba23
d78a6604fd UI for error and explainer fragments 2021-04-26 12:29:45 +02:00
ameba23
8ffe9a6367 Modify drawables to show one device with a qr code and one without 2021-04-26 12:27:38 +02:00
ameba23
4b9c796c1a Implement handshake on IncomingDuplexSyncConnection 2021-04-26 09:59:19 +02:00
ameba23
6af739e584 Resolve conflict after merging with social-backup-outgoing-handshake 2021-04-25 12:06:49 +02:00
ameba23
50cb3997d9 Merge remote-tracking branch 'origin/social-backup-outgoing-handshake' into social-backup-restore-activity
* origin/social-backup-outgoing-handshake:
  WIP: Add handshake support for outgoing connections.
2021-04-25 12:01:18 +02:00
ameba23
a6f06e328b Dont use an observer when adding contacts 2021-04-25 12:00:44 +02:00
ameba23
a5f0516135 Tidy RestoreAccount 2021-04-23 13:22:10 +02:00
ameba23
3d34a36908 Show success fragment on recovering account 2021-04-23 13:18:47 +02:00
akwizgran
e29a5f487e WIP: Add handshake support for outgoing connections. 2021-04-23 12:17:56 +01:00
ameba23
acb9b18507 addContact method which also takes a handshakePublicKey 2021-04-23 12:23:13 +02:00
ameba23
f5455d320b bramble-core 2021-04-23 12:22:18 +02:00
ameba23
07141b688a Add a method to add recovered contacts to db 2021-04-22 17:42:33 +02:00
ameba23
b1c6c602a6 Add DozeView 2021-04-22 17:41:58 +02:00
ameba23
60c6c6a7ae RestoreAccount should be injected as singleton 2021-04-22 11:55:20 +02:00
ameba23
3ac7d71f8a Change to fail state if no backup found 2021-04-22 11:04:24 +02:00
ameba23
41c13f80f4 Copy code from SetPassword fragment to avoid it using the wrong view model 2021-04-22 10:56:20 +02:00
ameba23
2e03967519 Fix dependency problems after refactor 2021-04-22 09:01:44 +02:00
ameba23
4b77a9ab60 Use backup with highest version number 2021-04-21 21:53:06 +02:00
ameba23
327cbe23ee Use DozeHelper 2021-04-21 21:52:48 +02:00
ameba23
34f15b6bdc ContactData and SocialBackup now live in briar-api 2021-04-21 16:35:27 +02:00
ameba23
5c22d233ef Restore account activity/view model 2021-04-21 16:34:56 +02:00
ameba23
afc0bc3f3c Refactor and create a RestoreAccount class which does the combining 2021-04-21 16:34:28 +02:00
ameba23
2a365d986f Restore account method for account manager 2021-04-21 15:36:44 +02:00
ameba23
741c9b63d9 Custodian closes tcp socket following error 2021-04-21 15:19:36 +02:00
ameba23
5420204703 Rm fixed port constant 2021-04-21 09:56:36 +02:00
ameba23
e827b8a190 Tidy 2021-04-21 09:55:09 +02:00
ameba23
c6046a1c38 Fix bug with re-starting listening on a tcp socket 2021-04-21 09:54:42 +02:00
peg
b401232736 Merge branch 'social-backup-shard-return' into 'social-backup-poc'
Social backup shard return

See merge request briar/briar!1433
2021-04-20 10:52:25 +00:00
ameba23
46fc510ce2 Improve UI for account recovery 2021-04-20 12:47:14 +02:00
ameba23
b835064b5e Logging and improvements to BackupPayloadDecoderImpl 2021-04-20 12:46:22 +02:00
ameba23
ae35354e82 Encode nonce in backup payload 2021-04-19 11:37:46 +02:00
ameba23
bdbc377c8f Fix UI around receiving multiple returned shards 2021-04-19 10:07:06 +02:00
ameba23
ad3c9e101c Implement BackupPayloadDecoder 2021-04-19 09:00:05 +02:00
ameba23
101b93b3da Interface for BackupPayloadDecoder 2021-04-19 08:59:37 +02:00
ameba23
e392a0dd8b Custodian should instantiate socket at the point of connecting, secret owner parse payload 2021-04-16 21:17:10 +02:00
ameba23
00de32aa87 add encoder to ReturnShardPayload 2021-04-16 21:15:29 +02:00
ameba23
3ff6042d10 Recovery UI 2021-04-16 21:14:34 +02:00
ameba23
b3adfe19a4 Allow ReturnShardPayload instances to be compared for equality 2021-04-16 12:01:39 +02:00
ameba23
708262c512 Refactor and add real shard payload to return shard activity and view model 2021-04-16 12:00:40 +02:00
ameba23
f4d667f50a give and retrieve shard payload 2021-04-15 21:25:13 +02:00
ameba23
79369f4e7a Failure reasons 2021-04-15 21:24:22 +02:00
ameba23
fec74ed343 tasks take and produce shard payload, improve integration test 2021-04-15 21:24:01 +02:00
ameba23
4ba3fdb1e3 Always cancel the task before starting it 2021-04-15 11:47:48 +02:00
ameba23
20df10d7a8 When cancelling, assume nothing is instantiated 2021-04-15 11:40:07 +02:00
Sebastian Kürten
b901974488 Start work on an integration test 2021-04-15 10:56:08 +02:00
ameba23
badc2c5d9b Fix bug with localKeypair being generated twice 2021-04-15 09:00:13 +02:00
ameba23
ed1ed7d3e1 Refactor duplicate task code into parent class 2021-04-14 17:59:29 +02:00
ameba23
e6d80ec484 Improve UI for Secret owner shard return 2021-04-14 17:22:59 +02:00
ameba23
536905c260 Encrypted shard return handshake 2021-04-14 17:22:34 +02:00
ameba23
9b4f5be6fe Basic encryption on the custodian side 2021-04-13 21:20:51 +02:00
ameba23
f13cc15661 Enter success state after sending ack 2021-04-13 18:22:19 +02:00
ameba23
b07206c898 Improve UI for shard return 2021-04-13 18:21:55 +02:00
ameba23
d2abd6dcc2 Basic handshake implementation 2021-04-13 17:38:03 +02:00
ameba23
6a143eea8a Update state in UI for Custodian 2021-04-13 17:37:29 +02:00
ameba23
4da20a2412 add timeout to client 2021-04-13 12:29:33 +02:00
ameba23
1bf9f57ad9 secret owner listens, and custodian connects 2021-04-13 12:20:17 +02:00
ameba23
cd1ac43b7d get the actual ip address on local wifi and add it to qr code 2021-04-13 11:56:52 +02:00
ameba23
df37a39cb4 Qr code payload contains socket address and public key 2021-04-13 11:13:28 +02:00
ameba23
f7e40657ee Temporary - allow us to jump to the custodian return shard activity directly from the settings menu, even if we dont hold any shards 2021-04-13 09:20:37 +02:00
ameba23
d6608fd8cb add a CustodianReturnShardModule which provides the view model 2021-04-13 09:19:42 +02:00
ameba23
dba4cc278c dummy ip address for local socket 2021-04-13 08:53:27 +02:00
ameba23
01bcc6d491 ensure that qr code is ready when start button is pressed 2021-04-13 08:52:42 +02:00
ameba23
e106166cfe provide SecretOwnerTask 2021-04-12 16:18:23 +02:00
ameba23
5fd0d0d2d3 OwnerReturnShard activity and view model now running 2021-04-12 16:17:22 +02:00
ameba23
e006e22616 rename ReturnShardModule, it is now only used by secret owner 2021-04-12 16:15:52 +02:00
ameba23
c0827eda77 use the new OwnerReturnShardActivity 2021-04-12 15:57:15 +02:00
ameba23
b55ae1ce18 Changes to implementation for SecertOwnerTask 2021-04-12 15:03:50 +02:00
ameba23
d925f3be0b Secret owner return shard - activity, view model and fragment - qr code generation 2021-04-12 15:03:15 +02:00
ameba23
71c327112c Implement SecretOwnerTask 2021-04-12 15:02:26 +02:00
ameba23
30b2905c2e make SecretOwnerTask states public 2021-04-12 12:21:35 +02:00
ameba23
9d01de9868 Secret owner return shard - activity, view model and fragment 2021-04-12 12:21:16 +02:00
ameba23
71b8c32a3e implement CustodianTask 2021-04-12 10:52:03 +02:00
ameba23
207a8bc7cb make CustodianTask states public 2021-04-12 10:51:34 +02:00
ameba23
9e4ace4ce7 Activity and view model for custodian returning shard 2021-04-12 10:50:47 +02:00
ameba23
e856ee48f9 Merge branch 'social-backup-recovery-task-interfaces' into social-backup-shard-return
* social-backup-recovery-task-interfaces:
  Add interfaces for social backup recovery tasks.
2021-04-09 15:59:03 +02:00
ameba23
ea4bd5f438 WIP activity for custodian to return a shard 2021-04-09 15:58:50 +02:00
akwizgran
5b7bc54e16 Add interfaces for social backup recovery tasks. 2021-04-09 14:46:45 +01:00
ameba23
996eb20556 Additional logging in KeyAgreementConnector 2021-04-09 15:12:56 +02:00
ameba23
61453b96ab Make a ReturnShardFragment, based on ContactExchangeFragment 2021-04-08 16:43:39 +02:00
ameba23
73ce6c2fb0 Fix parser for backup messages 2021-04-08 15:46:56 +02:00
ameba23
3ddda8cf7f Revert package name to socialbackup 2021-04-08 13:11:51 +02:00
ameba23
93ee8df43a Resolve merge conflict with 1872-key-agreement 2021-04-08 12:23:18 +02:00
ameba23
d0b939dafb add provider for ClientHelper 2021-04-07 15:51:04 +02:00
ameba23
4f26230996 implement method to get a ReturnShardPayload as bytes to avoid needing the messageEncoder 2021-04-06 16:28:09 +02:00
ameba23
e804a8d573 method to get a ReturnShardPayload as bytes to avoid needing the messageEncoder 2021-04-06 16:27:51 +02:00
ameba23
6bff0647d6 return shard activity dependencies 2021-04-06 16:26:57 +02:00
ameba23
3688b0b17a Encoding and decoding for returned social backups 2021-03-31 16:01:22 +02:00
ameba23
4f42ce9a01 Public interface of SocialBackupExchangeManager and Message encoder/parser 2021-03-31 16:00:57 +02:00
ameba23
c155020064 CustodianHelpRecoverActivity passes a ReturnShardPayload 2021-03-31 16:00:04 +02:00
ameba23
933397f58b move MessageParser and MessageEncoder to make public 2021-03-31 15:59:24 +02:00
ameba23
d129186bab social backup exchange 2021-03-30 12:06:45 +02:00
ameba23
a11a81f3d4 backup payload and returned shard payload 2021-03-30 12:05:57 +02:00
ameba23
7c6a2a9b46 Refactor from public contact exchange code 2021-03-30 12:05:18 +02:00
ameba23
0258cf9c59 Rename constants to make public 2021-03-30 12:01:55 +02:00
ameba23
caee34f738 Rename constants to make public 2021-03-30 12:01:10 +02:00
ameba23
7afe5a85f8 create a socialBackupExchangeManager copying the ContactExchangeManager 2021-03-26 11:59:52 +01:00
ameba23
943e734ae9 fix bugs relating to return shard activity 2021-03-26 11:00:44 +01:00
ameba23
c2cbba451d return shard activity and view model 2021-03-25 20:43:34 +01:00
ameba23
fc909a317e make add nearby contact stuff public 2021-03-25 20:42:43 +01:00
ameba23
a0df8ded69 recover package and return shard activity 2021-03-25 20:41:34 +01:00
ameba23
9d23c876ae merge with 1872-key-agreement 2021-03-25 14:55:15 +01:00
ameba23
265d1da566 improve threshold choosing UI 2021-03-23 09:14:18 +01:00
ameba23
b6d57a492b only allow choosing a threshold with > 3 custodians 2021-03-23 08:25:09 +01:00
ameba23
943f107232 Merge branch 'social-backup-poc' of https://code.briarproject.org/briar/briar into social-backup-poc
* 'social-backup-poc' of https://code.briarproject.org/briar/briar:
  Inject social backup eager singletons when Briar core is created.
2021-03-22 17:42:22 +01:00
peg
09e024ea5e Merge branch 'social-backup-eager-singletons' into 'social-backup-poc'
Dark Crystal: Inject social backup eager singletons when Briar core is created

See merge request briar/briar!1414
2021-03-22 16:37:20 +00:00
ameba23
2486a60fea only display custodian help recover explainer screen if you are a custodian 2021-03-22 17:03:22 +01:00
ameba23
365fa58928 add amCustodian method which determines whether you are a custodian for a given contact 2021-03-22 17:02:39 +01:00
akwizgran
45d2e2ce06 Inject social backup eager singletons when Briar core is created. 2021-03-22 15:19:41 +00:00
ameba23
b1f5d71a4e add read flag to shard message header 2021-03-22 16:13:08 +01:00
ameba23
d47c18b392 ShardReceivedEvent in briar api 2021-03-22 09:22:32 +01:00
ameba23
8ed58eaada broadcast a ShardReceivedEvent on getting a shard 2021-03-22 09:22:04 +01:00
ameba23
8478097a3c test setting read flag for shard messages 2021-03-22 08:42:25 +01:00
ameba23
0440c5c7c8 update the message tracker on incoming/outgoing shard messages 2021-03-18 14:55:30 +01:00
ameba23
58db654a9b pass MessageStatus information to shard message headers (sent and seen) 2021-03-18 12:00:19 +01:00
Sebastian Kürten
c3d137a73c Move ShardsSentDismissedListener into ShardsSentFragment 2021-03-18 10:21:00 +01:00
Sebastian Kürten
db7825d7f6 Try making message tracker assertions 2021-03-18 10:13:22 +01:00
Sebastian Kürten
24059adbd6 Start working on integration test 2021-03-18 09:51:29 +01:00
ameba23
7d128988a7 listener for custodian scan qr code button 2021-03-17 14:51:11 +01:00
ameba23
9499a078a6 front end fragments for recovery 2021-03-17 14:41:29 +01:00
ameba23
6483b0ed87 display explainer screen when choosing recover account 2021-03-17 10:46:34 +01:00
ameba23
af097dc859 add timestamp to shard message metadata 2021-03-17 09:23:31 +01:00
ameba23
3adc6d002c add isLocal boolean to shard message headers 2021-03-17 09:17:36 +01:00
ameba23
0658e90c65 implement slightly more of conversation client to get delete messages test passing 2021-03-17 08:41:39 +01:00
ameba23
6d0aebd7ec SocialBackupManager implements a ConverationClient for shard message headers 2021-03-16 17:28:00 +01:00
ameba23
0faccfe5a3 SocialBackupManager interface has a getMessageHeaders method 2021-03-16 17:27:00 +01:00
ameba23
c19c40bdc8 when providing SocialBackupManager, register the conversation client 2021-03-16 17:23:47 +01:00
ameba23
363da96709 recover activity 2021-03-16 11:51:03 +01:00
ameba23
e9c2cb2cc5 fix merge conflict 2021-03-16 10:52:11 +01:00
ameba23
505124a22f add the contact group and local group if it doesnt already exist 2021-03-16 09:40:18 +01:00
Sebastian Kürten
9b750291d1 Remove proguard rule that we do not need after all 2021-03-15 18:29:59 +01:00
Sebastian Kürten
9c829ec7c9 Don't let proguard strip important JNA class members 2021-03-15 18:27:05 +01:00
ameba23
1b9ba41110 return false on error when checking if local backup already exists 2021-03-15 15:06:06 +01:00
peg
fa39e7c824 Merge branch 'social-backup-poc-separate-namespace' into 'social-backup-poc'
Use different applicationId/app package

See merge request briar/briar!1410
2021-03-15 09:51:32 +00:00
ameba23
37fb3bd79f return false on error when checking if local backup already exists 2021-03-15 09:57:36 +01:00
ameba23
1c5e89b100 handle error when checking for existing backup 2021-03-15 09:40:51 +01:00
Sebastian Kürten
6dc6a34d29 Use different applicationId/app package 2021-03-12 12:03:45 +01:00
Sebastian Kürten
35b2b8c9d2 Add DefaultSocialBackupModule to test components 2021-03-12 12:01:18 +01:00
ameba23
e3ff8a80e5 change SocialBackupModule to DefaultSocialBackupModule 2021-03-12 10:52:26 +01:00
ameba23
e09fedd79f add AndroidSocialBackupModule to AppModule 2021-03-12 10:51:00 +01:00
ameba23
6c3df2a3d4 add AndroidSocialBackupModule 2021-03-11 11:10:38 +01:00
Sebastian Kürten
a9edf43df2 Add ShardMessageHeader 2021-03-11 09:52:39 +01:00
ameba23
d91d2e0070 listener for setup new account button 2021-03-10 10:17:55 +01:00
ameba23
58f803a48a add new or recover screen - displays fragment with buttons 2021-03-10 09:08:34 +01:00
ameba23
ac9c71f7eb add new or recover screen WIP 2021-03-09 16:09:26 +01:00
ameba23
b3292f86ab improve ExistingBackupFragment 2021-03-09 12:36:02 +01:00
ameba23
28d2697e38 add custodian names to Existing backup fragment 2021-03-09 11:47:11 +01:00
ameba23
8e4b309a12 Existing backup fragment 2021-03-09 11:33:33 +01:00
ameba23
8a1333e8f2 display a different fragment when a backup already exists 2021-03-09 09:47:48 +01:00
ameba23
bd2a671f9f rm unused drawables 2021-03-09 08:49:40 +01:00
peg
845be86113 Merge branch 'incorporate-mockup-fragments' into 'social-backup-poc'
Incorporate mockup fragments

See merge request briar/briar!1395
2021-03-08 17:07:07 +00:00
ameba23
25bbb5aa36 dependency injection for SocialBackupManager and DatabaseComponent 2021-03-08 18:00:24 +01:00
ameba23
57605d55ce WIP db transaction for DistributedBackupActivity 2021-03-08 17:08:19 +01:00
ameba23
6c079e172a provide default constructor for DistributedBackupActivity 2021-03-08 16:40:24 +01:00
ameba23
a101229f73 add help recover account to conversation action menu 2021-03-08 16:27:30 +01:00
ameba23
3f7f53774b inject SocialBackupManager 2021-03-08 16:26:16 +01:00
ameba23
9beb4d7b81 improve thresholdSelectorFragment 2021-03-08 13:45:02 +01:00
ameba23
378112c00c add comments 2021-03-08 13:13:00 +01:00
ameba23
451a3238be rm comments 2021-03-08 12:57:25 +01:00
ameba23
bf6dd0d924 pass treshold to DistributedBackupActivity 2021-03-08 12:43:04 +01:00
ameba23
085e25cc14 improve thresholdSelectorFragment 2021-03-08 12:31:32 +01:00
ameba23
033c9f4d59 get argument with number of custodians to thresholdselectorfragment 2021-03-08 11:58:05 +01:00
ameba23
5f7bc4a143 dont throw on no group id 2021-03-05 17:17:50 +01:00
ameba23
4972c554dc fix pathname in settings.xml 2021-03-05 12:30:15 +01:00
ameba23
44e33e3d1a add DistributedBackupActivity for AndroidManifest 2021-03-05 11:34:30 +01:00
ameba23
5212bb7a01 add settings menu item 2021-03-05 10:28:53 +01:00
ameba23
83aad185cd add missing string 2021-03-05 10:28:33 +01:00
ameba23
c318dcfb5f rm CustodianDisplayFragment 2021-03-05 10:27:58 +01:00
ameba23
10610930c0 dont inject activist CustodianDisplayFragment 2021-03-05 09:22:36 +01:00
ameba23
2af236b733 add more strings from the mock-ups 2021-03-05 09:03:56 +01:00
ameba23
d46a513208 add remaining strings from the mock-ups 2021-03-05 08:46:38 +01:00
ameba23
022357fb4c rm strings_mockups.xml 2021-03-04 14:26:47 +01:00
ameba23
a576d7abf8 bump secretsharingwrapper to 1.1.0 2021-03-04 14:25:28 +01:00
ameba23
008877a9da bump secretsharingwrapper to 1.1.0 2021-03-04 10:37:20 +01:00
ameba23
01bc94c241 Merge branch 'social-backup-poc' into incorporate-mockup-fragments
* social-backup-poc:
  move DarkCrystal interface to briar-api - import it
  move DarkCrystal interface to briar-api
  make SocialBackupConstants public
  make DarkCrystal interface public
  DarkCrystal implementation which calls SecretSharingWrapper
  updated witness.gradle files
  rm SecretShardingWrapper as dependency of briar-core
  add SecretShardingWrapper as dependency of briar-android
  implement DarkCrystal in briar-android
  add updated witness.gradle
  add secret-sharing-wrapper to build.gradle (WIP)
2021-03-04 09:32:28 +01:00
ameba23
03c1f9c99a fix problems so that the mockup fragments build 2021-03-04 09:32:12 +01:00
ameba23
0b9e4915dc set initial state of threshold representation 2021-03-04 08:52:52 +01:00
ameba23
55e5600214 add some of the strings from the mockups 2021-03-04 08:39:37 +01:00
ameba23
4c357fe87a change threshold svg for placeholder string 2021-03-04 08:38:36 +01:00
ameba23
6a7ceb4a68 use a string as threshold representation rather than svg 2021-03-04 08:38:02 +01:00
ameba23
d917e9d642 move DarkCrystal interface to briar-api - import it 2021-03-02 12:50:43 +01:00
ameba23
c7f6270b2a move DarkCrystal interface to briar-api 2021-03-02 12:48:49 +01:00
ameba23
681b151c8b attempt to incorporate fragments (WIP) 2021-03-02 09:47:13 +01:00
ameba23
b86b0f5fbc make SocialBackupConstants public 2021-03-02 08:52:43 +01:00
ameba23
dc138c713f make DarkCrystal interface public 2021-03-02 08:52:16 +01:00
ameba23
7da49ae6df DarkCrystal implementation which calls SecretSharingWrapper 2021-03-02 08:51:00 +01:00
ameba23
3c61f499d9 updated witness.gradle files 2021-03-02 08:49:57 +01:00
ameba23
fbe839d9ca rm SecretShardingWrapper as dependency of briar-core 2021-03-02 08:49:09 +01:00
ameba23
f2638c9db2 add SecretShardingWrapper as dependency of briar-android 2021-03-02 08:48:38 +01:00
ameba23
808166931e implement DarkCrystal in briar-android 2021-03-02 08:47:59 +01:00
ameba23
77d0c16530 add updated witness.gradle 2021-02-26 11:15:50 +01:00
ameba23
c991cfb926 add secret-sharing-wrapper to build.gradle (WIP) 2021-02-26 10:57:27 +01:00
ameba23
dcda13db64 add fragments (WIP) 2021-02-26 10:45:29 +01:00
ameba23
ff4640b789 update SocialBackupValidator 2021-02-25 11:30:46 +01:00
ameba23
a2426e3b2a rm number of shards and threshold from shard messages from message parserimpl 2021-02-24 16:00:02 +01:00
ameba23
0bc4bf232f Merge branch 'social-backup-poc' of https://code.briarproject.org/briar/briar into social-backup-poc
* 'social-backup-poc' of https://code.briarproject.org/briar/briar:
  add combine shards stub
2021-02-24 15:44:39 +01:00
ameba23
2ed44aa2a8 rm number of shards and threshold from shard messages 2021-02-24 15:44:24 +01:00
ameba23
8496ab0a6a rm number of shards and threshold from shard messages in message encoder 2021-02-24 15:43:50 +01:00
ameba23
b57d811b4a rm number of shards and threshold from shard messages in stub 2021-02-24 15:43:27 +01:00
akwizgran
4077e28999 Merge branch 'combine-shards-stub' into 'social-backup-poc'
add combine shards stub

See merge request briar/briar!1379
2021-02-24 14:19:19 +00:00
ameba23
292fb6d3b1 add combine shards stub 2021-02-24 12:39:51 +01:00
akwizgran
4ead7cd4a1 WIP: Update our backup when contacts are added or removed. 2021-02-23 17:22:56 +00:00
akwizgran
513e696238 Initial implementation of social backup client. 2021-02-23 15:48:19 +00:00
akwizgran
f160efb0e7 Use BriarCoreModule for integration tests. 2021-02-23 15:03:28 +00:00
193 changed files with 8669 additions and 121 deletions

View File

@@ -31,15 +31,6 @@
<option name="PACKAGES_TO_USE_STAR_IMPORTS">
<value />
</option>
<option name="PACKAGES_IMPORT_LAYOUT">
<value>
<package name="" alias="false" withSubpackages="true" />
<package name="java" alias="false" withSubpackages="true" />
<package name="javax" alias="false" withSubpackages="true" />
<package name="kotlin" alias="false" withSubpackages="true" />
<package name="" alias="true" withSubpackages="true" />
</value>
</option>
<option name="NAME_COUNT_TO_USE_STAR_IMPORT" value="2147483647" />
<option name="NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS" value="2147483647" />
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />

View File

@@ -2,6 +2,7 @@ package org.briarproject.bramble.api.account;
import org.briarproject.bramble.api.crypto.DecryptionException;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.identity.Identity;
import org.briarproject.bramble.api.identity.IdentityManager;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
@@ -43,6 +44,17 @@ public interface AccountManager {
*/
boolean createAccount(String name, String password);
/**
* Restores a given identity by registering it with the
* {@link IdentityManager}. Creates a database key, encrypts it with the
* given password and stores it on disk. {@link #accountExists()} will
* return true after this method returns true.
* @param identity
* @param password
* @return
*/
boolean restoreAccount(Identity identity, String password);
/**
* Deletes all account state from disk. {@link #accountExists()} will
* return false after this method returns.

View File

@@ -1,6 +1,6 @@
package org.briarproject.bramble.contact;
package org.briarproject.bramble.api.contact;
interface ContactExchangeConstants {
public interface ContactExchangeConstants {
/**
* The current version of the contact exchange protocol.

View File

@@ -1,4 +1,4 @@
package org.briarproject.bramble.contact;
package org.briarproject.bramble.api.contact;
import org.briarproject.bramble.api.crypto.PrivateKey;
import org.briarproject.bramble.api.crypto.PublicKey;
@@ -6,7 +6,7 @@ import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
@NotNullByDefault
interface ContactExchangeCrypto {
public interface ContactExchangeCrypto {
/**
* Derives the header key for a contact exchange stream from the master key.

View File

@@ -0,0 +1,9 @@
package org.briarproject.bramble.api.contact;
/**
* Record types for the contact exchange protocol.
*/
public interface ContactExchangeRecordTypes {
byte CONTACT_INFO = 0;
}

View File

@@ -3,6 +3,7 @@ package org.briarproject.bramble.api.contact;
import org.briarproject.bramble.api.FormatException;
import org.briarproject.bramble.api.Pair;
import org.briarproject.bramble.api.UnsupportedVersionException;
import org.briarproject.bramble.api.crypto.PublicKey;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.db.ContactExistsException;
import org.briarproject.bramble.api.db.DbException;
@@ -48,6 +49,10 @@ public interface ContactManager {
SecretKey rootKey, long timestamp, boolean alice, boolean verified,
boolean active) throws DbException;
ContactId addContact(Transaction txn, Author remote, AuthorId local,
PublicKey handshake, boolean verified)
throws DbException, GeneralSecurityException;
/**
* Stores a contact associated with the given local and remote pseudonyms,
* replacing the given pending contact, derives and stores handshake mode
@@ -205,6 +210,18 @@ public interface ContactManager {
void setContactAlias(ContactId c, @Nullable String alias)
throws DbException;
/**
* Sets the contact's handshake public key
*/
void setHandshakePublicKey(Transaction txn, ContactId c,
PublicKey handshakePublicKey) throws DbException;
/**
* Sets the contact's handshake public key
*/
void setHandshakePublicKey(ContactId c, PublicKey handshakePublicKey)
throws DbException;
/**
* Returns true if a contact with this {@code remoteAuthorId} belongs to
* the local pseudonym with this {@code localAuthorId}.

View File

@@ -24,6 +24,19 @@ public interface HandshakeManager {
HandshakeResult handshake(PendingContactId p, InputStream in,
StreamWriter out) throws DbException, IOException;
/**
* Handshakes with the given contact. Returns an ephemeral master key
* authenticated with both parties' handshake key pairs and a flag
* indicating whether the local peer is Alice or Bob.
*
* @param in An incoming stream for the handshake, which must be secured in
* handshake mode
* @param out An outgoing stream for the handshake, which must be secured
* in handshake mode
*/
HandshakeResult handshake(ContactId c, InputStream in, StreamWriter out)
throws DbException, IOException;
class HandshakeResult {
private final SecretKey masterKey;

View File

@@ -1,12 +1,11 @@
package org.briarproject.bramble.crypto;
package org.briarproject.bramble.api.crypto;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import java.security.GeneralSecurityException;
@NotNullByDefault
interface AuthenticatedCipher {
public interface AuthenticatedCipher {
/**
* Initializes this cipher for encryption or decryption with a key and an

View File

@@ -546,6 +546,11 @@ public interface DatabaseComponent extends TransactionManager {
void setContactAlias(Transaction txn, ContactId c, @Nullable String alias)
throws DbException;
/**
* Sets the remote handshake public key for a given contact
*/
void setHandshakePublicKey(Transaction txn, ContactId c, PublicKey handshakePublicKey) throws DbException;
/**
* Sets the given group's visibility to the given contact.
*/

View File

@@ -26,6 +26,11 @@ public interface IdentityManager {
*/
void registerIdentity(Identity i);
/**
* Returns the cached local identity or loads it from the database.
*/
Identity getIdentity(Transaction txn) throws DbException;
/**
* Returns the cached local identity or loads it from the database.
*/

View File

@@ -74,6 +74,13 @@ public interface TransportPropertyManager {
TransportProperties getRemoteProperties(ContactId c, TransportId t)
throws DbException;
/**
* Returns the remote transport properties for the given contact and
* transport.
*/
TransportProperties getRemoteProperties(Transaction txn, ContactId c,
TransportId t) throws DbException;
/**
* Merges the given properties with the existing local properties for the
* given transport.

View File

@@ -35,6 +35,20 @@ public interface KeyManager {
ContactId c, SecretKey rootKey, long timestamp, boolean alice,
boolean active) throws DbException;
/**
* Derives and stores a set of rotation mode transport keys for
* communicating with the given contact over each transport and returns the
* key set IDs.
* <p/>
* {@link StreamContext StreamContexts} for the contact can be created
* after this method has returned.
*
* @param alice True if the local party is Alice
* @param active Whether the derived keys can be used for outgoing streams
*/
Map<TransportId, KeySetId> addRotationKeys(ContactId c, SecretKey rootKey,
long timestamp, boolean alice, boolean active) throws DbException;
/**
* Informs the key manager that a new contact has been added. Derives and
* stores a set of handshake mode transport keys for communicating with the

View File

@@ -176,6 +176,18 @@ class AccountManagerImpl implements AccountManager {
}
}
public boolean restoreAccount(Identity identity, String password) {
synchronized (stateChangeLock) {
if (hasDatabaseKey())
throw new AssertionError("Already have a database key");
identityManager.registerIdentity(identity);
SecretKey key = crypto.generateSecretKey();
if (!encryptAndStoreDatabaseKey(key, password)) return false;
databaseKey = key;
return true;
}
}
@GuardedBy("stateChangeLock")
private boolean encryptAndStoreDatabaseKey(SecretKey key, String password) {
byte[] plaintext = key.getBytes();

View File

@@ -76,7 +76,7 @@ class ConnectionManagerImpl implements ConnectionManager {
ioExecutor.execute(new IncomingDuplexSyncConnection(keyManager,
connectionRegistry, streamReaderFactory, streamWriterFactory,
syncSessionFactory, transportPropertyManager, ioExecutor,
t, d));
t, d, handshakeManager));
}
@Override
@@ -101,7 +101,7 @@ class ConnectionManagerImpl implements ConnectionManager {
ioExecutor.execute(new OutgoingDuplexSyncConnection(keyManager,
connectionRegistry, streamReaderFactory, streamWriterFactory,
syncSessionFactory, transportPropertyManager, ioExecutor,
secureRandom, c, t, d));
secureRandom, handshakeManager, c, t, d));
}
@Override

View File

@@ -3,6 +3,7 @@ package org.briarproject.bramble.connection;
import org.briarproject.bramble.api.connection.ConnectionRegistry;
import org.briarproject.bramble.api.connection.InterruptibleConnection;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.contact.HandshakeManager;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.plugin.TransportConnectionReader;
import org.briarproject.bramble.api.plugin.TransportConnectionWriter;

View File

@@ -2,6 +2,7 @@ package org.briarproject.bramble.connection;
import org.briarproject.bramble.api.connection.ConnectionRegistry;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.contact.HandshakeManager;
import org.briarproject.bramble.api.db.DbException;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.plugin.TransportId;
@@ -13,9 +14,11 @@ import org.briarproject.bramble.api.sync.SyncSessionFactory;
import org.briarproject.bramble.api.transport.KeyManager;
import org.briarproject.bramble.api.transport.StreamContext;
import org.briarproject.bramble.api.transport.StreamReaderFactory;
import org.briarproject.bramble.api.transport.StreamWriter;
import org.briarproject.bramble.api.transport.StreamWriterFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Executor;
import static java.util.logging.Level.WARNING;
@@ -24,6 +27,10 @@ import static org.briarproject.bramble.util.LogUtils.logException;
@NotNullByDefault
class IncomingDuplexSyncConnection extends DuplexSyncConnection
implements Runnable {
private final HandshakeManager handshakeManager;
// FIXME: Exchange timestamp as part of handshake protocol?
private static final long TIMESTAMP = 1617235200; // 1 April 2021 00:00 UTC
IncomingDuplexSyncConnection(KeyManager keyManager,
ConnectionRegistry connectionRegistry,
@@ -32,14 +39,18 @@ class IncomingDuplexSyncConnection extends DuplexSyncConnection
SyncSessionFactory syncSessionFactory,
TransportPropertyManager transportPropertyManager,
Executor ioExecutor, TransportId transportId,
DuplexTransportConnection connection) {
DuplexTransportConnection connection,
HandshakeManager handshakeManager) {
super(keyManager, connectionRegistry, streamReaderFactory,
streamWriterFactory, syncSessionFactory,
transportPropertyManager, ioExecutor, transportId, connection);
this.handshakeManager = handshakeManager;
}
@Override
public void run() {
LOG.info("Running IncomingDuplexSyncConnection on transport " +
transportId.getString());
// Read and recognise the tag
StreamContext ctx = recogniseTag(reader, transportId);
if (ctx == null) {
@@ -54,10 +65,22 @@ class IncomingDuplexSyncConnection extends DuplexSyncConnection
return;
}
if (ctx.isHandshakeMode()) {
// TODO: Support handshake mode for contacts
LOG.warning("Received handshake tag, expected rotation mode");
onReadError(true);
return;
if (!performHandshake(ctx, contactId)) {
LOG.warning("Handshake failed");
return;
}
// Allocate a rotation mode stream context
ctx = allocateStreamContext(contactId, transportId);
if (ctx == null) {
LOG.warning("Could not allocate stream context");
onWriteError();
return;
}
if (ctx.isHandshakeMode()) {
LOG.warning("Got handshake mode context after handshaking");
onWriteError();
return;
}
}
connectionRegistry.registerIncomingConnection(contactId, transportId,
this);
@@ -103,5 +126,35 @@ class IncomingDuplexSyncConnection extends DuplexSyncConnection
onWriteError();
}
}
private boolean performHandshake(StreamContext ctxIn, ContactId contactId) {
LOG.info("Performing handshake (Incoming)");
// Allocate the outgoing stream context
StreamContext ctxOut =
allocateStreamContext(contactId, transportId);
if (ctxOut == null) {
LOG.warning("Could not allocate stream context");
onReadError(true);
return false;
}
try {
InputStream in = streamReaderFactory.createStreamReader(
reader.getInputStream(), ctxIn);
// Flush the output stream to send the outgoing stream header
StreamWriter out = streamWriterFactory.createStreamWriter(
writer.getOutputStream(), ctxOut);
out.getOutputStream().flush();
HandshakeManager.HandshakeResult result =
handshakeManager.handshake(contactId, in, out);
keyManager.addRotationKeys(contactId, result.getMasterKey(),
TIMESTAMP, result.isAlice(), true);
LOG.info("Rotation keys added");
return true;
} catch (IOException | DbException e) {
logException(LOG, WARNING, e);
onReadError(true);
return false;
}
}
}

View File

@@ -2,6 +2,7 @@ package org.briarproject.bramble.connection;
import org.briarproject.bramble.api.connection.ConnectionRegistry;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.contact.HandshakeManager;
import org.briarproject.bramble.api.db.DbException;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.plugin.TransportId;
@@ -14,9 +15,11 @@ import org.briarproject.bramble.api.sync.SyncSessionFactory;
import org.briarproject.bramble.api.transport.KeyManager;
import org.briarproject.bramble.api.transport.StreamContext;
import org.briarproject.bramble.api.transport.StreamReaderFactory;
import org.briarproject.bramble.api.transport.StreamWriter;
import org.briarproject.bramble.api.transport.StreamWriterFactory;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.util.concurrent.Executor;
@@ -28,26 +31,38 @@ import static org.briarproject.bramble.util.LogUtils.logException;
class OutgoingDuplexSyncConnection extends DuplexSyncConnection
implements Runnable {
// FIXME: Exchange timestamp as part of handshake protocol?
private static final long TIMESTAMP = 1617235200; // 1 April 2021 00:00 UTC
private final SecureRandom secureRandom;
private final HandshakeManager handshakeManager;
private final ContactId contactId;
OutgoingDuplexSyncConnection(KeyManager keyManager,
OutgoingDuplexSyncConnection(
KeyManager keyManager,
ConnectionRegistry connectionRegistry,
StreamReaderFactory streamReaderFactory,
StreamWriterFactory streamWriterFactory,
SyncSessionFactory syncSessionFactory,
TransportPropertyManager transportPropertyManager,
Executor ioExecutor, SecureRandom secureRandom, ContactId contactId,
TransportId transportId, DuplexTransportConnection connection) {
Executor ioExecutor,
SecureRandom secureRandom,
HandshakeManager handshakeManager,
ContactId contactId,
TransportId transportId,
DuplexTransportConnection connection) {
super(keyManager, connectionRegistry, streamReaderFactory,
streamWriterFactory, syncSessionFactory,
transportPropertyManager, ioExecutor, transportId, connection);
this.secureRandom = secureRandom;
this.handshakeManager = handshakeManager;
this.contactId = contactId;
}
@Override
public void run() {
LOG.info("Running OutgoingDuplexSyncConnection on transport " +
transportId.getString());
// Allocate a stream context
StreamContext ctx = allocateStreamContext(contactId, transportId);
if (ctx == null) {
@@ -56,10 +71,22 @@ class OutgoingDuplexSyncConnection extends DuplexSyncConnection
return;
}
if (ctx.isHandshakeMode()) {
// TODO: Support handshake mode for contacts
LOG.warning("Cannot use handshake mode stream context");
onWriteError();
return;
if (!performHandshake(ctx)) {
LOG.warning("Handshake failed");
return;
}
// Allocate a rotation mode stream context
ctx = allocateStreamContext(contactId, transportId);
if (ctx == null) {
LOG.warning("Could not allocate stream context");
onWriteError();
return;
}
if (ctx.isHandshakeMode()) {
LOG.warning("Got handshake mode context after handshaking");
onWriteError();
return;
}
}
// Start the incoming session on another thread
Priority priority = generatePriority();
@@ -127,6 +154,59 @@ class OutgoingDuplexSyncConnection extends DuplexSyncConnection
}
}
private boolean performHandshake(StreamContext ctxOut) {
LOG.info("Performing handshake (Outgoing)");
// Flush the output stream to send the outgoing stream header
StreamWriter out;
try {
out = streamWriterFactory.createStreamWriter(
writer.getOutputStream(), ctxOut);
out.getOutputStream().flush();
} catch (IOException e) {
logException(LOG, WARNING, e);
onWriteError();
return false;
}
// Read and recognise the tag
StreamContext ctxIn = recogniseTag(reader, transportId);
// Unrecognised tags are suspicious in this case
if (ctxIn == null) {
LOG.warning("Unrecognised tag for returning stream");
onReadError();
return false;
}
// Check that the stream comes from the expected contact
ContactId inContactId = ctxIn.getContactId();
if (contactId == null) {
LOG.warning("Expected contact tag, got rendezvous tag");
onReadError();
return false;
}
if (!inContactId.equals(contactId)) {
LOG.warning("Wrong contact ID for returning stream");
onReadError();
return false;
}
// TODO: Register the connection, close it if it's redundant
// Handshake and exchange contacts
try {
InputStream in = streamReaderFactory.createStreamReader(
reader.getInputStream(), ctxIn);
HandshakeManager.HandshakeResult result =
handshakeManager.handshake(contactId, in, out);
keyManager.addRotationKeys(contactId, result.getMasterKey(),
TIMESTAMP, result.isAlice(), true);
LOG.info("Rotation keys added");
return true;
} catch (IOException | DbException e) {
logException(LOG, WARNING, e);
onWriteError();
return false;
} finally {
// TODO: Unregister the connection
}
}
private void onReadError() {
// 'Recognised' is always true for outgoing connections
onReadError(true);

View File

@@ -1,5 +1,6 @@
package org.briarproject.bramble.contact;
import org.briarproject.bramble.api.contact.ContactExchangeCrypto;
import org.briarproject.bramble.api.crypto.CryptoComponent;
import org.briarproject.bramble.api.crypto.PrivateKey;
import org.briarproject.bramble.api.crypto.PublicKey;
@@ -10,12 +11,12 @@ import java.security.GeneralSecurityException;
import javax.inject.Inject;
import static org.briarproject.bramble.contact.ContactExchangeConstants.ALICE_KEY_LABEL;
import static org.briarproject.bramble.contact.ContactExchangeConstants.ALICE_NONCE_LABEL;
import static org.briarproject.bramble.contact.ContactExchangeConstants.BOB_KEY_LABEL;
import static org.briarproject.bramble.contact.ContactExchangeConstants.BOB_NONCE_LABEL;
import static org.briarproject.bramble.contact.ContactExchangeConstants.PROTOCOL_VERSION;
import static org.briarproject.bramble.contact.ContactExchangeConstants.SIGNING_LABEL;
import static org.briarproject.bramble.api.contact.ContactExchangeConstants.ALICE_KEY_LABEL;
import static org.briarproject.bramble.api.contact.ContactExchangeConstants.ALICE_NONCE_LABEL;
import static org.briarproject.bramble.api.contact.ContactExchangeConstants.BOB_KEY_LABEL;
import static org.briarproject.bramble.api.contact.ContactExchangeConstants.BOB_NONCE_LABEL;
import static org.briarproject.bramble.api.contact.ContactExchangeConstants.PROTOCOL_VERSION;
import static org.briarproject.bramble.api.contact.ContactExchangeConstants.SIGNING_LABEL;
@NotNullByDefault
class ContactExchangeCryptoImpl implements ContactExchangeCrypto {

View File

@@ -4,6 +4,7 @@ import org.briarproject.bramble.api.FormatException;
import org.briarproject.bramble.api.Predicate;
import org.briarproject.bramble.api.client.ClientHelper;
import org.briarproject.bramble.api.contact.Contact;
import org.briarproject.bramble.api.contact.ContactExchangeCrypto;
import org.briarproject.bramble.api.contact.ContactExchangeManager;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.contact.ContactManager;
@@ -47,8 +48,8 @@ import javax.inject.Inject;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.api.identity.AuthorConstants.MAX_SIGNATURE_LENGTH;
import static org.briarproject.bramble.contact.ContactExchangeConstants.PROTOCOL_VERSION;
import static org.briarproject.bramble.contact.ContactExchangeRecordTypes.CONTACT_INFO;
import static org.briarproject.bramble.api.contact.ContactExchangeConstants.PROTOCOL_VERSION;
import static org.briarproject.bramble.api.contact.ContactExchangeRecordTypes.CONTACT_INFO;
import static org.briarproject.bramble.util.ValidationUtils.checkLength;
import static org.briarproject.bramble.util.ValidationUtils.checkSize;
@@ -81,7 +82,8 @@ class ContactExchangeManagerImpl implements ContactExchangeManager {
private final ContactManager contactManager;
private final IdentityManager identityManager;
private final TransportPropertyManager transportPropertyManager;
private final ContactExchangeCrypto contactExchangeCrypto;
private final org.briarproject.bramble.api.contact.ContactExchangeCrypto
contactExchangeCrypto;
private final StreamReaderFactory streamReaderFactory;
private final StreamWriterFactory streamWriterFactory;

View File

@@ -1,9 +0,0 @@
package org.briarproject.bramble.contact;
/**
* Record types for the contact exchange protocol.
*/
interface ContactExchangeRecordTypes {
byte CONTACT_INFO = 0;
}

View File

@@ -9,6 +9,7 @@ import org.briarproject.bramble.api.contact.PendingContact;
import org.briarproject.bramble.api.contact.PendingContactId;
import org.briarproject.bramble.api.contact.PendingContactState;
import org.briarproject.bramble.api.contact.event.PendingContactStateChangedEvent;
import org.briarproject.bramble.api.crypto.CryptoConstants;
import org.briarproject.bramble.api.crypto.KeyPair;
import org.briarproject.bramble.api.crypto.PublicKey;
import org.briarproject.bramble.api.crypto.SecretKey;
@@ -119,6 +120,18 @@ class ContactManagerImpl implements ContactManager, EventListener {
verified, active));
}
@Override
public ContactId addContact(Transaction txn, Author remote, AuthorId local,
PublicKey handshake, boolean verified)
throws DbException, GeneralSecurityException {
ContactId c = db.addContact(txn, remote, local, handshake, verified);
Contact contact = db.getContact(txn, c);
KeyPair ourKeyPair = identityManager.getHandshakeKeys(txn);
keyManager.addContact(txn, c, handshake, ourKeyPair);
for (ContactHook hook : hooks) hook.addingContact(txn, contact);
return c;
}
@Override
public String getHandshakeLink() throws DbException {
KeyPair keyPair = db.transactionWithResult(true,
@@ -234,6 +247,23 @@ class ContactManagerImpl implements ContactManager, EventListener {
db.transaction(false, txn -> setContactAlias(txn, c, alias));
}
@Override
public void setHandshakePublicKey(Transaction txn, ContactId c,
PublicKey handshakePublicKey) throws DbException {
if (handshakePublicKey.getKeyType() !=
CryptoConstants.KEY_TYPE_AGREEMENT) {
throw new IllegalArgumentException();
}
db.setHandshakePublicKey(txn, c, handshakePublicKey);
}
@Override
public void setHandshakePublicKey(ContactId c, PublicKey handshakePublicKey)
throws DbException {
db.transaction(false,
txn -> setHandshakePublicKey(txn, c, handshakePublicKey));
}
@Override
public boolean contactExists(Transaction txn, AuthorId remoteAuthorId,
AuthorId localAuthorId) throws DbException {

View File

@@ -1,5 +1,6 @@
package org.briarproject.bramble.contact;
import org.briarproject.bramble.api.contact.ContactExchangeCrypto;
import org.briarproject.bramble.api.contact.ContactExchangeManager;
import org.briarproject.bramble.api.contact.ContactManager;
import org.briarproject.bramble.api.contact.HandshakeManager;

View File

@@ -3,6 +3,8 @@ package org.briarproject.bramble.contact;
import org.briarproject.bramble.api.FormatException;
import org.briarproject.bramble.api.Pair;
import org.briarproject.bramble.api.Predicate;
import org.briarproject.bramble.api.contact.Contact;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.contact.ContactManager;
import org.briarproject.bramble.api.contact.HandshakeManager;
import org.briarproject.bramble.api.contact.PendingContact;
@@ -88,6 +90,27 @@ class HandshakeManagerImpl implements HandshakeManager {
});
PublicKey theirStaticPublicKey = keys.getFirst();
KeyPair ourStaticKeyPair = keys.getSecond();
return handshake(theirStaticPublicKey, ourStaticKeyPair, in, out);
}
@Override
public HandshakeResult handshake(ContactId c, InputStream in,
StreamWriter out) throws DbException, IOException {
Pair<PublicKey, KeyPair> keys = db.transactionWithResult(true, txn -> {
Contact contact = contactManager.getContact(txn, c);
PublicKey handshakePublicKey = contact.getHandshakePublicKey();
if (handshakePublicKey == null) throw new DbException();
KeyPair keyPair = identityManager.getHandshakeKeys(txn);
return new Pair<>(handshakePublicKey, keyPair);
});
PublicKey theirStaticPublicKey = keys.getFirst();
KeyPair ourStaticKeyPair = keys.getSecond();
return handshake(theirStaticPublicKey, ourStaticKeyPair, in, out);
}
private HandshakeResult handshake(PublicKey theirStaticPublicKey,
KeyPair ourStaticKeyPair, InputStream in, StreamWriter out)
throws IOException {
boolean alice = transportCrypto.isAlice(theirStaticPublicKey,
ourStaticKeyPair);
RecordReader recordReader = recordReaderFactory.createRecordReader(in);

View File

@@ -6,6 +6,7 @@ import net.i2p.crypto.eddsa.KeyPairGenerator;
import org.briarproject.bramble.api.crypto.AgreementPrivateKey;
import org.briarproject.bramble.api.crypto.AgreementPublicKey;
import org.briarproject.bramble.api.crypto.AuthenticatedCipher;
import org.briarproject.bramble.api.crypto.CryptoComponent;
import org.briarproject.bramble.api.crypto.DecryptionException;
import org.briarproject.bramble.api.crypto.KeyPair;

View File

@@ -1,5 +1,6 @@
package org.briarproject.bramble.crypto;
import org.briarproject.bramble.api.crypto.AuthenticatedCipher;
import org.briarproject.bramble.api.crypto.CryptoComponent;
import org.briarproject.bramble.api.crypto.KeyAgreementCrypto;
import org.briarproject.bramble.api.crypto.PasswordStrengthEstimator;

View File

@@ -1,5 +1,6 @@
package org.briarproject.bramble.crypto;
import org.briarproject.bramble.api.crypto.AuthenticatedCipher;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.crypto.StreamDecrypter;
import org.briarproject.bramble.api.crypto.StreamDecrypterFactory;

View File

@@ -1,6 +1,7 @@
package org.briarproject.bramble.crypto;
import org.briarproject.bramble.api.FormatException;
import org.briarproject.bramble.api.crypto.AuthenticatedCipher;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.crypto.StreamDecrypter;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;

View File

@@ -1,5 +1,6 @@
package org.briarproject.bramble.crypto;
import org.briarproject.bramble.api.crypto.AuthenticatedCipher;
import org.briarproject.bramble.api.crypto.CryptoComponent;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.crypto.StreamEncrypter;

View File

@@ -1,5 +1,6 @@
package org.briarproject.bramble.crypto;
import org.briarproject.bramble.api.crypto.AuthenticatedCipher;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.crypto.StreamEncrypter;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;

View File

@@ -1,5 +1,6 @@
package org.briarproject.bramble.crypto;
import org.briarproject.bramble.api.crypto.AuthenticatedCipher;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.spongycastle.crypto.DataLengthException;

View File

@@ -32,6 +32,7 @@ import org.briarproject.bramble.api.transport.KeySetId;
import org.briarproject.bramble.api.transport.TransportKeySet;
import org.briarproject.bramble.api.transport.TransportKeys;
import java.sql.Connection;
import java.util.Collection;
import java.util.List;
import java.util.Map;
@@ -695,6 +696,11 @@ interface Database<T> {
void setHandshakeKeyPair(T txn, AuthorId local, PublicKey publicKey,
PrivateKey privateKey) throws DbException;
/**
* Sets the handshake public key for a given contact
*/
void setHandshakePublicKey(T txn, ContactId c, PublicKey handshakePublicKey) throws DbException;
/**
* Marks the given message as permanent, i.e. not temporary.
*/

View File

@@ -1040,6 +1040,15 @@ class DatabaseComponentImpl<T> implements DatabaseComponent {
}
}
@Override
public void setHandshakePublicKey(Transaction transaction, ContactId c, PublicKey handshakePublicKey) throws DbException {
if (transaction.isReadOnly()) throw new IllegalArgumentException();
T txn = unbox(transaction);
if (!db.containsContact(txn, c))
throw new NoSuchContactException();
db.setHandshakePublicKey(txn, c, handshakePublicKey);
}
@Override
public void setHandshakeKeyPair(Transaction transaction, AuthorId local,
PublicKey publicKey, PrivateKey privateKey) throws DbException {

View File

@@ -3058,6 +3058,23 @@ abstract class JdbcDatabase implements Database<Connection> {
}
}
@Override
public void setHandshakePublicKey(Connection txn, ContactId c, PublicKey handshakePublicKey) throws DbException {
PreparedStatement ps = null;
try {
String sql = "UPDATE contacts SET handshakePublicKey = ? WHERE contactId = ?";
ps = txn.prepareStatement(sql);
ps.setBytes(1, handshakePublicKey.getEncoded());
ps.setInt(2, c.getInt());
int affected = ps.executeUpdate();
if (affected < 0 || affected > 1) throw new DbStateException();
ps.close();
} catch (SQLException e) {
tryToClose(ps, LOG, WARNING);
throw new DbException(e);
}
}
@Override
public void setGroupVisibility(Connection txn, ContactId c, GroupId g,
boolean shared) throws DbException {

View File

@@ -118,6 +118,11 @@ class IdentityManagerImpl implements IdentityManager, OpenDatabaseHook {
return cached.getLocalAuthor();
}
@Override
public Identity getIdentity(Transaction txn) throws DbException {
return getCachedIdentity(txn);
}
@Override
public LocalAuthor getLocalAuthor(Transaction txn) throws DbException {
return getCachedIdentity(txn).getLocalAuthor();

View File

@@ -127,6 +127,7 @@ class KeyAgreementConnector {
List<Pair<DuplexPlugin, BdfList>> transports = new ArrayList<>();
for (TransportId id : PREFERRED_TRANSPORTS) {
TransportDescriptor d = descriptors.get(id);
LOG.info("id: " + id + " d: " + d);
Plugin p = pluginManager.getPlugin(id);
if (d != null && p instanceof DuplexPlugin) {
if (LOG.isLoggable(INFO))
@@ -137,6 +138,9 @@ class KeyAgreementConnector {
// TODO: If we don't have any transports in common with the peer,
// warn the user and give up (#1224)
if (transports.isEmpty()) {
LOG.info("No transports found");
}
if (!transports.isEmpty()) {
byte[] commitment = remotePayload.getCommitment();

View File

@@ -294,7 +294,13 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
public TransportProperties getRemoteProperties(ContactId c, TransportId t)
throws DbException {
return db.transactionWithResult(true, txn ->
getRemoteProperties(txn, db.getContact(txn, c), t));
getRemoteProperties(txn, c, t));
}
@Override
public TransportProperties getRemoteProperties(Transaction txn,
ContactId c, TransportId t) throws DbException {
return getRemoteProperties(txn, db.getContact(txn, c), t);
}
@Override

View File

@@ -101,9 +101,9 @@ class KeyManagerImpl implements KeyManager, Service, EventListener {
}
@Override
public Map<TransportId, KeySetId> addRotationKeys(
Transaction txn, ContactId c, SecretKey rootKey, long timestamp,
boolean alice, boolean active) throws DbException {
public Map<TransportId, KeySetId> addRotationKeys(Transaction txn,
ContactId c, SecretKey rootKey, long timestamp, boolean alice,
boolean active) throws DbException {
Map<TransportId, KeySetId> ids = new HashMap<>();
for (Entry<TransportId, TransportKeyManager> e : managers.entrySet()) {
TransportId t = e.getKey();
@@ -114,6 +114,14 @@ class KeyManagerImpl implements KeyManager, Service, EventListener {
return ids;
}
@Override
public Map<TransportId, KeySetId> addRotationKeys(ContactId c,
SecretKey rootKey, long timestamp, boolean alice, boolean active)
throws DbException {
return db.transactionWithResult(false, txn ->
addRotationKeys(txn, c, rootKey, timestamp, alice, active));
}
@Override
public Map<TransportId, KeySetId> addContact(Transaction txn, ContactId c,
PublicKey theirPublicKey, KeyPair ourKeyPair)
@@ -137,7 +145,7 @@ class KeyManagerImpl implements KeyManager, Service, EventListener {
PendingContactId p, PublicKey theirPublicKey, KeyPair ourKeyPair)
throws DbException, GeneralSecurityException {
SecretKey staticMasterKey = transportCrypto
.deriveStaticMasterKey(theirPublicKey, ourKeyPair);
.deriveStaticMasterKey(theirPublicKey, ourKeyPair);
SecretKey rootKey =
transportCrypto.deriveHandshakeRootKey(staticMasterKey, true);
boolean alice = transportCrypto.isAlice(theirPublicKey, ourKeyPair);

View File

@@ -1,5 +1,6 @@
package org.briarproject.bramble.crypto;
import org.briarproject.bramble.api.crypto.AuthenticatedCipher;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestUtils;

View File

@@ -1,5 +1,6 @@
package org.briarproject.bramble.crypto;
import org.briarproject.bramble.api.crypto.AuthenticatedCipher;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestUtils;

View File

@@ -1,5 +1,6 @@
package org.briarproject.bramble.crypto;
import org.briarproject.bramble.api.crypto.AuthenticatedCipher;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;

View File

@@ -1,5 +1,6 @@
package org.briarproject.bramble.crypto;
import org.briarproject.bramble.api.crypto.AuthenticatedCipher;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.util.StringUtils;

View File

@@ -28,7 +28,7 @@ android {
targetSdkVersion 29
versionCode 10218
versionName "1.2.18"
applicationId "org.briarproject.briar.android"
applicationId "org.briarproject.briar.socialbackup"
vectorDrawables.useSupportLibrary = true
buildConfigField "String", "GitHash",
@@ -106,6 +106,7 @@ dependencies {
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.recyclerview:recyclerview-selection:1.1.0-rc03'
implementation 'org.magmacollective.darkcrystal:dark-crystal-secret-sharing-wrapper:1.1.0'
implementation 'info.guardianproject.panic:panic:1.0'
implementation 'info.guardianproject.trustedintents:trustedintents:0.2'

View File

@@ -40,3 +40,5 @@
# Dependency injection annotations, needed for UI tests on older API levels
-keep class javax.inject.**
-keep class com.sun.jna.** { *; }

View File

@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name" translatable="false">Briar Debug</string>
<string name="app_package" translatable="false">org.briarproject.briar.android.debug</string>
<string name="app_name" translatable="false">Briar SB Debug</string>
<string name="app_package" translatable="false">org.briarproject.briar.socialbackup.debug</string>
</resources>

View File

@@ -138,6 +138,51 @@
</intent-filter>
</activity>
<activity
android:name="org.briarproject.briar.android.account.NewOrRecoverActivity"
android:label="@string/activity_name_new_or_recover_account"
android:parentActivityName="org.briarproject.briar.android.login.StartupActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="org.briarproject.briar.android.login.StartupActivity" />
</activity>
<activity
android:name="org.briarproject.briar.android.socialbackup.DistributedBackupActivity"
android:label="@string/activity_name_distributed_backup"
android:parentActivityName="org.briarproject.briar.android.settings.SettingsActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="org.briarproject.briar.android.settings.SettingsActivity" />
</activity>
<activity
android:name="org.briarproject.briar.android.socialbackup.recover.CustodianReturnShardActivity"
android:label="@string/activity_name_custodian_help_recovery"
android:parentActivityName="org.briarproject.briar.android.conversation.ConversationActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="org.briarproject.briar.android.conversation.ConversationActivity" />
</activity>
<activity
android:name="org.briarproject.briar.android.socialbackup.recover.OwnerReturnShardActivity"
android:label="@string/activity_name_recovery"
android:parentActivityName="org.briarproject.briar.android.account.NewOrRecoverActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="org.briarproject.briar.android.account.NewOrRecoverActivity" />
</activity>
<activity
android:name="org.briarproject.briar.android.socialbackup.recover.RestoreAccountActivity"
android:label="@string/activity_name_restore_account"
android:parentActivityName="org.briarproject.briar.android.socialbackup.recover.OwnerReturnShardActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="org.briarproject.briar.android.socialbackup.recover.OwnerReturnShardActivity" />
</activity>
<activity
android:name="org.briarproject.briar.android.conversation.ConversationActivity"
android:label="@string/app_name"

View File

@@ -8,11 +8,13 @@ import org.briarproject.bramble.BrambleCoreModule;
import org.briarproject.bramble.account.BriarAccountModule;
import org.briarproject.bramble.api.FeatureFlags;
import org.briarproject.bramble.api.account.AccountManager;
import org.briarproject.bramble.api.client.ClientHelper;
import org.briarproject.bramble.api.connection.ConnectionRegistry;
import org.briarproject.bramble.api.contact.ContactExchangeManager;
import org.briarproject.bramble.api.contact.ContactManager;
import org.briarproject.bramble.api.crypto.CryptoExecutor;
import org.briarproject.bramble.api.crypto.PasswordStrengthEstimator;
import org.briarproject.bramble.api.db.DatabaseComponent;
import org.briarproject.bramble.api.db.DatabaseExecutor;
import org.briarproject.bramble.api.db.TransactionManager;
import org.briarproject.bramble.api.event.EventBus;
@@ -59,6 +61,7 @@ import org.briarproject.briar.api.privategroup.PrivateGroupFactory;
import org.briarproject.briar.api.privategroup.PrivateGroupManager;
import org.briarproject.briar.api.privategroup.invitation.GroupInvitationFactory;
import org.briarproject.briar.api.privategroup.invitation.GroupInvitationManager;
import org.briarproject.briar.api.socialbackup.SocialBackupManager;
import org.briarproject.briar.api.test.TestDataCreator;
import java.util.concurrent.Executor;
@@ -184,6 +187,12 @@ public interface AndroidComponent
Thread.UncaughtExceptionHandler exceptionHandler();
SocialBackupManager socialBackupManager();
DatabaseComponent databaseComponent();
ClientHelper clientHelper();
void inject(SignInReminderReceiver briarService);
void inject(BriarService briarService);

View File

@@ -42,6 +42,8 @@ import org.briarproject.briar.android.privategroup.list.GroupListModule;
import org.briarproject.briar.android.reporting.DevReportModule;
import org.briarproject.briar.android.settings.SettingsModule;
import org.briarproject.briar.android.sharing.SharingModule;
import org.briarproject.briar.android.socialbackup.recover.CustodianReturnShardModule;
import org.briarproject.briar.android.socialbackup.recover.OwnerReturnShardModule;
import org.briarproject.briar.android.test.TestAvatarCreatorImpl;
import org.briarproject.briar.android.viewmodel.ViewModelModule;
import org.briarproject.briar.api.android.AndroidNotificationManager;
@@ -49,6 +51,7 @@ import org.briarproject.briar.api.android.DozeWatchdog;
import org.briarproject.briar.api.android.LockManager;
import org.briarproject.briar.api.android.ScreenFilterMonitor;
import org.briarproject.briar.api.test.TestAvatarCreator;
import org.briarproject.briar.socialbackup.AndroidDarkCrystalModule;
import java.io.File;
import java.security.GeneralSecurityException;
@@ -83,12 +86,15 @@ import static org.briarproject.briar.android.TestingConstants.IS_DEBUG_BUILD;
SettingsModule.class,
DevReportModule.class,
ContactListModule.class,
AndroidDarkCrystalModule.class,
IntroductionModule.class,
// below need to be within same scope as ViewModelProvider.Factory
ForumModule.class,
GroupListModule.class,
GroupConversationModule.class,
SharingModule.class,
OwnerReturnShardModule.class,
CustodianReturnShardModule.class
})
public class AppModule {

View File

@@ -2,7 +2,7 @@ package org.briarproject.briar.android.account;
import android.content.Context;
interface DozeHelper {
public interface DozeHelper {
boolean needToShowDozeFragment(Context context);
}

View File

@@ -14,7 +14,7 @@ import static org.briarproject.briar.android.util.UiUtils.needsDozeWhitelisting;
@UiThread
@NotNullByDefault
class DozeView extends PowerView {
public class DozeView extends PowerView {
@Nullable
private Runnable onButtonClickListener;

View File

@@ -21,7 +21,7 @@ import static android.os.Build.VERSION.SDK_INT;
@UiThread
@NotNullByDefault
class HuaweiView extends PowerView {
public class HuaweiView extends PowerView {
private final static String PACKAGE_NAME = "com.huawei.systemmanager";
private final static String CLASS_NAME =

View File

@@ -0,0 +1,60 @@
package org.briarproject.briar.android.account;
import android.content.Intent;
import android.os.Bundle;
import org.briarproject.briar.R;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.activity.BaseActivity;
import org.briarproject.briar.android.fragment.BaseFragment;
import org.briarproject.briar.android.socialbackup.recover.OwnerReturnShardActivity;
import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK;
import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
public class NewOrRecoverActivity extends BaseActivity implements
BaseFragment.BaseFragmentListener, SetupNewAccountChosenListener,
RecoverAccountListener {
@Override
public void injectActivity(ActivityComponent component) {
component.inject(this);
}
@Override
public void onCreate(Bundle state) {
super.onCreate(state);
// fade-in after splash screen instead of default animation
// TODO the fade in is not working
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
setContentView(R.layout.activity_fragment_container);
NewOrRecoverFragment fragment = NewOrRecoverFragment.newInstance();
showInitialFragment(fragment);
}
@Override
public void setupNewAccountChosen() {
finish();
Intent i = new Intent(this, SetupActivity.class);
i.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TOP |
FLAG_ACTIVITY_CLEAR_TASK | FLAG_ACTIVITY_TASK_ON_HOME);
startActivity(i);
}
@Override
public void recoverAccountChosen() {
finish();
Intent i = new Intent(this, OwnerReturnShardActivity.class);
i.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TOP |
FLAG_ACTIVITY_CLEAR_TASK | FLAG_ACTIVITY_TASK_ON_HOME);
startActivity(i);
}
@Override
@Deprecated
public void runOnDbThread(Runnable runnable) {
throw new RuntimeException("Don't use this deprecated method here.");
}
}

View File

@@ -0,0 +1,70 @@
package org.briarproject.briar.android.account;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import org.briarproject.briar.R;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.fragment.BaseFragment;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class NewOrRecoverFragment extends BaseFragment {
public static final String TAG = NewOrRecoverFragment.class.getName();
protected SetupNewAccountChosenListener setupNewAccountListener;
protected RecoverAccountListener recoverAccountListener;
public static NewOrRecoverFragment newInstance() {
Bundle bundle = new Bundle();
NewOrRecoverFragment fragment = new NewOrRecoverFragment();
fragment.setArguments(bundle);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requireActivity().setTitle(R.string.setup_title);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable
ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_new_or_recover,
container, false);
Button newAccountButton = view.findViewById(R.id.buttonSetupNewAccount);
newAccountButton.setOnClickListener(e -> {
setupNewAccountListener.setupNewAccountChosen();
});
Button recoverAccountButton = view.findViewById(R.id.buttonRestoreAccount);
recoverAccountButton.setOnClickListener(e -> {
recoverAccountListener.recoverAccountChosen();
});
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
setupNewAccountListener = (SetupNewAccountChosenListener) context;
recoverAccountListener = (RecoverAccountListener) context;
}
@Override
public String getUniqueTag() {
return TAG;
}
@Override
public void injectFragment(ActivityComponent component) {
component.inject(this);
}
}

View File

@@ -24,7 +24,7 @@ import static org.briarproject.briar.android.util.UiUtils.showOnboardingDialog;
@UiThread
@NotNullByDefault
abstract class PowerView extends ConstraintLayout {
public abstract class PowerView extends ConstraintLayout {
private final TextView textView;
private final ImageView checkImage;
@@ -156,7 +156,7 @@ abstract class PowerView extends ConstraintLayout {
};
}
interface OnCheckedChangedListener {
public interface OnCheckedChangedListener {
void onCheckedChanged();
}

View File

@@ -0,0 +1,8 @@
package org.briarproject.briar.android.account;
import androidx.annotation.UiThread;
public interface RecoverAccountListener {
@UiThread
void recoverAccountChosen();
}

View File

@@ -0,0 +1,8 @@
package org.briarproject.briar.android.account;
import androidx.annotation.UiThread;
public interface SetupNewAccountChosenListener {
@UiThread
void setupNewAccountChosen();
}

View File

@@ -29,6 +29,7 @@ import static org.briarproject.briar.android.account.SetupViewModel.State.SET_PA
@MethodsNotNullByDefault
@ParametersNotNullByDefault
public
class SetupViewModel extends AndroidViewModel {
enum State {AUTHOR_NAME, SET_PASSWORD, DOZE, CREATED, FAILED}

View File

@@ -2,10 +2,13 @@ package org.briarproject.briar.android.activity;
import android.app.Activity;
import org.briarproject.bramble.api.db.DatabaseComponent;
import org.briarproject.briar.android.AndroidComponent;
import org.briarproject.briar.android.StartupFailureActivity;
import org.briarproject.briar.android.account.AuthorNameFragment;
import org.briarproject.briar.android.account.DozeFragment;
import org.briarproject.briar.android.account.NewOrRecoverActivity;
import org.briarproject.briar.android.account.NewOrRecoverFragment;
import org.briarproject.briar.android.account.SetPasswordFragment;
import org.briarproject.briar.android.account.SetupActivity;
import org.briarproject.briar.android.account.UnlockActivity;
@@ -77,20 +80,42 @@ import org.briarproject.briar.android.sharing.ShareBlogFragment;
import org.briarproject.briar.android.sharing.ShareForumActivity;
import org.briarproject.briar.android.sharing.ShareForumFragment;
import org.briarproject.briar.android.sharing.SharingModule;
import org.briarproject.briar.android.socialbackup.recover.CustodianRecoveryModeExplainerFragment;
import org.briarproject.briar.android.socialbackup.CustodianSelectorFragment;
import org.briarproject.briar.android.socialbackup.DistributedBackupActivity;
import org.briarproject.briar.android.socialbackup.ExistingBackupFragment;
import org.briarproject.briar.android.socialbackup.recover.CustodianReturnShardActivity;
import org.briarproject.briar.android.socialbackup.recover.CustodianReturnShardErrorFragment;
import org.briarproject.briar.android.socialbackup.recover.CustodianReturnShardFragment;
import org.briarproject.briar.android.socialbackup.recover.CustodianReturnShardSuccessFragment;
import org.briarproject.briar.android.socialbackup.recover.OwnerRecoveryModeErrorFragment;
import org.briarproject.briar.android.socialbackup.recover.OwnerRecoveryModeExplainerFragment;
import org.briarproject.briar.android.socialbackup.recover.OwnerRecoveryModeMainFragment;
import org.briarproject.briar.android.socialbackup.recover.OwnerReturnShardActivity;
import org.briarproject.briar.android.socialbackup.recover.OwnerReturnShardFragment;
import org.briarproject.briar.android.socialbackup.ShardsSentFragment;
import org.briarproject.briar.android.socialbackup.ThresholdSelectorFragment;
import org.briarproject.briar.android.socialbackup.creation.CreateBackupModule;
import org.briarproject.briar.android.socialbackup.recover.OwnerReturnShardSuccessFragment;
import org.briarproject.briar.android.socialbackup.recover.RestoreAccountActivity;
import org.briarproject.briar.android.socialbackup.recover.RestoreAccountDozeFragment;
import org.briarproject.briar.android.socialbackup.recover.RestoreAccountSetPasswordFragment;
import org.briarproject.briar.android.splash.SplashScreenActivity;
import org.briarproject.briar.android.test.TestDataActivity;
import org.briarproject.briar.api.socialbackup.recovery.RestoreAccount;
import dagger.Component;
@ActivityScope
@Component(modules = {
@Component(modules ={
ActivityModule.class,
BlogModule.class,
CreateGroupModule.class,
GroupInvitationModule.class,
GroupMemberModule.class,
GroupRevealModule.class,
SharingModule.SharingLegacyModule.class
SharingModule.SharingLegacyModule.class,
CreateBackupModule.class
}, dependencies = AndroidComponent.class)
public interface ActivityComponent {
@@ -180,6 +205,16 @@ public interface ActivityComponent {
void inject(CrashReportActivity crashReportActivity);
void inject(NewOrRecoverActivity newOrRecoverActivity);
void inject(CustodianReturnShardActivity custodianReturnShardActivity);
void inject(OwnerReturnShardActivity ownerReturnShardActivity);
void inject(OwnerRecoveryModeMainFragment ownerRecoveryModeMainFragment);
void inject(RestoreAccountActivity restoreAccountActivity);
// Fragments
void inject(AuthorNameFragment fragment);
@@ -238,4 +273,37 @@ public interface ActivityComponent {
void inject(ConfirmAvatarDialogFragment fragment);
void inject(ThresholdSelectorFragment thresholdSelectorFragment);
void inject(DistributedBackupActivity distributedBackupActivity);
void inject(DatabaseComponent databaseComponent);
void inject(CustodianSelectorFragment custodianSelectorFragment);
void inject(ShardsSentFragment shardsSentFragment);
void inject(OwnerRecoveryModeExplainerFragment ownerRecoveryModeExplainerFragment);
void inject(ExistingBackupFragment existingBackupFragment);
void inject(NewOrRecoverFragment newOrRecoverFragment);
void inject(CustodianRecoveryModeExplainerFragment custodianRecoveryModeExplainerFragment);
void inject(CustodianReturnShardFragment custodianReturnShardFragment);
void inject(OwnerReturnShardFragment ownerReturnShardFragment);
void inject(CustodianReturnShardSuccessFragment custodianReturnShardSuccessFragment);
void inject(RestoreAccountSetPasswordFragment restoreAccountSetPasswordFragment);
void inject(RestoreAccountDozeFragment restoreAccountDozeFragment);
void inject(OwnerReturnShardSuccessFragment ownerReturnShardSuccessFragment);
void inject(OwnerRecoveryModeErrorFragment ownerRecoveryModeErrorFragment);
void inject(CustodianReturnShardErrorFragment custodianReturnShardErrorFragment);
}

View File

@@ -45,7 +45,7 @@ import static org.briarproject.bramble.util.LogUtils.logException;
public class AddNearbyContactFragment extends BaseFragment
implements QrCodeView.FullscreenListener {
static final String TAG = AddNearbyContactFragment.class.getName();
public static final String TAG = AddNearbyContactFragment.class.getName();
private static final Logger LOG = Logger.getLogger(TAG);

View File

@@ -25,7 +25,7 @@ import static androidx.core.app.ActivityCompat.shouldShowRequestPermissionRation
import static androidx.core.content.ContextCompat.checkSelfPermission;
import static org.briarproject.briar.android.util.UiUtils.getGoToSettingsListener;
class AddNearbyContactPermissionManager {
public class AddNearbyContactPermissionManager {
private enum Permission {
UNKNOWN, GRANTED, SHOW_RATIONALE, PERMANENTLY_DENIED
@@ -38,7 +38,7 @@ class AddNearbyContactPermissionManager {
private final Consumer<String[]> requestPermissions;
private final boolean isBluetoothSupported;
AddNearbyContactPermissionManager(FragmentActivity ctx,
public AddNearbyContactPermissionManager(FragmentActivity ctx,
Consumer<String[]> requestPermissions,
boolean isBluetoothSupported) {
this.ctx = ctx;
@@ -46,7 +46,7 @@ class AddNearbyContactPermissionManager {
this.isBluetoothSupported = isBluetoothSupported;
}
void resetPermissions() {
public void resetPermissions() {
cameraPermission = Permission.UNKNOWN;
locationPermission = Permission.UNKNOWN;
}
@@ -64,7 +64,7 @@ class AddNearbyContactPermissionManager {
}
}
static boolean areEssentialPermissionsGranted(Context ctx,
public static boolean areEssentialPermissionsGranted(Context ctx,
boolean isBluetoothSupported) {
int ok = PERMISSION_GRANTED;
return checkSelfPermission(ctx, CAMERA) == ok &&
@@ -79,7 +79,7 @@ class AddNearbyContactPermissionManager {
!isBluetoothSupported);
}
boolean checkPermissions() {
public boolean checkPermissions() {
boolean locationEnabled = isLocationEnabled(ctx);
if (locationEnabled && areEssentialPermissionsGranted()) return true;
// If an essential permission has been permanently denied, ask the
@@ -164,7 +164,7 @@ class AddNearbyContactPermissionManager {
requestPermissions.accept(permissions);
}
void onRequestPermissionResult(Map<String, Boolean> result,
public void onRequestPermissionResult(Map<String, Boolean> result,
Runnable onPermissionsGranted) {
if (gotPermission(CAMERA, result)) {
cameraPermission = Permission.GRANTED;

View File

@@ -2,7 +2,7 @@ package org.briarproject.briar.android.contact.add.nearby;
import java.io.IOException;
class CameraException extends IOException {
public class CameraException extends IOException {
CameraException(String message) {
super(message);

View File

@@ -32,7 +32,7 @@ import static java.util.logging.Logger.getLogger;
@MethodsNotNullByDefault
@ParametersNotNullByDefault
class QrCodeDecoder implements PreviewConsumer, PreviewCallback {
public class QrCodeDecoder implements PreviewConsumer, PreviewCallback {
private static final Logger LOG = getLogger(QrCodeDecoder.class.getName());
@@ -44,7 +44,7 @@ class QrCodeDecoder implements PreviewConsumer, PreviewCallback {
private Camera camera = null;
private int cameraIndex = 0;
QrCodeDecoder(AndroidExecutor androidExecutor,
public QrCodeDecoder(AndroidExecutor androidExecutor,
@IoExecutor Executor ioExecutor, ResultCallback callback) {
this.androidExecutor = androidExecutor;
this.ioExecutor = ioExecutor;
@@ -127,7 +127,7 @@ class QrCodeDecoder implements PreviewConsumer, PreviewCallback {
}
@NotNullByDefault
interface ResultCallback {
public interface ResultCallback {
@IoExecutor
void onQrCodeDecoded(Result result);
}

View File

@@ -22,12 +22,12 @@ import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.LogUtils.logException;
@NotNullByDefault
class QrCodeUtils {
public class QrCodeUtils {
private static final Logger LOG = getLogger(QrCodeUtils.class.getName());
@Nullable
static Bitmap createQrCode(DisplayMetrics dm, String input) {
public static Bitmap createQrCode(DisplayMetrics dm, String input) {
int smallestDimen = Math.min(dm.widthPixels, dm.heightPixels);
try {
// Generate QR code

View File

@@ -56,8 +56,11 @@ public abstract class BaseContactSelectorFragment<I extends SelectableContactIte
Bundle args = requireArguments();
byte[] b = args.getByteArray(GROUP_ID);
if (b == null) throw new IllegalStateException("No GroupId");
groupId = new GroupId(b);
// if (b == null) throw new IllegalStateException("No GroupId");
// TODO find what the groupId should be when selecting custodians
if (b != null) {
groupId = new GroupId(b);
}
}
@Override

View File

@@ -18,7 +18,7 @@ public abstract class ContactSelectorFragment extends
public static final String TAG = ContactSelectorFragment.class.getName();
private Menu menu;
protected Menu menu;
@Override
protected ContactSelectorAdapter getAdapter(Context context,

View File

@@ -52,6 +52,7 @@ import org.briarproject.briar.android.conversation.ConversationVisitor.TextCache
import org.briarproject.briar.android.forum.ForumActivity;
import org.briarproject.briar.android.introduction.IntroductionActivity;
import org.briarproject.briar.android.privategroup.conversation.GroupActivity;
import org.briarproject.briar.android.socialbackup.recover.CustodianReturnShardActivity;
import org.briarproject.briar.android.util.BriarSnackbarBuilder;
import org.briarproject.briar.android.view.BriarRecyclerView;
import org.briarproject.briar.android.view.ImagePreview;
@@ -396,6 +397,12 @@ public class ConversationActivity extends BriarActivity
case R.id.action_social_remove_person:
askToRemoveContact();
return true;
case R.id.action_help_recover_account:
if (contactId == null) return false;
Intent i = new Intent(this, CustodianReturnShardActivity.class);
i.putExtra(CONTACT_ID, contactId.getInt());
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}

View File

@@ -3,6 +3,7 @@ package org.briarproject.briar.android.conversation;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.briar.api.conversation.ConversationRequest;
import org.briarproject.briar.api.conversation.ConversationResponse;
import org.briarproject.briar.api.socialbackup.ShardMessageHeader;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
@@ -30,6 +31,13 @@ class ConversationNoticeItem extends ConversationItem {
this.msgText = null;
}
ConversationNoticeItem(@LayoutRes int layoutRes, String text,
ShardMessageHeader r) {
super(layoutRes, r);
this.text = text;
this.msgText = null;
}
@Nullable
String getMsgText() {
return msgText;

View File

@@ -16,6 +16,7 @@ import org.briarproject.briar.api.introduction.IntroductionResponse;
import org.briarproject.briar.api.messaging.PrivateMessageHeader;
import org.briarproject.briar.api.privategroup.invitation.GroupInvitationRequest;
import org.briarproject.briar.api.privategroup.invitation.GroupInvitationResponse;
import org.briarproject.briar.api.socialbackup.ShardMessageHeader;
import java.util.List;
@@ -292,6 +293,21 @@ class ConversationVisitor implements
}
}
@Override
public ConversationItem visitShardMessage(ShardMessageHeader r) {
if (r.isLocal()) {
String text = ctx.getString(R.string.social_backup_shard_sent,
contactName.getValue());
return new ConversationNoticeItem(
R.layout.list_item_conversation_notice_out, text, r);
} else {
String text = ctx.getString(R.string.social_backup_shard_received,
contactName.getValue());
return new ConversationNoticeItem(
R.layout.list_item_conversation_notice_in, text, r);
}
}
interface TextCache {
@Nullable
String getText(MessageId m);

View File

@@ -7,6 +7,7 @@ import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
import org.briarproject.briar.R;
import org.briarproject.briar.android.BriarService;
import org.briarproject.briar.android.account.NewOrRecoverActivity;
import org.briarproject.briar.android.account.SetupActivity;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.activity.BaseActivity;
@@ -107,7 +108,7 @@ public class StartupActivity extends BaseActivity implements
private void onAccountDeleted() {
setResult(RESULT_CANCELED);
finish();
Intent i = new Intent(this, SetupActivity.class);
Intent i = new Intent(this, NewOrRecoverActivity.class);
i.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TOP |
FLAG_ACTIVITY_CLEAR_TASK | FLAG_ACTIVITY_TASK_ON_HOME);
startActivity(i);

View File

@@ -0,0 +1,93 @@
package org.briarproject.briar.android.socialbackup;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.db.DbException;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
import org.briarproject.bramble.api.sync.GroupId;
import org.briarproject.briar.R;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.socialbackup.creation.CreateBackupController;
import org.briarproject.briar.android.contactselection.BaseContactSelectorAdapter;
import org.briarproject.briar.android.contactselection.ContactSelectorController;
import org.briarproject.briar.android.contactselection.ContactSelectorFragment;
import org.briarproject.briar.android.contactselection.SelectableContactItem;
import org.briarproject.briar.android.controller.handler.ResultExceptionHandler;
import java.util.Collection;
import javax.inject.Inject;
import androidx.annotation.Nullable;
import static java.util.Objects.requireNonNull;
@MethodsNotNullByDefault
@ParametersNotNullByDefault
public class CustodianSelectorFragment extends ContactSelectorFragment {
public static final String TAG = CustodianSelectorFragment.class.getName();
@Inject
CreateBackupController controller;
public static CustodianSelectorFragment newInstance() {
Bundle args = new Bundle();
CustodianSelectorFragment fragment = new CustodianSelectorFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void injectFragment(ActivityComponent component) {
component.inject(this);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requireActivity().setTitle(R.string.title_select_custodians);
}
@Override
protected ContactSelectorController<SelectableContactItem> getController() {
return controller;
}
@Override
public String getUniqueTag() {
return TAG;
}
@Override
protected void onSelectionChanged() {
super.onSelectionChanged();
if (menu == null) return;
MenuItem item = menu.findItem(R.id.action_contacts_selected);
if (item == null) return;
BaseContactSelectorAdapter a = adapter;
selectedContacts = a.getSelectedContactIds();
int n = selectedContacts.size();
int min = 2;
boolean enough = n >= min;
item.setVisible(enough);
if (n == 0) {
Toast.makeText(getContext(), String.format(getString(R.string.select_at_least_n_contacts), min),
Toast.LENGTH_SHORT).show();
} else if (n < min) {
Toast.makeText(getContext(), String.format(getString(R.string.select_at_least_n_more_contacts), min - n),
Toast.LENGTH_SHORT).show();
}
}
}

View File

@@ -0,0 +1,57 @@
package org.briarproject.briar.android.socialbackup;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.briar.api.socialbackup.DarkCrystal;
import org.briarproject.briar.api.socialbackup.Shard;
import org.magmacollective.darkcrystal.secretsharingwrapper.SecretSharingWrapper;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import javax.inject.Inject;
import static org.briarproject.briar.socialbackup.SocialBackupConstants.SECRET_ID_BYTES;
@NotNullByDefault
public class DarkCrystalImpl implements DarkCrystal {
@Inject
DarkCrystalImpl() {
}
@Override
public List<Shard> createShards(SecretKey secret, int numShards,
int threshold) {
Random random = new Random();
byte[] secretId = new byte[SECRET_ID_BYTES];
random.nextBytes(secretId);
List<byte[]> shardsBytes = SecretSharingWrapper
.share(secret.getBytes(), numShards, threshold);
List<Shard> shards = new ArrayList<>(numShards);
for (byte[] shardBytes : shardsBytes) {
shards.add(new Shard(secretId, shardBytes));
}
return shards;
}
@Override
public SecretKey combineShards(List<Shard> shards) throws
GeneralSecurityException {
// Check each shard has the same secret Id
byte[] secretId = shards.get(0).getSecretId();
for (Shard shard : shards) {
if (!Arrays.equals(shard.getSecretId(), secretId))
throw new GeneralSecurityException();
}
List<byte[]> shardsBytes = new ArrayList<>(shards.size());
for (Shard shard : shards) {
shardsBytes.add(shard.getShard());
}
byte[] secretBytes = SecretSharingWrapper.combine(shardsBytes);
return new SecretKey(secretBytes);
}
}

View File

@@ -0,0 +1,94 @@
package org.briarproject.briar.android.socialbackup;
import android.os.Bundle;
import android.widget.Toast;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.db.DatabaseComponent;
import org.briarproject.bramble.api.db.DbException;
import org.briarproject.briar.R;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.activity.BriarActivity;
import org.briarproject.briar.android.contactselection.ContactSelectorListener;
import org.briarproject.briar.android.fragment.BaseFragment;
import org.briarproject.briar.api.socialbackup.BackupMetadata;
import org.briarproject.briar.api.socialbackup.SocialBackupManager;
import java.util.Collection;
import java.util.List;
import javax.inject.Inject;
public class DistributedBackupActivity extends BriarActivity implements
BaseFragment.BaseFragmentListener, ContactSelectorListener,
ThresholdDefinedListener,
ShardsSentFragment.ShardsSentDismissedListener {
private Collection<ContactId> custodians;
@Inject
public SocialBackupManager socialBackupManager;
@Inject
public DatabaseComponent db;
@Override
public void injectActivity(ActivityComponent component) {
component.inject(this);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_distributed_backup);
try {
db.transaction(false, txn -> {
BackupMetadata backupMetadata =
socialBackupManager.getBackupMetadata(txn);
if (backupMetadata == null) throw new DbException();
ExistingBackupFragment fragment =
ExistingBackupFragment.newInstance(backupMetadata);
showInitialFragment(fragment);
});
} catch (DbException e) {
CustodianSelectorFragment fragment =
CustodianSelectorFragment.newInstance();
showInitialFragment(fragment);
}
}
@Override
public void contactsSelected(Collection<ContactId> contacts) {
Toast.makeText(this,
String.format("Selected %d contacts", contacts.size()),
Toast.LENGTH_SHORT).show();
custodians = contacts;
ThresholdSelectorFragment fragment =
ThresholdSelectorFragment.newInstance(contacts.size());
showNextFragment(fragment);
}
@Override
public void thresholdDefined(int threshold) {
try {
db.transaction(false, txn -> {
socialBackupManager
.createBackup(txn, (List<ContactId>) custodians,
threshold);
ShardsSentFragment fragment = new ShardsSentFragment();
showNextFragment(fragment);
});
} catch (DbException e) {
Toast.makeText(this,
"There was an error when creating the backup",
Toast.LENGTH_LONG).show();
finish();
}
}
@Override
public void shardsSentDismissed() {
finish();
}
}

View File

@@ -0,0 +1,93 @@
package org.briarproject.briar.android.socialbackup;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.briarproject.bramble.api.identity.Author;
import org.briarproject.briar.R;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.fragment.BaseFragment;
import org.briarproject.briar.api.socialbackup.BackupMetadata;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class ExistingBackupFragment extends BaseFragment {
private static final String THRESHOLD = "threshold";
private static final String CUSTODIANS = "custodians";
public static final String TAG = ExistingBackupFragment.class.getName();
public static ExistingBackupFragment newInstance(
BackupMetadata backupMetadata) {
Bundle bundle = new Bundle();
List<Author> custodians = backupMetadata.getCustodians();
ArrayList custodianNames = new ArrayList();
for (Author custodian : custodians) {
custodianNames.add(custodian.getName());
}
bundle.putStringArrayList(CUSTODIANS, custodianNames);
bundle.putInt(THRESHOLD, backupMetadata.getThreshold());
ExistingBackupFragment fragment = new ExistingBackupFragment();
fragment.setArguments(bundle);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requireActivity().setTitle(R.string.title_distributed_backup);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable
ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_existing_backup,
container, false);
Bundle args = requireArguments();
ArrayList<String> custodianNames = args.getStringArrayList(CUSTODIANS);
StringBuilder custodianNamesString = new StringBuilder();
for (String custodianName : custodianNames) {
custodianNamesString
.append("")
.append(custodianName)
.append("\n");
}
TextView textViewThreshold = view.findViewById(R.id.textViewThreshold);
textViewThreshold.setText(getString(R.string.existing_backup_explain,
args.getInt(THRESHOLD)));
TextView textViewCustodians =
view.findViewById(R.id.textViewCustodians);
textViewCustodians.setText(custodianNamesString);
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
// listener = (ShardsSentDismissedListener) context;
}
@Override
public String getUniqueTag() {
return TAG;
}
@Override
public void injectFragment(ActivityComponent component) {
component.inject(this);
}
}

View File

@@ -0,0 +1,8 @@
package org.briarproject.briar.android.socialbackup;
import androidx.annotation.UiThread;
public interface ExplainerDismissedListener {
@UiThread
void explainerDismissed();
}

View File

@@ -0,0 +1,8 @@
package org.briarproject.briar.android.socialbackup;
import androidx.annotation.UiThread;
public interface ScanQrButtonListener {
@UiThread
void scanQrButtonClicked();
}

View File

@@ -0,0 +1,74 @@
package org.briarproject.briar.android.socialbackup;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import org.briarproject.briar.R;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.fragment.BaseFragment;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
public class ShardsSentFragment extends BaseFragment {
public static final String TAG = ShardsSentFragment.class.getName();
interface ShardsSentDismissedListener {
@UiThread
void shardsSentDismissed();
}
protected ShardsSentDismissedListener listener;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requireActivity().setTitle(R.string.title_distributed_backup);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_shards_sent,
container, false);
Button button = view.findViewById(R.id.button);
button.setOnClickListener(e -> {
listener.shardsSentDismissed();
});
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
listener = (ShardsSentDismissedListener) context;
}
@Override
public String getUniqueTag() {
return TAG;
}
@Override
public void injectFragment(ActivityComponent component) {
component.inject(this);
}
public void onBackPressed() {
listener.shardsSentDismissed();
}
}

View File

@@ -0,0 +1,12 @@
package org.briarproject.briar.android.socialbackup;
import org.briarproject.bramble.api.db.DbException;
import androidx.annotation.UiThread;
public interface ThresholdDefinedListener {
@UiThread
void thresholdDefined(int threshold) throws DbException;
}

View File

@@ -0,0 +1,182 @@
package org.briarproject.briar.android.socialbackup;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import org.briarproject.bramble.api.db.DbException;
import org.briarproject.briar.R;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.fragment.BaseFragment;
import org.magmacollective.darkcrystal.secretsharingwrapper.SecretSharingWrapper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class ThresholdSelectorFragment extends BaseFragment {
public static final String TAG = ThresholdSelectorFragment.class.getName();
private static final String NUMBER_CUSTODIANS = "numberCustodians";
protected ThresholdDefinedListener listener;
private int numberOfCustodians;
private int threshold;
private int recommendedThreshold;
private SeekBar seekBar;
private TextView thresholdRepresentation;
private TextView message;
private TextView mOfn;
public static ThresholdSelectorFragment newInstance(int numberCustodians) {
Bundle bundle = new Bundle();
bundle.putInt(NUMBER_CUSTODIANS, numberCustodians);
ThresholdSelectorFragment fragment = new ThresholdSelectorFragment();
fragment.setArguments(bundle);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requireActivity().setTitle(R.string.title_define_threshold);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_select_threshold,
container, false);
Bundle args = requireArguments();
numberOfCustodians = args.getInt(NUMBER_CUSTODIANS);
seekBar = view.findViewById(R.id.seekBar);
thresholdRepresentation =
view.findViewById(R.id.textViewThresholdRepresentation);
message = view.findViewById(R.id.textViewMessage);
mOfn = view.findViewById(R.id.textViewmOfn);
if (numberOfCustodians == 2) {
message.setText(R.string.threshold_too_few_custodians);
}
if (numberOfCustodians > 3) {
seekBar.setMax(numberOfCustodians -3);
seekBar.setProgress(threshold - 2);
seekBar.setOnSeekBarChangeListener(new SeekBarListener());
recommendedThreshold =
SecretSharingWrapper.defaultThreshold(numberOfCustodians);
threshold = recommendedThreshold;
} else {
seekBar.setEnabled(false);
threshold = 2;
seekBar.setMax(numberOfCustodians);
seekBar.setProgress(threshold);
TextView t = view.findViewById(R.id.title_threshold);
t.setText(R.string.threshold_disabled);
}
thresholdRepresentation.setText(buildThresholdRepresentationString());
setmOfnText();
return view;
// return super.onCreateView(inflater, container, savedInstanceState);
}
private void setmOfnText() {
mOfn.setText(String.format(
getString(R.string.threshold_m_of_n), threshold,
numberOfCustodians));
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
listener = (ThresholdDefinedListener) context;
}
@Override
public String getUniqueTag() {
return TAG;
}
@Override
public void injectFragment(ActivityComponent component) {
component.inject(this);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.define_threshold_actions, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_threshold_defined:
try {
listener.thresholdDefined(threshold);
} catch (DbException e) {
e.printStackTrace();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private String buildThresholdRepresentationString() {
String thresholdRepresentationText = "";
for (int i = 0; i < threshold; i++) {
thresholdRepresentationText += getString(R.string.filled_bullet);
}
for (int i = 0; i < (numberOfCustodians - threshold); i++) {
thresholdRepresentationText += getString(R.string.linear_bullet);
}
return thresholdRepresentationText;
}
private class SeekBarListener implements SeekBar.OnSeekBarChangeListener {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
threshold = progress + 2;
thresholdRepresentation.setText(
buildThresholdRepresentationString()
);
setmOfnText();
int sanityLevel = SecretSharingWrapper
.thresholdSanity(threshold, numberOfCustodians);
int text = R.string.threshold_secure;
if (threshold == recommendedThreshold)
text = R.string.threshold_recommended;
if (sanityLevel < -1) text = R.string.threshold_low_insecure;
if (sanityLevel > 0) text = R.string.threshold_high_insecure;
message.setText(text);
// TODO change colour of thresholdRepresentation to green/red based on sanityLevel
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// do nothing
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// do nothing
}
}
}

View File

@@ -0,0 +1,26 @@
package org.briarproject.briar.android.socialbackup.creation;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.db.DbException;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.sync.GroupId;
import org.briarproject.briar.android.contactselection.ContactSelectorController;
import org.briarproject.briar.android.contactselection.SelectableContactItem;
import org.briarproject.briar.android.controller.handler.ResultExceptionHandler;
import java.util.Collection;
import androidx.annotation.Nullable;
@NotNullByDefault
public interface CreateBackupController
extends ContactSelectorController<SelectableContactItem> {
void createGroup(String name,
ResultExceptionHandler<GroupId, DbException> result);
void sendInvitation(GroupId g, Collection<ContactId> contacts,
@Nullable String text,
ResultExceptionHandler<Void, DbException> result);
}

View File

@@ -0,0 +1,206 @@
package org.briarproject.briar.android.socialbackup.creation;
import org.briarproject.bramble.api.contact.Contact;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.contact.ContactManager;
import org.briarproject.bramble.api.crypto.CryptoExecutor;
import org.briarproject.bramble.api.db.DatabaseExecutor;
import org.briarproject.bramble.api.db.DbException;
import org.briarproject.bramble.api.db.NoSuchContactException;
import org.briarproject.bramble.api.identity.IdentityManager;
import org.briarproject.bramble.api.identity.LocalAuthor;
import org.briarproject.bramble.api.lifecycle.LifecycleManager;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.sync.GroupId;
import org.briarproject.bramble.api.system.Clock;
import org.briarproject.briar.android.contactselection.ContactSelectorControllerImpl;
import org.briarproject.briar.android.controller.handler.ResultExceptionHandler;
import org.briarproject.briar.api.identity.AuthorManager;
import org.briarproject.briar.api.privategroup.GroupMessage;
import org.briarproject.briar.api.privategroup.GroupMessageFactory;
import org.briarproject.briar.api.privategroup.PrivateGroup;
import org.briarproject.briar.api.privategroup.PrivateGroupFactory;
import org.briarproject.briar.api.privategroup.PrivateGroupManager;
import org.briarproject.briar.api.privategroup.invitation.GroupInvitationFactory;
import org.briarproject.briar.api.privategroup.invitation.GroupInvitationManager;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.logging.Logger;
import javax.annotation.concurrent.Immutable;
import javax.inject.Inject;
import androidx.annotation.Nullable;
import static java.util.logging.Level.WARNING;
import static org.briarproject.bramble.util.LogUtils.logException;
@Immutable
@NotNullByDefault
/**
* Derived from {@link org.briarproject.briar.android.privategroup.invitation.GroupInvitationControllerImpl}
*/
class CreateBackupControllerImpl extends ContactSelectorControllerImpl
implements CreateBackupController {
private static final Logger LOG =
Logger.getLogger(
CreateBackupControllerImpl.class.getName());
private final Executor cryptoExecutor;
private final ContactManager contactManager;
private final IdentityManager identityManager;
private final PrivateGroupFactory groupFactory;
private final GroupMessageFactory groupMessageFactory;
private final PrivateGroupManager groupManager;
private final GroupInvitationFactory groupInvitationFactory;
private final GroupInvitationManager groupInvitationManager;
private final Clock clock;
@Inject
CreateBackupControllerImpl(@DatabaseExecutor Executor dbExecutor,
@CryptoExecutor Executor cryptoExecutor,
LifecycleManager lifecycleManager, ContactManager contactManager,
IdentityManager identityManager, PrivateGroupFactory groupFactory,
GroupMessageFactory groupMessageFactory,
PrivateGroupManager groupManager,
GroupInvitationFactory groupInvitationFactory,
GroupInvitationManager groupInvitationManager, Clock clock, AuthorManager authorManager) {
super(dbExecutor, lifecycleManager, contactManager, authorManager);
this.cryptoExecutor = cryptoExecutor;
this.contactManager = contactManager;
this.identityManager = identityManager;
this.groupFactory = groupFactory;
this.groupMessageFactory = groupMessageFactory;
this.groupManager = groupManager;
this.groupInvitationFactory = groupInvitationFactory;
this.groupInvitationManager = groupInvitationManager;
this.clock = clock;
}
@Override
public void createGroup(String name,
ResultExceptionHandler<GroupId, DbException> handler) {
runOnDbThread(() -> {
try {
LocalAuthor author = identityManager.getLocalAuthor();
createGroupAndMessages(author, name, handler);
} catch (DbException e) {
logException(LOG, WARNING, e);
handler.onException(e);
}
});
}
private void createGroupAndMessages(LocalAuthor author, String name,
ResultExceptionHandler<GroupId, DbException> handler) {
cryptoExecutor.execute(() -> {
LOG.info("Creating group...");
PrivateGroup group =
groupFactory.createPrivateGroup(name, author);
LOG.info("Creating new join announcement...");
GroupMessage joinMsg =
groupMessageFactory.createJoinMessage(group.getId(),
clock.currentTimeMillis(), author);
storeGroup(group, joinMsg, handler);
});
}
private void storeGroup(PrivateGroup group, GroupMessage joinMsg,
ResultExceptionHandler<GroupId, DbException> handler) {
runOnDbThread(() -> {
LOG.info("Adding group to database...");
try {
groupManager.addPrivateGroup(group, joinMsg, true);
handler.onResult(group.getId());
} catch (DbException e) {
logException(LOG, WARNING, e);
handler.onException(e);
}
});
}
@Override
protected boolean isDisabled(GroupId g, Contact c) {
return false;
}
@Override
public void sendInvitation(GroupId g, Collection<ContactId> contactIds,
@Nullable String text,
ResultExceptionHandler<Void, DbException> handler) {
runOnDbThread(() -> {
try {
LocalAuthor localAuthor = identityManager.getLocalAuthor();
List<Contact> contacts = new ArrayList<>();
for (ContactId c : contactIds) {
try {
contacts.add(contactManager.getContact(c));
} catch (NoSuchContactException e) {
// Continue
}
}
signInvitations(g, localAuthor, contacts, text, handler);
} catch (DbException e) {
logException(LOG, WARNING, e);
handler.onException(e);
}
});
}
private void signInvitations(GroupId g, LocalAuthor localAuthor,
Collection<Contact> contacts, @Nullable String text,
ResultExceptionHandler<Void, DbException> handler) {
cryptoExecutor.execute(() -> {
long timestamp = clock.currentTimeMillis();
List<InvitationContext> contexts = new ArrayList<>();
for (Contact c : contacts) {
byte[] signature = groupInvitationFactory.signInvitation(c, g,
timestamp, localAuthor.getPrivateKey());
contexts.add(new InvitationContext(c.getId(), timestamp,
signature));
}
sendInvitations(g, contexts, text, handler);
});
}
private void sendInvitations(GroupId g,
Collection<InvitationContext> contexts, @Nullable String text,
ResultExceptionHandler<Void, DbException> handler) {
runOnDbThread(() -> {
try {
for (InvitationContext context : contexts) {
try {
groupInvitationManager.sendInvitation(g,
context.contactId, text, context.timestamp,
context.signature);
} catch (NoSuchContactException e) {
// Continue
}
}
//noinspection ConstantConditions
handler.onResult(null);
} catch (DbException e) {
logException(LOG, WARNING, e);
handler.onException(e);
}
});
}
private static class InvitationContext {
private final ContactId contactId;
private final long timestamp;
private final byte[] signature;
private InvitationContext(ContactId contactId, long timestamp,
byte[] signature) {
this.contactId = contactId;
this.timestamp = timestamp;
this.signature = signature;
}
}
}

View File

@@ -0,0 +1,18 @@
package org.briarproject.briar.android.socialbackup.creation;
import org.briarproject.briar.android.activity.ActivityScope;
import dagger.Module;
import dagger.Provides;
@Module
public class CreateBackupModule {
@ActivityScope
@Provides
CreateBackupController provideCreateGroupController(
CreateBackupControllerImpl createBackupController) {
return createBackupController;
}
}

View File

@@ -0,0 +1,59 @@
package org.briarproject.briar.android.socialbackup.recover;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import org.briarproject.briar.R;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.fragment.BaseFragment;
import javax.inject.Inject;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
public class CustodianRecoveryModeExplainerFragment extends BaseFragment {
@Inject
ViewModelProvider.Factory viewModelFactory;
private CustodianReturnShardViewModel viewModel;
public static final String TAG =
CustodianRecoveryModeExplainerFragment.class.getName();
@Override
public void injectFragment(ActivityComponent component) {
component.inject(this);
viewModel = new ViewModelProvider(requireActivity(), viewModelFactory)
.get(CustodianReturnShardViewModel.class);
}
// @Override
// public void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// requireActivity().setTitle(R.string.title_help_recover);
// }
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable
ViewGroup container, @Nullable Bundle savedInstanceState) {
View view =
inflater.inflate(R.layout.fragment_recovery_custodian_explainer,
container, false);
Button button = view.findViewById(R.id.button);
button.setOnClickListener(e -> viewModel.onContinueClicked());
return view;
}
@Override
public String getUniqueTag() {
return TAG;
}
}

View File

@@ -0,0 +1,135 @@
package org.briarproject.briar.android.socialbackup.recover;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.db.DbException;
import org.briarproject.briar.R;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.activity.BriarActivity;
import org.briarproject.briar.android.fragment.BaseFragment;
import org.briarproject.briar.api.socialbackup.recovery.CustodianTask;
import java.io.IOException;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.inject.Inject;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.ViewModelProvider;
import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.briar.android.conversation.ConversationActivity.CONTACT_ID;
public class CustodianReturnShardActivity extends BriarActivity
implements BaseFragment.BaseFragmentListener {
private CustodianReturnShardViewModel viewModel;
private static final Logger LOG =
getLogger(CustodianReturnShardActivity.class.getName());
private ContactId contactId;
@Inject
ViewModelProvider.Factory viewModelFactory;
@Override
public void injectActivity(ActivityComponent component) {
component.inject(this);
viewModel = new ViewModelProvider(this, viewModelFactory)
.get(CustodianReturnShardViewModel.class);
}
@Override
public void onCreate(@Nullable Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_fragment_container);
if (state == null) {
Intent intent = getIntent();
int id = intent.getIntExtra(CONTACT_ID, -1);
if (id == -1) throw new IllegalStateException("No ContactId");
contactId = new ContactId(id);
try {
viewModel.start(contactId);
// } catch (IOException e) {
// // TODO improve this
// Toast.makeText(this,
// "It looks like you are not connected to a Wifi network",
// Toast.LENGTH_SHORT).show();
// showInitialFragment(new CustodianReturnShardErrorFragment());
} catch (DbException e) {
Toast.makeText(this,
"You do not hold a backup piece for this contact",
Toast.LENGTH_SHORT).show();
finish();
}
}
showInitialFragment(new CustodianRecoveryModeExplainerFragment());
viewModel.getContinueClicked().observeEvent(this, clicked -> {
if (clicked) beginTransfer();
});
viewModel.getShowCameraFragment().observeEvent(this, show -> {
if (show) showCameraFragment();
});
viewModel.getSuccessDismissed().observeEvent(this, dismissed -> {
if (dismissed) finish();
});
viewModel.getErrorTryAgain().observeEvent(this, tryAgain -> {
if (tryAgain) beginTransfer();
});
viewModel.getState()
.observe(this, this::onReturnShardStateChanged);
}
private void beginTransfer() {
try {
viewModel.beginTransfer();
} catch (IOException e) {
Toast.makeText(this,
"It looks like you are not connected to a Wifi network",
Toast.LENGTH_SHORT).show();
FragmentManager fm = getSupportFragmentManager();
if (fm.findFragmentByTag(CustodianReturnShardFragment.TAG) == null) {
BaseFragment f = new CustodianReturnShardErrorFragment();
fm.beginTransaction()
.replace(R.id.fragmentContainer, f, f.getUniqueTag())
.addToBackStack(f.getUniqueTag())
.commit();
}
}
}
private void onReturnShardStateChanged(CustodianTask.State state) {
if (state instanceof CustodianTask.State.Success) {
CustodianReturnShardSuccessFragment fragment = new CustodianReturnShardSuccessFragment();
showNextFragment(fragment);
} else if (state instanceof CustodianTask.State.Failure) {
// TODO error fragment here
// TODO handle reason
Toast.makeText(this,
"Backup piece transfer failed",
Toast.LENGTH_SHORT).show();
finish();
}
}
private void showCameraFragment() {
// FIXME #824
FragmentManager fm = getSupportFragmentManager();
if (fm.findFragmentByTag(CustodianReturnShardFragment.TAG) == null) {
BaseFragment f = CustodianReturnShardFragment.newInstance();
fm.beginTransaction()
.replace(R.id.fragmentContainer, f, f.getUniqueTag())
.addToBackStack(f.getUniqueTag())
.commit();
}
}
}

View File

@@ -0,0 +1,57 @@
package org.briarproject.briar.android.socialbackup.recover;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
import org.briarproject.briar.R;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.fragment.BaseFragment;
import javax.inject.Inject;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
@MethodsNotNullByDefault
@ParametersNotNullByDefault
public class CustodianReturnShardErrorFragment extends BaseFragment {
public static final String TAG =
CustodianReturnShardErrorFragment.class.getName();
@Inject
ViewModelProvider.Factory viewModelFactory;
private CustodianReturnShardViewModel viewModel;
@Override
public void injectFragment(ActivityComponent component) {
component.inject(this);
viewModel = new ViewModelProvider(requireActivity(), viewModelFactory)
.get(CustodianReturnShardViewModel.class);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recovery_custodian_error_explainer,
container, false);
Button button = view.findViewById(R.id.button);
button.setOnClickListener(e -> viewModel.onErrorTryAgain());
// TODO cancel button
// button.setOnClickListener(e -> viewModel.onErrorCancelled());
return view;
}
@Override
public String getUniqueTag() {
return TAG;
}
}

View File

@@ -0,0 +1,193 @@
package org.briarproject.briar.android.socialbackup.recover;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
import org.briarproject.briar.R;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.contact.add.nearby.CameraException;
import org.briarproject.briar.android.contact.add.nearby.CameraView;
import org.briarproject.briar.android.fragment.BaseFragment;
import org.briarproject.briar.android.view.QrCodeView;
import org.briarproject.briar.api.socialbackup.recovery.CustodianTask;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.inject.Inject;
import androidx.annotation.UiThread;
import androidx.lifecycle.ViewModelProvider;
import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.widget.LinearLayout.HORIZONTAL;
import static android.widget.Toast.LENGTH_LONG;
import static java.util.logging.Level.WARNING;
import static org.briarproject.bramble.util.LogUtils.logException;
@MethodsNotNullByDefault
@ParametersNotNullByDefault
public class CustodianReturnShardFragment extends BaseFragment
implements QrCodeView.FullscreenListener {
public static final String TAG = CustodianReturnShardFragment.class.getName();
private static final Logger LOG = Logger.getLogger(TAG);
@Inject
ViewModelProvider.Factory viewModelFactory;
private CustodianReturnShardViewModel viewModel;
private CameraView cameraView;
private LinearLayout cameraOverlay;
private View statusView;
private TextView status;
public static CustodianReturnShardFragment newInstance() {
Bundle args = new Bundle();
CustodianReturnShardFragment fragment = new CustodianReturnShardFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void injectFragment(ActivityComponent component) {
component.inject(this);
viewModel = new ViewModelProvider(requireActivity(), viewModelFactory)
.get(CustodianReturnShardViewModel.class);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_keyagreement_qr, container,
false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
cameraView = view.findViewById(R.id.camera_view);
cameraOverlay = view.findViewById(R.id.camera_overlay);
statusView = view.findViewById(R.id.status_container);
status = view.findViewById(R.id.connect_status);
viewModel.getState().observe(getViewLifecycleOwner(),
this::onReturnShardStateChanged);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
requireActivity().setRequestedOrientation(SCREEN_ORIENTATION_NOSENSOR);
cameraView.setPreviewConsumer(viewModel.getQrCodeDecoder());
}
@Override
public void onStart() {
super.onStart();
try {
cameraView.start();
} catch (CameraException e) {
logCameraExceptionAndFinish(e);
}
}
@Override
public void onStop() {
super.onStop();
try {
cameraView.stop();
} catch (CameraException e) {
logCameraExceptionAndFinish(e);
}
}
@Override
public void onDestroy() {
requireActivity()
.setRequestedOrientation(SCREEN_ORIENTATION_UNSPECIFIED);
super.onDestroy();
}
@Override
public void setFullscreen(boolean fullscreen) {
LinearLayout.LayoutParams statusParams, qrCodeParams;
if (fullscreen) {
statusParams = new LinearLayout.LayoutParams(0, 0, 0f);
} else {
if (cameraOverlay.getOrientation() == HORIZONTAL) {
statusParams = new LinearLayout.LayoutParams(0, MATCH_PARENT, 1f);
} else {
statusParams = new LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f);
}
}
statusView.setLayoutParams(statusParams);
cameraOverlay.invalidate();
}
@UiThread
private void onReturnShardStateChanged(@Nullable CustodianTask.State state) {
LOG.info("State changed");
// if (state instanceof CustodianTask.State.Connecting) {
// try {
// cameraView.stop();
// } catch (CameraException e) {
// logCameraExceptionAndFinish(e);
// }
// cameraView.setVisibility(INVISIBLE);
// statusView.setVisibility(VISIBLE);
// status.setText(R.string.connecting_to_device);
if (state instanceof CustodianTask.State.SendingShard) {
try {
cameraView.stop();
} catch (CameraException e) {
logCameraExceptionAndFinish(e);
}
cameraView.setVisibility(INVISIBLE);
statusView.setVisibility(VISIBLE);
status.setText("Sending shard");
} else if (state instanceof CustodianTask.State.ReceivingAck) {
status.setText("Receiving Ack");
} else if (state instanceof CustodianTask.State.Success) {
// TODO
status.setText(R.string.exchanging_contact_details);
} else if (state instanceof CustodianTask.State.Failure) {
// the activity will replace this fragment with an error fragment
statusView.setVisibility(INVISIBLE);
cameraView.setVisibility(INVISIBLE);
}
}
@Override
public String getUniqueTag() {
return TAG;
}
@UiThread
private void logCameraExceptionAndFinish(CameraException e) {
logException(LOG, WARNING, e);
Toast.makeText(getActivity(), R.string.camera_error,
LENGTH_LONG).show();
finish();
}
@Override
protected void finish() {
requireActivity().getSupportFragmentManager().popBackStack();
}
}

View File

@@ -0,0 +1,19 @@
package org.briarproject.briar.android.socialbackup.recover;
import org.briarproject.briar.android.viewmodel.ViewModelKey;
import androidx.lifecycle.ViewModel;
import dagger.Binds;
import dagger.Module;
import dagger.multibindings.IntoMap;
@Module
public abstract class CustodianReturnShardModule {
@Binds
@IntoMap
@ViewModelKey(CustodianReturnShardViewModel.class)
abstract ViewModel bindCustodianReturnShardViewModel(
CustodianReturnShardViewModel custodianReturnShardViewModel);
}

View File

@@ -0,0 +1,59 @@
package org.briarproject.briar.android.socialbackup.recover;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
import org.briarproject.briar.R;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.fragment.BaseFragment;
import javax.inject.Inject;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
@MethodsNotNullByDefault
@ParametersNotNullByDefault
public class CustodianReturnShardSuccessFragment extends
BaseFragment {
public static final String TAG =
CustodianReturnShardFragment.class.getName();
@Inject
ViewModelProvider.Factory viewModelFactory;
private CustodianReturnShardViewModel viewModel;
@Override
public void injectFragment(ActivityComponent component) {
component.inject(this);
viewModel = new ViewModelProvider(requireActivity(), viewModelFactory)
.get(CustodianReturnShardViewModel.class);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recovery_custodian_done,
container, false);
Button button = view.findViewById(R.id.button);
button.setOnClickListener(e -> viewModel.onSuccessDismissed());
return view;
}
@Override
public String getUniqueTag() {
return TAG;
}
}

View File

@@ -0,0 +1,208 @@
package org.briarproject.briar.android.socialbackup.recover;
import android.app.Application;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.widget.Toast;
import com.google.zxing.Result;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.db.DatabaseComponent;
import org.briarproject.bramble.api.db.DbException;
import org.briarproject.bramble.api.lifecycle.IoExecutor;
import org.briarproject.bramble.api.system.AndroidExecutor;
import org.briarproject.briar.R;
import org.briarproject.briar.android.contact.add.nearby.QrCodeDecoder;
import org.briarproject.briar.android.viewmodel.LiveEvent;
import org.briarproject.briar.android.viewmodel.MutableLiveEvent;
import org.briarproject.briar.api.socialbackup.SocialBackupManager;
import org.briarproject.briar.api.socialbackup.recovery.CustodianTask;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.concurrent.Executor;
import java.util.logging.Logger;
import javax.inject.Inject;
import androidx.annotation.NonNull;
import androidx.annotation.UiThread;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import static android.content.Context.WIFI_SERVICE;
import static android.widget.Toast.LENGTH_LONG;
import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
public class CustodianReturnShardViewModel extends AndroidViewModel
implements QrCodeDecoder.ResultCallback, CustodianTask.Observer {
private static final Logger LOG =
getLogger(CustodianReturnShardViewModel.class.getName());
private final AndroidExecutor androidExecutor;
private final Executor ioExecutor;
private final SocialBackupManager socialBackupManager;
private final DatabaseComponent db;
final QrCodeDecoder qrCodeDecoder;
private boolean qrCodeRead = false;
private WifiManager wifiManager;
private final MutableLiveEvent<Boolean > continueClicked = new MutableLiveEvent<>();
private final MutableLiveEvent<Boolean> showCameraFragment =
new MutableLiveEvent<>();
private final MutableLiveEvent<Boolean> successDismissed =
new MutableLiveEvent<>();
private final MutableLiveEvent<Boolean> errorTryAgain = new MutableLiveEvent<>();
private final MutableLiveData<CustodianTask.State> state =
new MutableLiveData<>();
private final CustodianTask task;
private byte[] returnShardPayloadBytes;
@SuppressWarnings("CharsetObjectCanBeUsed") // Requires minSdkVersion >= 19
private static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
@Inject
public CustodianReturnShardViewModel(
@NonNull Application app,
@IoExecutor Executor ioExecutor,
SocialBackupManager socialBackupManager,
DatabaseComponent db,
CustodianTask task,
AndroidExecutor androidExecutor) {
super(app);
this.androidExecutor = androidExecutor;
this.ioExecutor = ioExecutor;
this.socialBackupManager = socialBackupManager;
this.db = db;
this.task = task;
qrCodeDecoder = new QrCodeDecoder(androidExecutor, ioExecutor, this);
wifiManager = (WifiManager) app.getSystemService(WIFI_SERVICE);
}
private InetAddress getWifiIpv4Address() {
if (wifiManager == null) return null;
// If we're connected to a wifi network, return its address
WifiInfo info = wifiManager.getConnectionInfo();
if (info != null && info.getIpAddress() != 0) {
return intToInetAddress(info.getIpAddress());
}
return null;
}
// TODO this is not the right place for this
private InetAddress intToInetAddress(int ip) {
byte[] ipBytes = new byte[4];
ipBytes[0] = (byte) (ip & 0xFF);
ipBytes[1] = (byte) ((ip >> 8) & 0xFF);
ipBytes[2] = (byte) ((ip >> 16) & 0xFF);
ipBytes[3] = (byte) ((ip >> 24) & 0xFF);
try {
return InetAddress.getByAddress(ipBytes);
} catch (UnknownHostException e) {
// Should only be thrown if address has illegal length
throw new AssertionError(e);
}
}
public void start(ContactId contactId) throws DbException {
// TODO this should be transactionWithResult
db.transaction(false, txn -> {
if (!socialBackupManager.amCustodian(txn, contactId)) {
throw new DbException();
}
returnShardPayloadBytes = socialBackupManager
.getReturnShardPayloadBytes(txn, contactId);
});
}
@IoExecutor
@Override
public void onQrCodeDecoded(Result result) {
LOG.info("Got result from decoder");
if (qrCodeRead) return;
qrCodeRead = true;
try {
byte[] payloadBytes = result.getText().getBytes(ISO_8859_1);
if (LOG.isLoggable(INFO))
LOG.info("Remote payload is " + payloadBytes.length + " bytes");
ioExecutor.execute(() -> {
task.qrCodeDecoded(payloadBytes);
});
} catch (IllegalArgumentException e) {
LOG.log(WARNING, "QR Code Invalid", e);
androidExecutor.runOnUiThread(() -> Toast.makeText(getApplication(),
R.string.qr_code_invalid, LENGTH_LONG).show());
ioExecutor.execute(() -> {
task.qrCodeDecoded(null);
});
}
}
public void beginTransfer() throws IOException {
InetAddress inetAddress = getWifiIpv4Address();
LOG.info("Client InetAddress: " + inetAddress);
if (inetAddress == null)
throw new IOException("Cannot get IP on local wifi");
task.cancel();
task.start(this, returnShardPayloadBytes);
//TODO camera permissions
showCameraFragment.setEvent(true);
}
@UiThread
public void onContinueClicked() {
continueClicked.setEvent(true);
// checkPermissions.setEvent(true);
}
@UiThread
public void onErrorCancelled() {
errorTryAgain.postEvent(false);
}
@UiThread
public void onErrorTryAgain() {
errorTryAgain.postEvent(true);
}
@UiThread
public void onSuccessDismissed() {
successDismissed.setEvent(true);
}
QrCodeDecoder getQrCodeDecoder() {
return qrCodeDecoder;
}
LiveEvent<Boolean> getShowCameraFragment() {
return showCameraFragment;
}
LiveEvent<Boolean> getSuccessDismissed() {
return successDismissed;
}
LiveData<CustodianTask.State> getState() {
return state;
}
@Override
public void onStateChanged(CustodianTask.State state) {
this.state.postValue(state);
// Connecting, SendingShard, ReceivingAck, Success, Failure
}
public MutableLiveEvent<Boolean> getErrorTryAgain() {
return errorTryAgain;
}
public MutableLiveEvent<Boolean> getContinueClicked() { return continueClicked; }
}

View File

@@ -0,0 +1,57 @@
package org.briarproject.briar.android.socialbackup.recover;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
import org.briarproject.briar.R;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.fragment.BaseFragment;
import javax.inject.Inject;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
@MethodsNotNullByDefault
@ParametersNotNullByDefault
public class OwnerRecoveryModeErrorFragment extends BaseFragment {
public static final String TAG =
OwnerRecoveryModeErrorFragment.class.getName();
@Inject
ViewModelProvider.Factory viewModelFactory;
private OwnerReturnShardViewModel viewModel;
@Override
public void injectFragment(ActivityComponent component) {
component.inject(this);
viewModel = new ViewModelProvider(requireActivity(), viewModelFactory)
.get(OwnerReturnShardViewModel.class);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recovery_custodian_error_explainer,
container, false);
Button button = view.findViewById(R.id.button);
button.setOnClickListener(e -> viewModel.onErrorTryAgain());
// TODO cancel button
// button.setOnClickListener(e -> viewModel.onErrorCancelled());
return view;
}
@Override
public String getUniqueTag() {
return TAG;
}
}

View File

@@ -0,0 +1,58 @@
package org.briarproject.briar.android.socialbackup.recover;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import org.briarproject.briar.R;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.fragment.BaseFragment;
import javax.inject.Inject;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
public class OwnerRecoveryModeExplainerFragment extends BaseFragment {
public static final String TAG =
OwnerRecoveryModeExplainerFragment.class.getName();
@Inject
ViewModelProvider.Factory viewModelFactory;
private OwnerReturnShardViewModel viewModel;
// @Override
// public void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// requireActivity().setTitle(R.string.title_recovery_mode);
// }
@Override
public void injectFragment(ActivityComponent component) {
component.inject(this);
viewModel = new ViewModelProvider(requireActivity(), viewModelFactory)
.get(OwnerReturnShardViewModel.class);
}
@Override
public String getUniqueTag() { return TAG; }
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recovery_owner_explainer,
container, false);
Button button = view.findViewById(R.id.beginButton);
button.setOnClickListener(e -> viewModel.onStartClicked());
return view;
}
}

View File

@@ -0,0 +1,69 @@
package org.briarproject.briar.android.socialbackup.recover;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import org.briarproject.briar.R;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.fragment.BaseFragment;
import org.briarproject.briar.android.socialbackup.ScanQrButtonListener;
import javax.inject.Inject;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
public class OwnerRecoveryModeMainFragment extends BaseFragment {
public static final String NUM_RECOVERED = "num_recovered";
public static final String TAG =
OwnerRecoveryModeMainFragment.class.getName();
@Inject
ViewModelProvider.Factory viewModelFactory;
private OwnerReturnShardViewModel viewModel;
@Override
public void injectFragment(ActivityComponent component) {
component.inject(this);
viewModel = new ViewModelProvider(requireActivity(), viewModelFactory)
.get(OwnerReturnShardViewModel.class);
}
@Override
public String getUniqueTag() {
return TAG;
}
// @Override
// public void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// requireActivity().setTitle(R.string.title_recovery_mode);
//
// Bundle args = requireArguments();
// }
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recovery_owner_main,
container, false);
TextView textViewCount = view.findViewById(R.id.textViewShardCount);
textViewCount.setText(String.format("%d", viewModel.getNumberOfShards()));
Button button = view.findViewById(R.id.button);
button.setOnClickListener(e -> viewModel.onContinueClicked());
return view;
}
}

View File

@@ -0,0 +1,193 @@
package org.briarproject.briar.android.socialbackup.recover;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
import org.briarproject.bramble.api.FormatException;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
import org.briarproject.briar.R;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.activity.BaseActivity;
import org.briarproject.briar.android.fragment.BaseFragment;
import org.briarproject.briar.api.socialbackup.ReturnShardPayload;
import org.briarproject.briar.api.socialbackup.recovery.RestoreAccount;
import org.briarproject.briar.api.socialbackup.recovery.SecretOwnerTask;
import java.security.GeneralSecurityException;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.inject.Inject;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.ViewModelProvider;
import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK;
import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
import static java.util.logging.Logger.getLogger;
@MethodsNotNullByDefault
@ParametersNotNullByDefault
public class OwnerReturnShardActivity extends BaseActivity
implements BaseFragment.BaseFragmentListener {
private static final Logger LOG =
getLogger(OwnerReturnShardActivity.class.getName());
@Inject
ViewModelProvider.Factory viewModelFactory;
private OwnerReturnShardViewModel viewModel;
// private final ActivityResultLauncher<String[]> permissionLauncher =
// registerForActivityResult(
// new ActivityResultContracts.RequestMultiplePermissions(),
// r ->
// permissionManager.onRequestPermissionResult(r,
// viewModel::showQrCodeFragmentIfAllowed));
@Override
public void injectActivity(ActivityComponent component) {
component.inject(this);
viewModel = new ViewModelProvider(this, viewModelFactory)
.get(OwnerReturnShardViewModel.class);
}
@Override
public void onCreate(@Nullable Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_fragment_container);
if (state == null) {
showInitialFragment(new OwnerRecoveryModeExplainerFragment());
}
viewModel.getShowQrCodeFragment().observeEvent(this, show -> {
if (show) {
LOG.info("Show QR code clicked");
viewModel.startListening();
showQrCodeFragment();
}
});
viewModel.getStartClicked().observeEvent(this, start -> {
if (start) {
showNextFragment(new OwnerRecoveryModeMainFragment());
}
});
viewModel.getSuccessDismissed().observeEvent(this, success -> {
if (success) onSuccessDismissed();
});
viewModel.getErrorTryAgain().observeEvent(this, tryAgain -> {
if (tryAgain) {
viewModel.startListening();
showQrCodeFragment();
}
});
viewModel.getState()
.observe(this, this::onReturnShardStateChanged);
}
@Override
public void onStart() {
super.onStart();
}
@Override
protected void onPostResume() {
super.onPostResume();
// viewModel.setIsActivityResumed(true);
}
@Override
protected void onPause() {
super.onPause();
// viewModel.setIsActivityResumed(false);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
// TODO should we cancel the return shard task here?
super.onBackPressed();
}
private void showQrCodeFragment() {
LOG.info("showQrCodeFragment called");
FragmentManager fm = getSupportFragmentManager();
if (fm.findFragmentByTag(OwnerReturnShardFragment.TAG) == null) {
BaseFragment f = OwnerReturnShardFragment.newInstance();
fm.beginTransaction()
.replace(R.id.fragmentContainer, f, f.getUniqueTag())
.addToBackStack(f.getUniqueTag())
.commit();
}
}
private void onSuccessDismissed() {
finish();
Intent i = new Intent(this, RestoreAccountActivity.class);
i.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TOP |
FLAG_ACTIVITY_CLEAR_TASK | FLAG_ACTIVITY_TASK_ON_HOME);
startActivity(i);
}
private void onReturnShardStateChanged(SecretOwnerTask.State state) {
if (state instanceof SecretOwnerTask.State.Success) {
ReturnShardPayload shardPayload =
((SecretOwnerTask.State.Success) state).getRemotePayload();
RestoreAccount.AddReturnShardPayloadResult result = viewModel.addToShardSet(shardPayload);
if (result == RestoreAccount.AddReturnShardPayloadResult.MISMATCH) {
// TODO improve this
Toast.makeText(this,
"WARNING: Mismatched backup piece!",
Toast.LENGTH_LONG).show();
}
boolean added = (result != RestoreAccount.AddReturnShardPayloadResult.DUPLICATE) ? true : false;
Toast.makeText(this,
"Success - got backup piece" + (added ? "" : " duplicate"),
Toast.LENGTH_SHORT).show();
if (added && viewModel.canRecover()) {
LOG.info("Secret key recovered");
try {
viewModel.recover();
} catch (GeneralSecurityException e) {
LOG.warning("Unable to decrypt backup" + e.toString());
Toast.makeText(this,
"Unable to decrypt backup",
Toast.LENGTH_LONG).show();
return;
} catch (FormatException e) {
LOG.warning("Unable to parse backup" + e.getMessage() +
e.getStackTrace().toString());
Toast.makeText(this,
"Unable to parse backup",
Toast.LENGTH_LONG).show();
return;
}
showNextFragment(new OwnerReturnShardSuccessFragment());
return;
}
onBackPressed();
} else if (state instanceof SecretOwnerTask.State.Failure) {
showNextFragment(new OwnerRecoveryModeErrorFragment());
}
}
@Override
@Deprecated
public void runOnDbThread(Runnable runnable) {
throw new RuntimeException("Don't use this deprecated method here.");
}
}

View File

@@ -0,0 +1,162 @@
package org.briarproject.briar.android.socialbackup.recover;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
import org.briarproject.briar.R;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.fragment.BaseFragment;
import org.briarproject.briar.android.view.QrCodeView;
import org.briarproject.briar.api.socialbackup.recovery.SecretOwnerTask;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.inject.Inject;
import androidx.annotation.UiThread;
import androidx.lifecycle.ViewModelProvider;
import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.widget.LinearLayout.HORIZONTAL;
@MethodsNotNullByDefault
@ParametersNotNullByDefault
public class OwnerReturnShardFragment extends BaseFragment
implements QrCodeView.FullscreenListener {
public static final String TAG = OwnerReturnShardFragment.class.getName();
private static final Logger LOG = Logger.getLogger(TAG);
@Inject
ViewModelProvider.Factory viewModelFactory;
private OwnerReturnShardViewModel viewModel;
private LinearLayout cameraOverlay;
private View statusView;
private QrCodeView qrCodeView;
private TextView status;
public static OwnerReturnShardFragment newInstance() {
Bundle args = new Bundle();
OwnerReturnShardFragment fragment = new OwnerReturnShardFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void injectFragment(ActivityComponent component) {
component.inject(this);
viewModel = new ViewModelProvider(requireActivity(), viewModelFactory)
.get(OwnerReturnShardViewModel.class);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_recovery_owner_qr, container,
false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
cameraOverlay = view.findViewById(R.id.camera_overlay);
statusView = view.findViewById(R.id.status_container);
status = view.findViewById(R.id.connect_status);
qrCodeView = view.findViewById(R.id.qr_code_view);
qrCodeView.setFullscreenListener(this);
viewModel.getState().observe(getViewLifecycleOwner(),
this::onReturnShardStateChanged);
Bitmap qrCodeBitmap = viewModel.getQrCodeBitmap();
if (qrCodeBitmap != null) {
qrCodeView.setQrCode(qrCodeBitmap);
}
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
requireActivity().setRequestedOrientation(SCREEN_ORIENTATION_NOSENSOR);
}
@Override
public void onDestroy() {
requireActivity()
.setRequestedOrientation(SCREEN_ORIENTATION_UNSPECIFIED);
super.onDestroy();
}
@Override
public void setFullscreen(boolean fullscreen) {
LinearLayout.LayoutParams statusParams, qrCodeParams;
if (fullscreen) {
// Grow the QR code view to fill its parent
statusParams = new LinearLayout.LayoutParams(0, 0, 0f);
qrCodeParams =
new LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT,
1f);
} else {
// Shrink the QR code view to fill half its parent
if (cameraOverlay.getOrientation() == HORIZONTAL) {
statusParams =
new LinearLayout.LayoutParams(0, MATCH_PARENT, 1f);
qrCodeParams =
new LinearLayout.LayoutParams(0, MATCH_PARENT, 1f);
} else {
statusParams =
new LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f);
qrCodeParams =
new LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f);
}
}
statusView.setLayoutParams(statusParams);
qrCodeView.setLayoutParams(qrCodeParams);
cameraOverlay.invalidate();
}
@UiThread
private void onReturnShardStateChanged(
@Nullable SecretOwnerTask.State state) {
if (state instanceof SecretOwnerTask.State.Listening) {
status.setText(R.string.waiting_for_contact_to_scan);
Bitmap qrCode = viewModel.getQrCodeBitmap();
qrCodeView.setQrCode(qrCode);
} else if (state instanceof SecretOwnerTask.State.ReceivingShard) {
status.setText(R.string.connecting_to_device);
} else if (state instanceof SecretOwnerTask.State.SendingAck) {
status.setText(R.string.recovery_sending_ack);
} else if (state instanceof SecretOwnerTask.State.Success) {
status.setText("Success");
} else if (state instanceof SecretOwnerTask.State.Failure) {
// the activity will replace this fragment with an error fragment
statusView.setVisibility(INVISIBLE);
}
}
@Override
public String getUniqueTag() {
return TAG;
}
@Override
protected void finish() {
requireActivity().getSupportFragmentManager().popBackStack();
}
}

View File

@@ -0,0 +1,26 @@
package org.briarproject.briar.android.socialbackup.recover;
import org.briarproject.briar.android.viewmodel.ViewModelKey;
import org.briarproject.briar.api.socialbackup.recovery.RestoreAccount;
import androidx.lifecycle.ViewModel;
import dagger.Binds;
import dagger.Module;
import dagger.multibindings.IntoMap;
@Module
public abstract class OwnerReturnShardModule {
@Binds
@IntoMap
@ViewModelKey(OwnerReturnShardViewModel.class)
abstract ViewModel bindOwnerReturnShardViewModel(
OwnerReturnShardViewModel ownerReturnShardViewModel);
@Binds
@IntoMap
@ViewModelKey(RestoreAccountViewModel.class)
abstract ViewModel bindRestoreAccountViewModel(
RestoreAccountViewModel restoreAccountViewModel);
}

View File

@@ -0,0 +1,54 @@
package org.briarproject.briar.android.socialbackup.recover;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import org.briarproject.briar.R;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.fragment.BaseFragment;
import javax.inject.Inject;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
public class OwnerReturnShardSuccessFragment extends BaseFragment {
public static final String TAG =
OwnerReturnShardSuccessFragment.class.getName();
@Inject
ViewModelProvider.Factory viewModelFactory;
private OwnerReturnShardViewModel viewModel;
@Override
public void injectFragment(ActivityComponent component) {
component.inject(this);
viewModel = new ViewModelProvider(requireActivity(), viewModelFactory)
.get(OwnerReturnShardViewModel.class);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recovery_owner_success,
container, false);
Button button = view.findViewById(R.id.button);
button.setOnClickListener(e -> viewModel.onSuccessDismissed());
return view;
}
@Override
public String getUniqueTag() {
return TAG;
}
}

View File

@@ -0,0 +1,256 @@
package org.briarproject.briar.android.socialbackup.recover;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.DisplayMetrics;
import org.briarproject.bramble.api.FormatException;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.lifecycle.IoExecutor;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.system.AndroidExecutor;
import org.briarproject.briar.android.contact.add.nearby.QrCodeUtils;
import org.briarproject.briar.android.viewmodel.LiveEvent;
import org.briarproject.briar.android.viewmodel.MutableLiveEvent;
import org.briarproject.briar.api.socialbackup.MessageEncoder;
import org.briarproject.briar.api.socialbackup.ReturnShardPayload;
import org.briarproject.briar.api.socialbackup.recovery.RestoreAccount;
import org.briarproject.briar.api.socialbackup.recovery.SecretOwnerTask;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.util.HashSet;
import java.util.concurrent.Executor;
import java.util.logging.Logger;
import javax.inject.Inject;
import androidx.annotation.UiThread;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import static android.content.Context.WIFI_SERVICE;
import static java.util.logging.Level.INFO;
import static java.util.logging.Logger.getLogger;
@NotNullByDefault
class OwnerReturnShardViewModel extends AndroidViewModel
implements SecretOwnerTask.Observer {
private static final Logger LOG =
getLogger(OwnerReturnShardViewModel.class.getName());
@SuppressWarnings("CharsetObjectCanBeUsed") // Requires minSdkVersion >= 19
private static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
private final AndroidExecutor androidExecutor;
private final Executor ioExecutor;
private final SecretOwnerTask task;
private final RestoreAccount restoreAccount;
private final SharedPreferences prefs;
private final MutableLiveEvent<Boolean> errorTryAgain =
new MutableLiveEvent<>();
private final MutableLiveEvent<Boolean> showQrCodeFragment =
new MutableLiveEvent<>();
private final MutableLiveEvent<Boolean> successDismissed = new MutableLiveEvent<>();
private final MutableLiveData<SecretOwnerTask.State> state =
new MutableLiveData<>();
private final MutableLiveEvent<Boolean> startClicked =
new MutableLiveEvent<>();
private boolean wasContinueClicked = false;
private boolean isActivityResumed = false;
private Bitmap qrCodeBitmap;
private WifiManager wifiManager;
private SecretKey secretKey;
private final MessageEncoder messageEncoder;
@Inject
OwnerReturnShardViewModel(Application app,
AndroidExecutor androidExecutor,
SecretOwnerTask task,
RestoreAccount restoreAccount,
@IoExecutor Executor ioExecutor,
MessageEncoder messageEncoder) {
super(app);
this.androidExecutor = androidExecutor;
this.ioExecutor = ioExecutor;
this.restoreAccount = restoreAccount;
this.messageEncoder = messageEncoder;
this.task = task;
this.prefs = app.getSharedPreferences("account-recovery",
Context.MODE_PRIVATE);
restoreAccount.restoreFromPrevious(prefs.getStringSet("recovered", new HashSet<>()));
wifiManager = (WifiManager) app.getSystemService(WIFI_SERVICE);
// IntentFilter filter = new IntentFilter(ACTION_SCAN_MODE_CHANGED);
}
private InetAddress getWifiIpv4Address() {
if (wifiManager == null) return null;
// If we're connected to a wifi network, return its address
WifiInfo info = wifiManager.getConnectionInfo();
if (info != null && info.getIpAddress() != 0) {
return intToInetAddress(info.getIpAddress());
}
return null;
}
// TODO this is not the right place for this
private InetAddress intToInetAddress(int ip) {
byte[] ipBytes = new byte[4];
ipBytes[0] = (byte) (ip & 0xFF);
ipBytes[1] = (byte) ((ip >> 8) & 0xFF);
ipBytes[2] = (byte) ((ip >> 16) & 0xFF);
ipBytes[3] = (byte) ((ip >> 24) & 0xFF);
try {
return InetAddress.getByAddress(ipBytes);
} catch (UnknownHostException e) {
// Should only be thrown if address has illegal length
throw new AssertionError(e);
}
}
@Override
protected void onCleared() {
super.onCleared();
stopListening();
}
@UiThread
void onStartClicked() {
startClicked.setEvent(true);
}
@UiThread
void onContinueClicked() {
wasContinueClicked = true;
startShardReturn();
}
@UiThread
void onSuccessDismissed() {
successDismissed.setEvent(true);
}
@UiThread
void startShardReturn() {
// If we return to the intro fragment, the continue button needs to be
// clicked again before showing the QR code fragment
wasContinueClicked = false;
// If we return to the intro fragment, we may need to enable wifi and
// hasEnabledWifi = false;
showQrCodeFragment.setEvent(true);
}
@UiThread
public void startListening() {
ioExecutor.execute(() -> {
task.start(this, getWifiIpv4Address());
});
}
@UiThread
private void stopListening() {
ioExecutor.execute(() -> {
task.cancel();
});
}
@UiThread
public void onErrorTryAgain() {
errorTryAgain.setEvent(true);
}
/**
* Set to true in onPostResume() and false in onPause(). This prevents the
* QR code fragment from being shown if onRequestPermissionsResult() is
* called while the activity is paused, which could cause a crash due to
* https://issuetracker.google.com/issues/37067655.
* TODO check if this is still happening with new permission requesting
*/
void setIsActivityResumed(boolean resumed) {
isActivityResumed = resumed;
// Workaround for
// https://code.google.com/p/android/issues/detail?id=190966
// showQrCodeFragmentIfAllowed();
}
LiveEvent<Boolean> getShowQrCodeFragment() {
return showQrCodeFragment;
}
LiveEvent<Boolean> getStartClicked() {
return startClicked;
}
LiveData<SecretOwnerTask.State> getState() {
return state;
}
public Bitmap getQrCodeBitmap() {
LOG.info("getting qrCodeBitmap");
return qrCodeBitmap;
}
public int getNumberOfShards() {
return restoreAccount.getNumberOfShards();
}
@Override
public void onStateChanged(SecretOwnerTask.State state) {
if (state instanceof SecretOwnerTask.State.Listening) {
DisplayMetrics dm =
getApplication().getResources().getDisplayMetrics();
ioExecutor.execute(() -> {
byte[] payloadBytes = ((SecretOwnerTask.State.Listening) state)
.getLocalPayload();
if (LOG.isLoggable(INFO)) {
LOG.info("Local QR code payload is " + payloadBytes.length
+ " bytes");
}
// Use ISO 8859-1 to encode bytes directly as a string
String content = new String(payloadBytes, ISO_8859_1);
qrCodeBitmap = QrCodeUtils.createQrCode(dm, content);
this.state.postValue(state);
});
} else if (state instanceof SecretOwnerTask.State.Success) {
this.state.postValue(state);
} else {
this.state.postValue(state);
}
}
public RestoreAccount.AddReturnShardPayloadResult addToShardSet(ReturnShardPayload toAdd) {
RestoreAccount.AddReturnShardPayloadResult result = restoreAccount.addReturnShardPayload(toAdd);
if (result == RestoreAccount.AddReturnShardPayloadResult.OK) {
prefs.edit().putStringSet("recovered", restoreAccount.getEncodedShards()).apply();
}
return result;
}
public boolean canRecover() {
return restoreAccount.canRecover();
}
public int recover() throws FormatException, GeneralSecurityException {
return restoreAccount.recover();
}
public MutableLiveEvent<Boolean> getSuccessDismissed() {
return successDismissed;
}
public MutableLiveEvent<Boolean> getErrorTryAgain() {
return errorTryAgain;
}
}

View File

@@ -0,0 +1,83 @@
package org.briarproject.briar.android.socialbackup.recover;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Bundle;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
import org.briarproject.briar.R;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.activity.BaseActivity;
import org.briarproject.briar.android.fragment.BaseFragment;
import javax.annotation.Nullable;
import javax.inject.Inject;
import androidx.lifecycle.ViewModelProvider;
import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK;
import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
import static org.briarproject.briar.android.BriarApplication.ENTRY_ACTIVITY;
import static org.briarproject.briar.android.socialbackup.recover.RestoreAccountViewModel.State;
@MethodsNotNullByDefault
@ParametersNotNullByDefault
public class RestoreAccountActivity extends BaseActivity
implements BaseFragment.BaseFragmentListener {
@Inject
ViewModelProvider.Factory viewModelFactory;
RestoreAccountViewModel viewModel;
@Override
public void injectActivity(ActivityComponent component) {
component.inject(this);
viewModel = new ViewModelProvider(this, viewModelFactory)
.get(RestoreAccountViewModel.class);
viewModel.getState().observeEvent(this, this::onStateChanged);
}
@Override
public void onCreate(@Nullable Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_fragment_container);
}
private void onStateChanged(RestoreAccountViewModel.State state) {
if (state == State.SET_PASSWORD) {
showInitialFragment(RestoreAccountSetPasswordFragment.newInstance());
} else if (state == State.DOZE) {
showDozeFragment();
} else if (state == State.CREATED) {
showApp();
} else { // FAILED
// TODO: Show an error if failed
finish();
}
}
@TargetApi(23)
void showDozeFragment() {
showNextFragment(RestoreAccountDozeFragment.newInstance());
}
void showApp() {
Intent i = new Intent(this, ENTRY_ACTIVITY);
i.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_TASK_ON_HOME |
FLAG_ACTIVITY_CLEAR_TASK | FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
supportFinishAfterTransition();
overridePendingTransition(R.anim.screen_new_in, R.anim.screen_old_out);
}
@Override
@Deprecated
public void runOnDbThread(Runnable runnable) {
throw new RuntimeException("Don't use this deprecated method here.");
}
}

View File

@@ -0,0 +1,118 @@
package org.briarproject.briar.android.socialbackup.recover;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
import org.briarproject.briar.R;
import org.briarproject.briar.android.account.DozeView;
import org.briarproject.briar.android.account.HuaweiView;
import org.briarproject.briar.android.account.PowerView;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.util.UiUtils;
import androidx.annotation.Nullable;
import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;
import static org.briarproject.briar.android.activity.RequestCodes.REQUEST_DOZE_WHITELISTING;
import static org.briarproject.briar.android.util.UiUtils.showOnboardingDialog;
@MethodsNotNullByDefault
@ParametersNotNullByDefault
public class RestoreAccountDozeFragment extends RestoreAccountFragment
implements PowerView.OnCheckedChangedListener {
private final static String TAG = RestoreAccountDozeFragment.class.getName();
private DozeView dozeView;
private HuaweiView huaweiView;
private Button next;
private boolean secondAttempt = false;
public static RestoreAccountDozeFragment newInstance() {
return new RestoreAccountDozeFragment();
}
@Override
public void injectFragment(ActivityComponent component) {
component.inject(this);
}
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
requireActivity().setTitle(getString(R.string.setup_doze_title));
setHasOptionsMenu(false);
View v = inflater.inflate(R.layout.fragment_setup_doze, container,
false);
dozeView = v.findViewById(R.id.dozeView);
dozeView.setOnCheckedChangedListener(this);
huaweiView = v.findViewById(R.id.huaweiView);
huaweiView.setOnCheckedChangedListener(this);
next = v.findViewById(R.id.next);
ProgressBar progressBar = v.findViewById(R.id.progress);
dozeView.setOnButtonClickListener(this::askForDozeWhitelisting);
next.setOnClickListener(this);
viewModel.getIsCreatingAccount()
.observe(getViewLifecycleOwner(), isCreatingAccount -> {
if (isCreatingAccount) {
next.setVisibility(INVISIBLE);
progressBar.setVisibility(VISIBLE);
}
});
return v;
}
@Override
public String getUniqueTag() {
return TAG;
}
@Override
protected String getHelpText() {
return getString(R.string.setup_doze_explanation);
}
@Override
public void onActivityResult(int request, int result,
@Nullable Intent data) {
super.onActivityResult(request, result, data);
if (request == REQUEST_DOZE_WHITELISTING) {
if (!dozeView.needsToBeShown() || secondAttempt) {
dozeView.setChecked(true);
} else if (getContext() != null) {
secondAttempt = true;
showOnboardingDialog(getContext(), getHelpText());
}
}
}
@Override
public void onCheckedChanged() {
next.setEnabled(dozeView.isChecked() && huaweiView.isChecked());
}
@SuppressLint("BatteryLife")
private void askForDozeWhitelisting() {
if (getContext() == null) return;
Intent i = UiUtils.getDozeWhitelistingIntent(getContext());
startActivityForResult(i, REQUEST_DOZE_WHITELISTING);
}
@Override
public void onClick(View view) {
viewModel.dozeExceptionConfirmed();
}
}

View File

@@ -0,0 +1,91 @@
package org.briarproject.briar.android.socialbackup.recover;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
import org.briarproject.briar.R;
import org.briarproject.briar.android.fragment.BaseFragment;
import javax.inject.Inject;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import static android.view.inputmethod.EditorInfo.IME_ACTION_DONE;
import static android.view.inputmethod.EditorInfo.IME_ACTION_NEXT;
import static org.briarproject.briar.android.util.UiUtils.enterPressed;
import static org.briarproject.briar.android.util.UiUtils.showOnboardingDialog;
@MethodsNotNullByDefault
@ParametersNotNullByDefault
abstract class RestoreAccountFragment extends BaseFragment implements TextWatcher,
TextView.OnEditorActionListener, View.OnClickListener {
private final static String STATE_KEY_CLICKED = "setupFragmentClicked";
@Inject
ViewModelProvider.Factory viewModelFactory;
RestoreAccountViewModel viewModel;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewModel = new ViewModelProvider(requireActivity())
.get(RestoreAccountViewModel.class);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.help_action, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_help) {
showOnboardingDialog(getContext(), getHelpText());
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
protected abstract String getHelpText();
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// noop
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// noop
}
@Override
public boolean onEditorAction(TextView textView, int actionId,
@Nullable KeyEvent keyEvent) {
if (actionId == IME_ACTION_NEXT || actionId == IME_ACTION_DONE ||
enterPressed(actionId, keyEvent)) {
onClick(textView);
return true;
}
return false;
}
@Override
public void afterTextChanged(Editable editable) {
// noop
}
}

View File

@@ -0,0 +1,131 @@
package org.briarproject.briar.android.socialbackup.recover;
import android.os.Bundle;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ProgressBar;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
import org.briarproject.briar.R;
import org.briarproject.briar.android.activity.ActivityComponent;
import org.briarproject.briar.android.login.StrengthMeter;
import javax.annotation.Nullable;
import static android.content.Context.INPUT_METHOD_SERVICE;
import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;
import static android.view.inputmethod.EditorInfo.IME_ACTION_DONE;
import static org.briarproject.bramble.api.crypto.PasswordStrengthEstimator.QUITE_WEAK;
import static org.briarproject.briar.android.util.UiUtils.setError;
@MethodsNotNullByDefault
@ParametersNotNullByDefault
public class RestoreAccountSetPasswordFragment extends RestoreAccountFragment {
private final static String TAG = RestoreAccountSetPasswordFragment.class.getName();
private TextInputLayout passwordEntryWrapper;
private TextInputLayout passwordConfirmationWrapper;
private TextInputEditText passwordEntry;
private TextInputEditText passwordConfirmation;
private StrengthMeter strengthMeter;
private Button nextButton;
public static RestoreAccountSetPasswordFragment newInstance() {
return new RestoreAccountSetPasswordFragment();
}
@Override
public void injectFragment(ActivityComponent component) {
component.inject(this);
}
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
requireActivity().setTitle(getString(R.string.setup_password_intro));
View v = inflater.inflate(R.layout.fragment_setup_password, container,
false);
strengthMeter = v.findViewById(R.id.strength_meter);
passwordEntryWrapper = v.findViewById(R.id.password_entry_wrapper);
passwordEntry = v.findViewById(R.id.password_entry);
passwordConfirmationWrapper =
v.findViewById(R.id.password_confirm_wrapper);
passwordConfirmation = v.findViewById(R.id.password_confirm);
nextButton = v.findViewById(R.id.next);
ProgressBar progressBar = v.findViewById(R.id.progress);
passwordEntry.addTextChangedListener(this);
passwordConfirmation.addTextChangedListener(this);
nextButton.setOnClickListener(this);
if (!viewModel.needToShowDozeFragment()) {
nextButton.setText(R.string.create_account_button);
passwordConfirmation.setImeOptions(IME_ACTION_DONE);
}
viewModel.getIsCreatingAccount()
.observe(getViewLifecycleOwner(), isCreatingAccount -> {
if (isCreatingAccount) {
nextButton.setVisibility(INVISIBLE);
progressBar.setVisibility(VISIBLE);
// this also avoids the keyboard popping up
passwordEntry.setFocusable(false);
passwordConfirmation.setFocusable(false);
}
});
return v;
}
@Override
public String getUniqueTag() {
return TAG;
}
@Override
protected String getHelpText() {
return getString(R.string.setup_password_explanation);
}
@Override
public void onTextChanged(CharSequence authorName, int i, int i1, int i2) {
String password1 = passwordEntry.getText().toString();
String password2 = passwordConfirmation.getText().toString();
boolean passwordsMatch = password1.equals(password2);
strengthMeter
.setVisibility(password1.length() > 0 ? VISIBLE : INVISIBLE);
float strength = viewModel.estimatePasswordStrength(password1);
strengthMeter.setStrength(strength);
boolean strongEnough = strength >= QUITE_WEAK;
setError(passwordEntryWrapper, getString(R.string.password_too_weak),
password1.length() > 0 && !strongEnough);
setError(passwordConfirmationWrapper,
getString(R.string.passwords_do_not_match),
password2.length() > 0 && !passwordsMatch);
boolean enabled = passwordsMatch && strongEnough;
nextButton.setEnabled(enabled);
passwordConfirmation.setOnEditorActionListener(enabled ? this : null);
}
@Override
public void onClick(View view) {
IBinder token = passwordEntry.getWindowToken();
Object o = getContext().getSystemService(INPUT_METHOD_SERVICE);
((InputMethodManager) o).hideSoftInputFromWindow(token, 0);
viewModel.setPassword(passwordEntry.getText().toString());
}
}

View File

@@ -0,0 +1,142 @@
package org.briarproject.briar.android.socialbackup.recover;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import org.briarproject.bramble.api.account.AccountManager;
import org.briarproject.bramble.api.contact.ContactManager;
import org.briarproject.bramble.api.crypto.PasswordStrengthEstimator;
import org.briarproject.bramble.api.db.DbException;
import org.briarproject.bramble.api.identity.Identity;
import org.briarproject.bramble.api.lifecycle.IoExecutor;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
import org.briarproject.briar.android.account.DozeHelper;
import org.briarproject.briar.android.viewmodel.LiveEvent;
import org.briarproject.briar.android.viewmodel.MutableLiveEvent;
import org.briarproject.briar.api.socialbackup.SocialBackup;
import org.briarproject.briar.api.socialbackup.recovery.RestoreAccount;
import java.util.concurrent.Executor;
import java.util.logging.Logger;
import javax.inject.Inject;
import androidx.annotation.Nullable;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import static java.util.logging.Logger.getLogger;
@MethodsNotNullByDefault
@ParametersNotNullByDefault
class RestoreAccountViewModel extends AndroidViewModel {
enum State {SET_PASSWORD, DOZE, CREATED, FAILED}
private static final Logger LOG =
getLogger(RestoreAccountViewModel.class.getName());
@Nullable
private String password;
private final MutableLiveEvent<State>
state = new MutableLiveEvent<>();
private final MutableLiveData<Boolean> isCreatingAccount =
new MutableLiveData<>(false);
private final AccountManager accountManager;
private final Executor ioExecutor;
private final PasswordStrengthEstimator strengthEstimator;
private final DozeHelper dozeHelper;
private final RestoreAccount restoreAccount;
private final SharedPreferences prefs;
@Inject
RestoreAccountViewModel(Application app,
AccountManager accountManager,
RestoreAccount restoreAccount,
@IoExecutor Executor ioExecutor,
PasswordStrengthEstimator strengthEstimator,
DozeHelper dozeHelper) {
super(app);
this.accountManager = accountManager;
this.ioExecutor = ioExecutor;
this.strengthEstimator = strengthEstimator;
this.dozeHelper = dozeHelper;
this.restoreAccount = restoreAccount;
this.prefs = app.getSharedPreferences("account-recovery",
Context.MODE_PRIVATE);
ioExecutor.execute(() -> {
if (accountManager.accountExists()) {
throw new AssertionError();
} else {
state.postEvent(State.SET_PASSWORD);
}
});
}
LiveEvent<State> getState() {
return state;
}
LiveData<Boolean> getIsCreatingAccount() {
return isCreatingAccount;
}
void setPassword(String password) {
this.password = password;
if (needToShowDozeFragment()) {
state.setEvent(State.DOZE);
} else {
createAccount();
}
}
float estimatePasswordStrength(String password) {
return strengthEstimator.estimateStrength(password);
}
boolean needToShowDozeFragment() {
return dozeHelper.needToShowDozeFragment(getApplication());
}
void dozeExceptionConfirmed() {
createAccount();
}
private void createAccount() {
if (password == null) throw new IllegalStateException();
isCreatingAccount.setValue(true);
SocialBackup socialBackup = restoreAccount.getSocialBackup();
if (socialBackup == null) {
LOG.warning("Cannot retrieve social backup");
state.postEvent(State.FAILED);
return;
}
Identity identity = socialBackup.getIdentity();
ioExecutor.execute(() -> {
if (accountManager.restoreAccount(identity, password)) {
LOG.info("Restored account");
try {
restoreAccount.restoreAccountWhenDatabaseReady();
} catch (DbException e) {
LOG.warning("Failure processing social backup");
e.printStackTrace();
state.postEvent(State.FAILED);
return;
}
// Remove partial recovery from shared preferences
prefs.edit().clear().apply();
state.postEvent(State.CREATED);
} else {
LOG.warning("Failed to create account");
state.postEvent(State.FAILED);
}
});
}
}

Some files were not shown because too many files have changed in this diff Show More