mirror of
https://code.briarproject.org/briar/briar.git
synced 2026-02-12 18:59:06 +01:00
Compare commits
260 Commits
beta-1.2.2
...
social-bac
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1eb6be2407 | ||
|
|
53c4ba184d | ||
|
|
4b9c3a1a96 | ||
|
|
eb66a13ded | ||
|
|
b860e73bdc | ||
|
|
851bbb293e | ||
|
|
36aaea40bd | ||
|
|
7563172121 | ||
|
|
fad9257066 | ||
|
|
873b088a42 | ||
|
|
c7bca253fe | ||
|
|
47f136904c | ||
|
|
0a0b79ad9b | ||
|
|
e9f4f084dd | ||
|
|
3484892628 | ||
|
|
f67d2f0157 | ||
|
|
ef05ecc342 | ||
|
|
3d807d9950 | ||
|
|
4cf9ca9c3e | ||
|
|
95d540644b | ||
|
|
3b4988c109 | ||
|
|
9b7b583e8a | ||
|
|
21f3634050 | ||
|
|
33549bcbe1 | ||
|
|
d975d1dbdd | ||
|
|
af64bb056d | ||
|
|
ca54566ce0 | ||
|
|
85683a57f1 | ||
|
|
f524af893d | ||
|
|
7b63471205 | ||
|
|
4db1c4cc6b | ||
|
|
71e63fb6f1 | ||
|
|
cae655b020 | ||
|
|
f601e2945b | ||
|
|
55e0ba8888 | ||
|
|
3b4a20ce01 | ||
|
|
e5eb82a5a8 | ||
|
|
26a35b3212 | ||
|
|
68f135adad | ||
|
|
7ecd952f49 | ||
|
|
4b30b50329 | ||
|
|
c2b7657041 | ||
|
|
61a052fc65 | ||
|
|
d78a6604fd | ||
|
|
8ffe9a6367 | ||
|
|
4b9c796c1a | ||
|
|
6af739e584 | ||
|
|
50cb3997d9 | ||
|
|
a6f06e328b | ||
|
|
a5f0516135 | ||
|
|
3d34a36908 | ||
|
|
e29a5f487e | ||
|
|
acb9b18507 | ||
|
|
f5455d320b | ||
|
|
07141b688a | ||
|
|
b1c6c602a6 | ||
|
|
60c6c6a7ae | ||
|
|
3ac7d71f8a | ||
|
|
41c13f80f4 | ||
|
|
2e03967519 | ||
|
|
4b77a9ab60 | ||
|
|
327cbe23ee | ||
|
|
34f15b6bdc | ||
|
|
5c22d233ef | ||
|
|
afc0bc3f3c | ||
|
|
2a365d986f | ||
|
|
741c9b63d9 | ||
|
|
5420204703 | ||
|
|
e827b8a190 | ||
|
|
c6046a1c38 | ||
|
|
b401232736 | ||
|
|
46fc510ce2 | ||
|
|
b835064b5e | ||
|
|
ae35354e82 | ||
|
|
bdbc377c8f | ||
|
|
ad3c9e101c | ||
|
|
101b93b3da | ||
|
|
e392a0dd8b | ||
|
|
00de32aa87 | ||
|
|
3ff6042d10 | ||
|
|
b3adfe19a4 | ||
|
|
708262c512 | ||
|
|
f4d667f50a | ||
|
|
79369f4e7a | ||
|
|
fec74ed343 | ||
|
|
4ba3fdb1e3 | ||
|
|
20df10d7a8 | ||
|
|
b901974488 | ||
|
|
badc2c5d9b | ||
|
|
ed1ed7d3e1 | ||
|
|
e6d80ec484 | ||
|
|
536905c260 | ||
|
|
9b4f5be6fe | ||
|
|
f13cc15661 | ||
|
|
b07206c898 | ||
|
|
d2abd6dcc2 | ||
|
|
6a143eea8a | ||
|
|
4da20a2412 | ||
|
|
1bf9f57ad9 | ||
|
|
cd1ac43b7d | ||
|
|
df37a39cb4 | ||
|
|
f7e40657ee | ||
|
|
d6608fd8cb | ||
|
|
dba4cc278c | ||
|
|
01bcc6d491 | ||
|
|
e106166cfe | ||
|
|
5fd0d0d2d3 | ||
|
|
e006e22616 | ||
|
|
c0827eda77 | ||
|
|
b55ae1ce18 | ||
|
|
d925f3be0b | ||
|
|
71c327112c | ||
|
|
30b2905c2e | ||
|
|
9d01de9868 | ||
|
|
71b8c32a3e | ||
|
|
207a8bc7cb | ||
|
|
9e4ace4ce7 | ||
|
|
e856ee48f9 | ||
|
|
ea4bd5f438 | ||
|
|
5b7bc54e16 | ||
|
|
996eb20556 | ||
|
|
61453b96ab | ||
|
|
73ce6c2fb0 | ||
|
|
3ddda8cf7f | ||
|
|
93ee8df43a | ||
|
|
0ee4ade404 | ||
|
|
d0b939dafb | ||
|
|
4f26230996 | ||
|
|
e804a8d573 | ||
|
|
6bff0647d6 | ||
|
|
5b52417d20 | ||
|
|
3688b0b17a | ||
|
|
4f42ce9a01 | ||
|
|
c155020064 | ||
|
|
933397f58b | ||
|
|
d129186bab | ||
|
|
a11a81f3d4 | ||
|
|
7c6a2a9b46 | ||
|
|
0258cf9c59 | ||
|
|
caee34f738 | ||
|
|
4f3e4b019a | ||
|
|
7afe5a85f8 | ||
|
|
943e734ae9 | ||
|
|
c2cbba451d | ||
|
|
fc909a317e | ||
|
|
a0df8ded69 | ||
|
|
9d23c876ae | ||
|
|
1d44305e34 | ||
|
|
a37af592cd | ||
|
|
7f486eef4c | ||
|
|
265d1da566 | ||
|
|
b6d57a492b | ||
|
|
943f107232 | ||
|
|
09e024ea5e | ||
|
|
2486a60fea | ||
|
|
365fa58928 | ||
|
|
45d2e2ce06 | ||
|
|
b1f5d71a4e | ||
|
|
d47c18b392 | ||
|
|
8ed58eaada | ||
|
|
8478097a3c | ||
|
|
0440c5c7c8 | ||
|
|
58db654a9b | ||
|
|
c3d137a73c | ||
|
|
db7825d7f6 | ||
|
|
24059adbd6 | ||
|
|
bcc0442add | ||
|
|
700f6e05bf | ||
|
|
d8327d6de2 | ||
|
|
5a55b3d7e3 | ||
|
|
bed87ed439 | ||
|
|
6d1f1c7852 | ||
|
|
f6b3bde724 | ||
|
|
94ec22bef8 | ||
|
|
7d128988a7 | ||
|
|
9499a078a6 | ||
|
|
6483b0ed87 | ||
|
|
af097dc859 | ||
|
|
3adc6d002c | ||
|
|
0658e90c65 | ||
|
|
6d0aebd7ec | ||
|
|
0faccfe5a3 | ||
|
|
c19c40bdc8 | ||
|
|
363da96709 | ||
|
|
e9c2cb2cc5 | ||
|
|
505124a22f | ||
|
|
9b750291d1 | ||
|
|
9c829ec7c9 | ||
|
|
1b9ba41110 | ||
|
|
fa39e7c824 | ||
|
|
37fb3bd79f | ||
|
|
1c5e89b100 | ||
|
|
6dc6a34d29 | ||
|
|
35b2b8c9d2 | ||
|
|
e3ff8a80e5 | ||
|
|
e09fedd79f | ||
|
|
6c3df2a3d4 | ||
|
|
a9edf43df2 | ||
|
|
d91d2e0070 | ||
|
|
58f803a48a | ||
|
|
ac9c71f7eb | ||
|
|
b3292f86ab | ||
|
|
28d2697e38 | ||
|
|
8e4b309a12 | ||
|
|
8a1333e8f2 | ||
|
|
bd2a671f9f | ||
|
|
845be86113 | ||
|
|
25bbb5aa36 | ||
|
|
57605d55ce | ||
|
|
6c079e172a | ||
|
|
a101229f73 | ||
|
|
3f7f53774b | ||
|
|
9beb4d7b81 | ||
|
|
378112c00c | ||
|
|
451a3238be | ||
|
|
bf6dd0d924 | ||
|
|
085e25cc14 | ||
|
|
033c9f4d59 | ||
|
|
5f7bc4a143 | ||
|
|
4972c554dc | ||
|
|
44e33e3d1a | ||
|
|
5212bb7a01 | ||
|
|
83aad185cd | ||
|
|
c318dcfb5f | ||
|
|
10610930c0 | ||
|
|
2af236b733 | ||
|
|
d46a513208 | ||
|
|
022357fb4c | ||
|
|
a576d7abf8 | ||
|
|
008877a9da | ||
|
|
01bc94c241 | ||
|
|
03c1f9c99a | ||
|
|
0b9e4915dc | ||
|
|
55e5600214 | ||
|
|
4c357fe87a | ||
|
|
6a7ceb4a68 | ||
|
|
d917e9d642 | ||
|
|
c7f6270b2a | ||
|
|
681b151c8b | ||
|
|
b86b0f5fbc | ||
|
|
dc138c713f | ||
|
|
7da49ae6df | ||
|
|
3c61f499d9 | ||
|
|
fbe839d9ca | ||
|
|
f2638c9db2 | ||
|
|
808166931e | ||
|
|
77d0c16530 | ||
|
|
c991cfb926 | ||
|
|
dcda13db64 | ||
|
|
ff4640b789 | ||
|
|
a2426e3b2a | ||
|
|
0bc4bf232f | ||
|
|
2ed44aa2a8 | ||
|
|
8496ab0a6a | ||
|
|
b57d811b4a | ||
|
|
4077e28999 | ||
|
|
292fb6d3b1 | ||
|
|
4ead7cd4a1 | ||
|
|
513e696238 | ||
|
|
f160efb0e7 |
9
.idea/codeStyles/Project.xml
generated
9
.idea/codeStyles/Project.xml
generated
@@ -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" />
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,9 @@
|
||||
package org.briarproject.bramble.api.contact;
|
||||
|
||||
/**
|
||||
* Record types for the contact exchange protocol.
|
||||
*/
|
||||
public interface ContactExchangeRecordTypes {
|
||||
|
||||
byte CONTACT_INFO = 0;
|
||||
}
|
||||
@@ -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}.
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
package org.briarproject.bramble.contact;
|
||||
|
||||
/**
|
||||
* Record types for the contact exchange protocol.
|
||||
*/
|
||||
interface ContactExchangeRecordTypes {
|
||||
|
||||
byte CONTACT_INFO = 0;
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -34,12 +34,12 @@ class KeyAgreementTransport {
|
||||
Logger.getLogger(KeyAgreementTransport.class.getName());
|
||||
|
||||
// Accept records with current protocol version, known record type
|
||||
private static Predicate<Record> ACCEPT = r ->
|
||||
private static final Predicate<Record> ACCEPT = r ->
|
||||
r.getProtocolVersion() == PROTOCOL_VERSION &&
|
||||
isKnownRecordType(r.getRecordType());
|
||||
|
||||
// Ignore records with current protocol version, unknown record type
|
||||
private static Predicate<Record> IGNORE = r ->
|
||||
private static final Predicate<Record> IGNORE = r ->
|
||||
r.getProtocolVersion() == PROTOCOL_VERSION &&
|
||||
!isKnownRecordType(r.getRecordType());
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -40,3 +40,5 @@
|
||||
|
||||
# Dependency injection annotations, needed for UI tests on older API levels
|
||||
-keep class javax.inject.**
|
||||
|
||||
-keep class com.sun.jna.** { *; }
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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"
|
||||
@@ -342,7 +387,7 @@
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name="org.briarproject.briar.android.keyagreement.ContactExchangeActivity"
|
||||
android:name="org.briarproject.briar.android.contact.add.nearby.AddNearbyContactActivity"
|
||||
android:label="@string/add_contact_title"
|
||||
android:parentActivityName="org.briarproject.briar.android.navdrawer.NavDrawerActivity"
|
||||
android:theme="@style/BriarTheme.NoActionBar">
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -31,9 +31,9 @@ import org.briarproject.briar.android.account.DozeHelperModule;
|
||||
import org.briarproject.briar.android.account.LockManagerImpl;
|
||||
import org.briarproject.briar.android.account.SetupModule;
|
||||
import org.briarproject.briar.android.contact.ContactListModule;
|
||||
import org.briarproject.briar.android.contact.add.nearby.AddNearbyContactModule;
|
||||
import org.briarproject.briar.android.forum.ForumModule;
|
||||
import org.briarproject.briar.android.introduction.IntroductionModule;
|
||||
import org.briarproject.briar.android.keyagreement.ContactExchangeModule;
|
||||
import org.briarproject.briar.android.logging.LoggingModule;
|
||||
import org.briarproject.briar.android.login.LoginModule;
|
||||
import org.briarproject.briar.android.navdrawer.NavDrawerModule;
|
||||
@@ -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;
|
||||
@@ -75,7 +78,7 @@ import static org.briarproject.briar.android.TestingConstants.IS_DEBUG_BUILD;
|
||||
@Module(includes = {
|
||||
SetupModule.class,
|
||||
DozeHelperModule.class,
|
||||
ContactExchangeModule.class,
|
||||
AddNearbyContactModule.class,
|
||||
LoggingModule.class,
|
||||
LoginModule.class,
|
||||
NavDrawerModule.class,
|
||||
@@ -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 {
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ package org.briarproject.briar.android.account;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
interface DozeHelper {
|
||||
public interface DozeHelper {
|
||||
|
||||
boolean needToShowDozeFragment(Context context);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 =
|
||||
|
||||
@@ -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.");
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
package org.briarproject.briar.android.account;
|
||||
|
||||
import androidx.annotation.UiThread;
|
||||
|
||||
public interface RecoverAccountListener {
|
||||
@UiThread
|
||||
void recoverAccountChosen();
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package org.briarproject.briar.android.account;
|
||||
|
||||
import androidx.annotation.UiThread;
|
||||
|
||||
public interface SetupNewAccountChosenListener {
|
||||
@UiThread
|
||||
void setupNewAccountChosen();
|
||||
}
|
||||
@@ -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}
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -21,6 +24,10 @@ import org.briarproject.briar.android.blog.RssFeedImportActivity;
|
||||
import org.briarproject.briar.android.blog.RssFeedManageActivity;
|
||||
import org.briarproject.briar.android.blog.WriteBlogPostActivity;
|
||||
import org.briarproject.briar.android.contact.ContactListFragment;
|
||||
import org.briarproject.briar.android.contact.add.nearby.AddNearbyContactActivity;
|
||||
import org.briarproject.briar.android.contact.add.nearby.AddNearbyContactErrorFragment;
|
||||
import org.briarproject.briar.android.contact.add.nearby.AddNearbyContactFragment;
|
||||
import org.briarproject.briar.android.contact.add.nearby.AddNearbyContactIntroFragment;
|
||||
import org.briarproject.briar.android.contact.add.remote.AddContactActivity;
|
||||
import org.briarproject.briar.android.contact.add.remote.LinkExchangeFragment;
|
||||
import org.briarproject.briar.android.contact.add.remote.NicknameFragment;
|
||||
@@ -36,10 +43,6 @@ import org.briarproject.briar.android.fragment.ScreenFilterDialogFragment;
|
||||
import org.briarproject.briar.android.introduction.ContactChooserFragment;
|
||||
import org.briarproject.briar.android.introduction.IntroductionActivity;
|
||||
import org.briarproject.briar.android.introduction.IntroductionMessageFragment;
|
||||
import org.briarproject.briar.android.keyagreement.ContactExchangeActivity;
|
||||
import org.briarproject.briar.android.keyagreement.ContactExchangeErrorFragment;
|
||||
import org.briarproject.briar.android.keyagreement.KeyAgreementActivity;
|
||||
import org.briarproject.briar.android.keyagreement.KeyAgreementFragment;
|
||||
import org.briarproject.briar.android.login.ChangePasswordActivity;
|
||||
import org.briarproject.briar.android.login.OpenDatabaseFragment;
|
||||
import org.briarproject.briar.android.login.PasswordFragment;
|
||||
@@ -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 {
|
||||
|
||||
@@ -108,9 +133,7 @@ public interface ActivityComponent {
|
||||
|
||||
void inject(PanicPreferencesActivity activity);
|
||||
|
||||
void inject(ContactExchangeActivity activity);
|
||||
|
||||
void inject(KeyAgreementActivity activity);
|
||||
void inject(AddNearbyContactActivity activity);
|
||||
|
||||
void inject(ConversationActivity activity);
|
||||
|
||||
@@ -182,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);
|
||||
@@ -208,7 +241,9 @@ public interface ActivityComponent {
|
||||
|
||||
void inject(FeedFragment fragment);
|
||||
|
||||
void inject(KeyAgreementFragment fragment);
|
||||
void inject(AddNearbyContactIntroFragment fragment);
|
||||
|
||||
void inject(AddNearbyContactFragment fragment);
|
||||
|
||||
void inject(LinkExchangeFragment fragment);
|
||||
|
||||
@@ -226,7 +261,7 @@ public interface ActivityComponent {
|
||||
|
||||
void inject(ScreenFilterDialogFragment fragment);
|
||||
|
||||
void inject(ContactExchangeErrorFragment fragment);
|
||||
void inject(AddNearbyContactErrorFragment fragment);
|
||||
|
||||
void inject(AliasDialogFragment aliasDialogFragment);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -9,9 +9,7 @@ public interface RequestCodes {
|
||||
int REQUEST_WRITE_BLOG_POST = 5;
|
||||
int REQUEST_SHARE_BLOG = 6;
|
||||
int REQUEST_RINGTONE = 7;
|
||||
int REQUEST_PERMISSION_CAMERA_LOCATION = 8;
|
||||
int REQUEST_DOZE_WHITELISTING = 9;
|
||||
int REQUEST_BLUETOOTH_DISCOVERABLE = 10;
|
||||
int REQUEST_UNLOCK = 11;
|
||||
int REQUEST_KEYGUARD_UNLOCK = 12;
|
||||
int REQUEST_ATTACH_IMAGE = 13;
|
||||
|
||||
@@ -15,11 +15,11 @@ 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.AddNearbyContactActivity;
|
||||
import org.briarproject.briar.android.contact.add.remote.AddContactActivity;
|
||||
import org.briarproject.briar.android.contact.add.remote.PendingContactListActivity;
|
||||
import org.briarproject.briar.android.conversation.ConversationActivity;
|
||||
import org.briarproject.briar.android.fragment.BaseFragment;
|
||||
import org.briarproject.briar.android.keyagreement.ContactExchangeActivity;
|
||||
import org.briarproject.briar.android.util.BriarSnackbarBuilder;
|
||||
import org.briarproject.briar.android.view.BriarRecyclerView;
|
||||
|
||||
@@ -125,7 +125,8 @@ public class ContactListFragment extends BaseFragment
|
||||
switch (itemId) {
|
||||
case R.id.action_add_contact_nearby:
|
||||
Intent intent =
|
||||
new Intent(getContext(), ContactExchangeActivity.class);
|
||||
new Intent(getContext(),
|
||||
AddNearbyContactActivity.class);
|
||||
startActivity(intent);
|
||||
return;
|
||||
case R.id.action_add_contact_remotely:
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package org.briarproject.briar.android.contact.add.nearby;
|
||||
|
||||
import android.graphics.Bitmap;
|
||||
|
||||
import org.briarproject.bramble.api.identity.Author;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
abstract class AddContactState {
|
||||
|
||||
static class KeyAgreementListening extends AddContactState {
|
||||
final Bitmap qrCode;
|
||||
|
||||
KeyAgreementListening(Bitmap qrCode) {
|
||||
this.qrCode = qrCode;
|
||||
}
|
||||
}
|
||||
|
||||
static class QrCodeScanned extends AddContactState {
|
||||
}
|
||||
|
||||
static class KeyAgreementWaiting extends AddContactState {
|
||||
}
|
||||
|
||||
static class KeyAgreementStarted extends AddContactState {
|
||||
}
|
||||
|
||||
static class ContactExchangeStarted extends AddContactState {
|
||||
}
|
||||
|
||||
static class ContactExchangeFinished extends AddContactState {
|
||||
final ContactExchangeResult result;
|
||||
|
||||
ContactExchangeFinished(ContactExchangeResult result) {
|
||||
this.result = result;
|
||||
}
|
||||
}
|
||||
|
||||
static class Failed extends AddContactState {
|
||||
/**
|
||||
* Non-null if failed due to the scanned QR code version.
|
||||
* True if the app producing the code is too old.
|
||||
* False if the scanning app is too old.
|
||||
*/
|
||||
@Nullable
|
||||
final Boolean qrCodeTooOld;
|
||||
|
||||
Failed(@Nullable Boolean qrCodeTooOld) {
|
||||
this.qrCodeTooOld = qrCodeTooOld;
|
||||
}
|
||||
|
||||
Failed() {
|
||||
this(null);
|
||||
}
|
||||
}
|
||||
|
||||
abstract static class ContactExchangeResult {
|
||||
static class Success extends ContactExchangeResult {
|
||||
final Author remoteAuthor;
|
||||
|
||||
Success(Author remoteAuthor) {
|
||||
this.remoteAuthor = remoteAuthor;
|
||||
}
|
||||
}
|
||||
|
||||
static class Error extends ContactExchangeResult {
|
||||
@Nullable
|
||||
final Author duplicateAuthor;
|
||||
|
||||
Error(@Nullable Author duplicateAuthor) {
|
||||
this.duplicateAuthor = duplicateAuthor;
|
||||
}
|
||||
}
|
||||
} // end ContactExchangeResult
|
||||
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package org.briarproject.briar.android.contact.add.nearby;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.view.MenuItem;
|
||||
import android.widget.Toast;
|
||||
|
||||
import org.briarproject.bramble.api.identity.Author;
|
||||
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.BriarActivity;
|
||||
import org.briarproject.briar.android.contact.add.nearby.AddContactState.ContactExchangeFinished;
|
||||
import org.briarproject.briar.android.contact.add.nearby.AddContactState.ContactExchangeResult;
|
||||
import org.briarproject.briar.android.contact.add.nearby.AddContactState.Failed;
|
||||
import org.briarproject.briar.android.contact.add.nearby.AddNearbyContactViewModel.BluetoothDecision;
|
||||
import org.briarproject.briar.android.fragment.BaseFragment;
|
||||
import org.briarproject.briar.android.fragment.BaseFragment.BaseFragmentListener;
|
||||
import org.briarproject.briar.android.util.RequestBluetoothDiscoverable;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import androidx.activity.result.ActivityResultLauncher;
|
||||
import androidx.appcompat.widget.Toolbar;
|
||||
import androidx.fragment.app.FragmentManager;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
|
||||
import static android.bluetooth.BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE;
|
||||
import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
|
||||
import static android.widget.Toast.LENGTH_LONG;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
import static org.briarproject.briar.android.contact.add.nearby.AddNearbyContactViewModel.BluetoothDecision.ACCEPTED;
|
||||
import static org.briarproject.briar.android.contact.add.nearby.AddNearbyContactViewModel.BluetoothDecision.REFUSED;
|
||||
|
||||
@MethodsNotNullByDefault
|
||||
@ParametersNotNullByDefault
|
||||
public class AddNearbyContactActivity extends BriarActivity
|
||||
implements BaseFragmentListener {
|
||||
|
||||
private static final Logger LOG =
|
||||
getLogger(AddNearbyContactActivity.class.getName());
|
||||
|
||||
@Inject
|
||||
ViewModelProvider.Factory viewModelFactory;
|
||||
|
||||
private AddNearbyContactViewModel viewModel;
|
||||
private final ActivityResultLauncher<Integer> bluetoothLauncher =
|
||||
registerForActivityResult(new RequestBluetoothDiscoverable(),
|
||||
this::onBluetoothDiscoverableResult);
|
||||
|
||||
@Override
|
||||
public void injectActivity(ActivityComponent component) {
|
||||
component.inject(this);
|
||||
viewModel = new ViewModelProvider(this, viewModelFactory)
|
||||
.get(AddNearbyContactViewModel.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate(@Nullable Bundle state) {
|
||||
super.onCreate(state);
|
||||
setContentView(R.layout.activity_fragment_container_toolbar);
|
||||
Toolbar toolbar = findViewById(R.id.toolbar);
|
||||
setSupportActionBar(toolbar);
|
||||
requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
|
||||
if (state == null) {
|
||||
showInitialFragment(AddNearbyContactIntroFragment.newInstance());
|
||||
}
|
||||
viewModel.getRequestBluetoothDiscoverable().observeEvent(this, r ->
|
||||
requestBluetoothDiscoverable()); // never false
|
||||
viewModel.getShowQrCodeFragment().observeEvent(this, show -> {
|
||||
if (show) showQrCodeFragment();
|
||||
});
|
||||
requireNonNull(getSupportActionBar())
|
||||
.setTitle(R.string.add_contact_title);
|
||||
viewModel.getState()
|
||||
.observe(this, this::onAddContactStateChanged);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPostResume() {
|
||||
super.onPostResume();
|
||||
viewModel.setIsActivityResumed(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPause() {
|
||||
super.onPause();
|
||||
viewModel.setIsActivityResumed(false);
|
||||
}
|
||||
|
||||
private void onBluetoothDiscoverableResult(boolean discoverable) {
|
||||
if (discoverable) {
|
||||
LOG.info("Bluetooth discoverability was accepted");
|
||||
viewModel.setBluetoothDecision(ACCEPTED);
|
||||
} else {
|
||||
LOG.info("Bluetooth discoverability was refused");
|
||||
viewModel.setBluetoothDecision(REFUSED);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(MenuItem item) {
|
||||
if (item.getItemId() == android.R.id.home) {
|
||||
onBackPressed();
|
||||
return true;
|
||||
}
|
||||
return super.onOptionsItemSelected(item);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBackPressed() {
|
||||
if (viewModel.getState().getValue() instanceof Failed) {
|
||||
// re-create this activity when going back in failed state
|
||||
Intent i = new Intent(this, AddNearbyContactActivity.class);
|
||||
i.setFlags(FLAG_ACTIVITY_CLEAR_TOP);
|
||||
startActivity(i);
|
||||
} else {
|
||||
super.onBackPressed();
|
||||
}
|
||||
}
|
||||
|
||||
private void requestBluetoothDiscoverable() {
|
||||
Intent i = new Intent(ACTION_REQUEST_DISCOVERABLE);
|
||||
if (i.resolveActivity(getPackageManager()) != null) {
|
||||
LOG.info("Asking for Bluetooth discoverability");
|
||||
viewModel.setBluetoothDecision(BluetoothDecision.WAITING);
|
||||
bluetoothLauncher.launch(120); // 2min discoverable
|
||||
} else {
|
||||
viewModel.setBluetoothDecision(BluetoothDecision.NO_ADAPTER);
|
||||
}
|
||||
}
|
||||
|
||||
private void showQrCodeFragment() {
|
||||
// FIXME #824
|
||||
FragmentManager fm = getSupportFragmentManager();
|
||||
if (fm.findFragmentByTag(AddNearbyContactFragment.TAG) == null) {
|
||||
BaseFragment f = AddNearbyContactFragment.newInstance();
|
||||
fm.beginTransaction()
|
||||
.replace(R.id.fragmentContainer, f, f.getUniqueTag())
|
||||
.addToBackStack(f.getUniqueTag())
|
||||
.commit();
|
||||
}
|
||||
}
|
||||
|
||||
private void onAddContactStateChanged(@Nullable AddContactState state) {
|
||||
if (state instanceof ContactExchangeFinished) {
|
||||
ContactExchangeResult result =
|
||||
((ContactExchangeFinished) state).result;
|
||||
onContactExchangeResult(result);
|
||||
} else if (state instanceof Failed) {
|
||||
Boolean qrCodeTooOld = ((Failed) state).qrCodeTooOld;
|
||||
onAddingContactFailed(qrCodeTooOld);
|
||||
}
|
||||
}
|
||||
|
||||
private void onContactExchangeResult(ContactExchangeResult result) {
|
||||
if (result instanceof ContactExchangeResult.Success) {
|
||||
Author remoteAuthor =
|
||||
((ContactExchangeResult.Success) result).remoteAuthor;
|
||||
String contactName = remoteAuthor.getName();
|
||||
String text = getString(R.string.contact_added_toast, contactName);
|
||||
Toast.makeText(this, text, LENGTH_LONG).show();
|
||||
supportFinishAfterTransition();
|
||||
} else if (result instanceof ContactExchangeResult.Error) {
|
||||
Author duplicateAuthor =
|
||||
((ContactExchangeResult.Error) result).duplicateAuthor;
|
||||
if (duplicateAuthor == null) {
|
||||
showErrorFragment();
|
||||
} else {
|
||||
String contactName = duplicateAuthor.getName();
|
||||
String text =
|
||||
getString(R.string.contact_already_exists, contactName);
|
||||
Toast.makeText(this, text, LENGTH_LONG).show();
|
||||
supportFinishAfterTransition();
|
||||
}
|
||||
} else throw new AssertionError();
|
||||
}
|
||||
|
||||
private void onAddingContactFailed(@Nullable Boolean qrCodeTooOld) {
|
||||
if (qrCodeTooOld == null) {
|
||||
showErrorFragment();
|
||||
} else {
|
||||
String msg;
|
||||
if (qrCodeTooOld) {
|
||||
msg = getString(R.string.qr_code_too_old,
|
||||
getString(R.string.app_name));
|
||||
} else {
|
||||
msg = getString(R.string.qr_code_too_new,
|
||||
getString(R.string.app_name));
|
||||
}
|
||||
showNextFragment(AddNearbyContactErrorFragment.newInstance(msg));
|
||||
}
|
||||
}
|
||||
|
||||
private void showErrorFragment() {
|
||||
showNextFragment(new AddNearbyContactErrorFragment());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.briarproject.briar.android.keyagreement;
|
||||
package org.briarproject.briar.android.contact.add.nearby;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
@@ -24,14 +24,14 @@ import static org.briarproject.briar.android.util.UiUtils.onSingleLinkClick;
|
||||
|
||||
@MethodsNotNullByDefault
|
||||
@ParametersNotNullByDefault
|
||||
public class ContactExchangeErrorFragment extends BaseFragment {
|
||||
public class AddNearbyContactErrorFragment extends BaseFragment {
|
||||
|
||||
public static final String TAG =
|
||||
ContactExchangeErrorFragment.class.getName();
|
||||
AddNearbyContactErrorFragment.class.getName();
|
||||
private static final String ERROR_MSG = "errorMessage";
|
||||
|
||||
public static ContactExchangeErrorFragment newInstance(String errorMsg) {
|
||||
ContactExchangeErrorFragment f = new ContactExchangeErrorFragment();
|
||||
public static AddNearbyContactErrorFragment newInstance(String errorMsg) {
|
||||
AddNearbyContactErrorFragment f = new AddNearbyContactErrorFragment();
|
||||
Bundle args = new Bundle();
|
||||
args.putString(ERROR_MSG, errorMsg);
|
||||
f.setArguments(args);
|
||||
@@ -72,7 +72,7 @@ public class ContactExchangeErrorFragment extends BaseFragment {
|
||||
tryAgain.setOnClickListener(view -> {
|
||||
// Recreate the activity so we return to the intro fragment
|
||||
FragmentActivity activity = requireActivity();
|
||||
Intent i = new Intent(activity, ContactExchangeActivity.class);
|
||||
Intent i = new Intent(activity, AddNearbyContactActivity.class);
|
||||
i.setFlags(FLAG_ACTIVITY_CLEAR_TOP);
|
||||
activity.startActivity(i);
|
||||
});
|
||||
@@ -0,0 +1,202 @@
|
||||
package org.briarproject.briar.android.contact.add.nearby;
|
||||
|
||||
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.LinearLayout.LayoutParams;
|
||||
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.AddContactState.ContactExchangeStarted;
|
||||
import org.briarproject.briar.android.contact.add.nearby.AddContactState.Failed;
|
||||
import org.briarproject.briar.android.contact.add.nearby.AddContactState.KeyAgreementStarted;
|
||||
import org.briarproject.briar.android.contact.add.nearby.AddContactState.KeyAgreementWaiting;
|
||||
import org.briarproject.briar.android.contact.add.nearby.AddContactState.QrCodeScanned;
|
||||
import org.briarproject.briar.android.fragment.BaseFragment;
|
||||
import org.briarproject.briar.android.view.QrCodeView;
|
||||
|
||||
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 AddNearbyContactFragment extends BaseFragment
|
||||
implements QrCodeView.FullscreenListener {
|
||||
|
||||
public static final String TAG = AddNearbyContactFragment.class.getName();
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(TAG);
|
||||
|
||||
@Inject
|
||||
ViewModelProvider.Factory viewModelFactory;
|
||||
|
||||
private AddNearbyContactViewModel viewModel;
|
||||
private CameraView cameraView;
|
||||
private LinearLayout cameraOverlay;
|
||||
private View statusView;
|
||||
private QrCodeView qrCodeView;
|
||||
private TextView status;
|
||||
|
||||
public static AddNearbyContactFragment newInstance() {
|
||||
Bundle args = new Bundle();
|
||||
AddNearbyContactFragment fragment = new AddNearbyContactFragment();
|
||||
fragment.setArguments(args);
|
||||
return fragment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void injectFragment(ActivityComponent component) {
|
||||
component.inject(this);
|
||||
viewModel = new ViewModelProvider(requireActivity(), viewModelFactory)
|
||||
.get(AddNearbyContactViewModel.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);
|
||||
qrCodeView = view.findViewById(R.id.qr_code_view);
|
||||
qrCodeView.setFullscreenListener(this);
|
||||
|
||||
viewModel.getState().observe(getViewLifecycleOwner(),
|
||||
this::onAddContactStateChanged);
|
||||
}
|
||||
|
||||
@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) {
|
||||
// Grow the QR code view to fill its parent
|
||||
statusParams = new LayoutParams(0, 0, 0f);
|
||||
qrCodeParams = new LayoutParams(MATCH_PARENT, MATCH_PARENT, 1f);
|
||||
} else {
|
||||
// Shrink the QR code view to fill half its parent
|
||||
if (cameraOverlay.getOrientation() == HORIZONTAL) {
|
||||
statusParams = new LayoutParams(0, MATCH_PARENT, 1f);
|
||||
qrCodeParams = new LayoutParams(0, MATCH_PARENT, 1f);
|
||||
} else {
|
||||
statusParams = new LayoutParams(MATCH_PARENT, 0, 1f);
|
||||
qrCodeParams = new LayoutParams(MATCH_PARENT, 0, 1f);
|
||||
}
|
||||
}
|
||||
statusView.setLayoutParams(statusParams);
|
||||
qrCodeView.setLayoutParams(qrCodeParams);
|
||||
cameraOverlay.invalidate();
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void onAddContactStateChanged(@Nullable AddContactState state) {
|
||||
if (state instanceof AddContactState.KeyAgreementListening) {
|
||||
Bitmap qrCode =
|
||||
((AddContactState.KeyAgreementListening) state).qrCode;
|
||||
qrCodeView.setQrCode(qrCode);
|
||||
} else if (state instanceof QrCodeScanned) {
|
||||
try {
|
||||
cameraView.stop();
|
||||
} catch (CameraException e) {
|
||||
logCameraExceptionAndFinish(e);
|
||||
}
|
||||
cameraView.setVisibility(INVISIBLE);
|
||||
statusView.setVisibility(VISIBLE);
|
||||
status.setText(R.string.connecting_to_device);
|
||||
} else if (state instanceof KeyAgreementWaiting) {
|
||||
status.setText(R.string.waiting_for_contact_to_scan);
|
||||
} else if (state instanceof KeyAgreementStarted) {
|
||||
qrCodeView.setVisibility(INVISIBLE);
|
||||
status.setText(R.string.authenticating_with_device);
|
||||
} else if (state instanceof ContactExchangeStarted) {
|
||||
status.setText(R.string.exchanging_contact_details);
|
||||
} else if (state instanceof Failed) {
|
||||
// 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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package org.briarproject.briar.android.contact.add.nearby;
|
||||
|
||||
import android.os.Bundle;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.ScrollView;
|
||||
|
||||
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.annotation.Nullable;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import androidx.activity.result.ActivityResultLauncher;
|
||||
import androidx.activity.result.contract.ActivityResultContracts.RequestMultiplePermissions;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
|
||||
import static android.view.View.FOCUS_DOWN;
|
||||
|
||||
@MethodsNotNullByDefault
|
||||
@ParametersNotNullByDefault
|
||||
public class AddNearbyContactIntroFragment extends BaseFragment {
|
||||
|
||||
public static final String TAG =
|
||||
AddNearbyContactIntroFragment.class.getName();
|
||||
|
||||
@Inject
|
||||
ViewModelProvider.Factory viewModelFactory;
|
||||
|
||||
private AddNearbyContactViewModel viewModel;
|
||||
private AddNearbyContactPermissionManager permissionManager;
|
||||
|
||||
private ScrollView scrollView;
|
||||
|
||||
private final ActivityResultLauncher<String[]> permissionLauncher =
|
||||
registerForActivityResult(new RequestMultiplePermissions(), r ->
|
||||
permissionManager.onRequestPermissionResult(r,
|
||||
viewModel::showQrCodeFragmentIfAllowed));
|
||||
|
||||
public static AddNearbyContactIntroFragment newInstance() {
|
||||
Bundle args = new Bundle();
|
||||
AddNearbyContactIntroFragment
|
||||
fragment = new AddNearbyContactIntroFragment();
|
||||
fragment.setArguments(args);
|
||||
return fragment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void injectFragment(ActivityComponent component) {
|
||||
component.inject(this);
|
||||
viewModel = new ViewModelProvider(requireActivity(), viewModelFactory)
|
||||
.get(AddNearbyContactViewModel.class);
|
||||
permissionManager = new AddNearbyContactPermissionManager(
|
||||
requireActivity(), permissionLauncher::launch,
|
||||
viewModel.isBluetoothSupported());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(LayoutInflater inflater,
|
||||
@Nullable ViewGroup container,
|
||||
@Nullable Bundle savedInstanceState) {
|
||||
|
||||
View v = inflater.inflate(R.layout.fragment_keyagreement_id, container,
|
||||
false);
|
||||
scrollView = v.findViewById(R.id.scrollView);
|
||||
View button = v.findViewById(R.id.continueButton);
|
||||
button.setOnClickListener(view -> viewModel.onContinueClicked(() ->
|
||||
permissionManager.checkPermissions()
|
||||
));
|
||||
return v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStart() {
|
||||
super.onStart();
|
||||
// Permissions may have been granted manually while we were stopped
|
||||
permissionManager.resetPermissions();
|
||||
scrollView.post(() -> scrollView.fullScroll(FOCUS_DOWN));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUniqueTag() {
|
||||
return TAG;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.briarproject.briar.android.keyagreement;
|
||||
package org.briarproject.briar.android.contact.add.nearby;
|
||||
|
||||
import org.briarproject.briar.android.viewmodel.ViewModelKey;
|
||||
|
||||
@@ -8,12 +8,12 @@ import dagger.Module;
|
||||
import dagger.multibindings.IntoMap;
|
||||
|
||||
@Module
|
||||
public abstract class ContactExchangeModule {
|
||||
public abstract class AddNearbyContactModule {
|
||||
|
||||
@Binds
|
||||
@IntoMap
|
||||
@ViewModelKey(ContactExchangeViewModel.class)
|
||||
@ViewModelKey(AddNearbyContactViewModel.class)
|
||||
abstract ViewModel bindContactExchangeViewModel(
|
||||
ContactExchangeViewModel contactExchangeViewModel);
|
||||
AddNearbyContactViewModel addNearbyContactViewModel);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package org.briarproject.briar.android.contact.add.nearby;
|
||||
|
||||
import android.content.ActivityNotFoundException;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.location.LocationManager;
|
||||
import android.widget.Toast;
|
||||
|
||||
import org.briarproject.briar.R;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import androidx.annotation.StringRes;
|
||||
import androidx.appcompat.app.AlertDialog;
|
||||
import androidx.core.util.Consumer;
|
||||
import androidx.fragment.app.FragmentActivity;
|
||||
|
||||
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
|
||||
import static android.Manifest.permission.CAMERA;
|
||||
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
|
||||
import static android.os.Build.VERSION.SDK_INT;
|
||||
import static android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS;
|
||||
import static android.widget.Toast.LENGTH_LONG;
|
||||
import static androidx.core.app.ActivityCompat.shouldShowRequestPermissionRationale;
|
||||
import static androidx.core.content.ContextCompat.checkSelfPermission;
|
||||
import static org.briarproject.briar.android.util.UiUtils.getGoToSettingsListener;
|
||||
|
||||
public class AddNearbyContactPermissionManager {
|
||||
|
||||
private enum Permission {
|
||||
UNKNOWN, GRANTED, SHOW_RATIONALE, PERMANENTLY_DENIED
|
||||
}
|
||||
|
||||
private Permission cameraPermission = Permission.UNKNOWN;
|
||||
private Permission locationPermission = Permission.UNKNOWN;
|
||||
|
||||
private final FragmentActivity ctx;
|
||||
private final Consumer<String[]> requestPermissions;
|
||||
private final boolean isBluetoothSupported;
|
||||
|
||||
public AddNearbyContactPermissionManager(FragmentActivity ctx,
|
||||
Consumer<String[]> requestPermissions,
|
||||
boolean isBluetoothSupported) {
|
||||
this.ctx = ctx;
|
||||
this.requestPermissions = requestPermissions;
|
||||
this.isBluetoothSupported = isBluetoothSupported;
|
||||
}
|
||||
|
||||
public void resetPermissions() {
|
||||
cameraPermission = Permission.UNKNOWN;
|
||||
locationPermission = Permission.UNKNOWN;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if location is enabled,
|
||||
* or it isn't required due to this being a SDK < 28 device.
|
||||
*/
|
||||
static boolean isLocationEnabled(Context ctx) {
|
||||
if (SDK_INT >= 28) {
|
||||
LocationManager lm = ctx.getSystemService(LocationManager.class);
|
||||
return lm.isLocationEnabled();
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean areEssentialPermissionsGranted(Context ctx,
|
||||
boolean isBluetoothSupported) {
|
||||
int ok = PERMISSION_GRANTED;
|
||||
return checkSelfPermission(ctx, CAMERA) == ok &&
|
||||
(SDK_INT < 23 ||
|
||||
checkSelfPermission(ctx, ACCESS_FINE_LOCATION) == ok ||
|
||||
!isBluetoothSupported);
|
||||
}
|
||||
|
||||
private boolean areEssentialPermissionsGranted() {
|
||||
return cameraPermission == Permission.GRANTED &&
|
||||
(SDK_INT < 23 || locationPermission == Permission.GRANTED ||
|
||||
!isBluetoothSupported);
|
||||
}
|
||||
|
||||
public boolean checkPermissions() {
|
||||
boolean locationEnabled = isLocationEnabled(ctx);
|
||||
if (locationEnabled && areEssentialPermissionsGranted()) return true;
|
||||
// If an essential permission has been permanently denied, ask the
|
||||
// user to change the setting
|
||||
if (cameraPermission == Permission.PERMANENTLY_DENIED) {
|
||||
showDenialDialog(R.string.permission_camera_title,
|
||||
R.string.permission_camera_denied_body);
|
||||
return false;
|
||||
}
|
||||
if (isBluetoothSupported &&
|
||||
locationPermission == Permission.PERMANENTLY_DENIED) {
|
||||
showDenialDialog(R.string.permission_location_title,
|
||||
R.string.permission_location_denied_body);
|
||||
return false;
|
||||
}
|
||||
// Should we show the rationale for one or both permissions?
|
||||
if (cameraPermission == Permission.SHOW_RATIONALE &&
|
||||
locationPermission == Permission.SHOW_RATIONALE) {
|
||||
showRationale(R.string.permission_camera_location_title,
|
||||
R.string.permission_camera_location_request_body);
|
||||
} else if (cameraPermission == Permission.SHOW_RATIONALE) {
|
||||
showRationale(R.string.permission_camera_title,
|
||||
R.string.permission_camera_request_body);
|
||||
} else if (locationPermission == Permission.SHOW_RATIONALE) {
|
||||
showRationale(R.string.permission_location_title,
|
||||
R.string.permission_location_request_body);
|
||||
} else if (isLocationEnabled(ctx)) {
|
||||
requestPermissions();
|
||||
} else {
|
||||
showLocationDialog(ctx);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void showDenialDialog(@StringRes int title, @StringRes int body) {
|
||||
AlertDialog.Builder builder =
|
||||
new AlertDialog.Builder(ctx, R.style.BriarDialogTheme);
|
||||
builder.setTitle(title);
|
||||
builder.setMessage(body);
|
||||
builder.setPositiveButton(R.string.ok, getGoToSettingsListener(ctx));
|
||||
builder.setNegativeButton(R.string.cancel,
|
||||
(dialog, which) -> ctx.supportFinishAfterTransition());
|
||||
builder.show();
|
||||
}
|
||||
|
||||
private void showRationale(@StringRes int title, @StringRes int body) {
|
||||
AlertDialog.Builder builder =
|
||||
new AlertDialog.Builder(ctx, R.style.BriarDialogTheme);
|
||||
builder.setTitle(title);
|
||||
builder.setMessage(body);
|
||||
builder.setNeutralButton(R.string.continue_button,
|
||||
(dialog, which) -> requestPermissions());
|
||||
builder.show();
|
||||
}
|
||||
|
||||
private static void showLocationDialog(Context ctx) {
|
||||
AlertDialog.Builder builder =
|
||||
new AlertDialog.Builder(ctx, R.style.BriarDialogTheme);
|
||||
builder.setTitle(R.string.permission_location_setting_title);
|
||||
builder.setMessage(R.string.permission_location_setting_body);
|
||||
builder.setNegativeButton(R.string.cancel, null);
|
||||
builder.setPositiveButton(R.string.permission_location_setting_button,
|
||||
(dialog, which) -> {
|
||||
Intent i = new Intent(ACTION_LOCATION_SOURCE_SETTINGS);
|
||||
try {
|
||||
ctx.startActivity(i);
|
||||
} catch (ActivityNotFoundException e) {
|
||||
Toast.makeText(ctx, R.string.error_start_activity,
|
||||
LENGTH_LONG).show();
|
||||
}
|
||||
});
|
||||
builder.show();
|
||||
}
|
||||
|
||||
private void requestPermissions() {
|
||||
String[] permissions;
|
||||
if (isBluetoothSupported) {
|
||||
permissions = new String[] {CAMERA, ACCESS_FINE_LOCATION};
|
||||
} else {
|
||||
permissions = new String[] {CAMERA};
|
||||
}
|
||||
requestPermissions.accept(permissions);
|
||||
}
|
||||
|
||||
public void onRequestPermissionResult(Map<String, Boolean> result,
|
||||
Runnable onPermissionsGranted) {
|
||||
if (gotPermission(CAMERA, result)) {
|
||||
cameraPermission = Permission.GRANTED;
|
||||
} else if (shouldShowRationale(CAMERA)) {
|
||||
cameraPermission = Permission.SHOW_RATIONALE;
|
||||
} else {
|
||||
cameraPermission = Permission.PERMANENTLY_DENIED;
|
||||
}
|
||||
if (isBluetoothSupported) {
|
||||
if (gotPermission(ACCESS_FINE_LOCATION, result)) {
|
||||
locationPermission = Permission.GRANTED;
|
||||
} else if (shouldShowRationale(ACCESS_FINE_LOCATION)) {
|
||||
locationPermission = Permission.SHOW_RATIONALE;
|
||||
} else {
|
||||
locationPermission = Permission.PERMANENTLY_DENIED;
|
||||
}
|
||||
}
|
||||
// If a permission dialog has been shown, showing the QR code fragment
|
||||
// on this call path would cause a crash due to
|
||||
// https://code.google.com/p/android/issues/detail?id=190966.
|
||||
// In that case the isResumed flag prevents the fragment from being
|
||||
// shown here, and showQrCodeFragmentIfAllowed() will be called again
|
||||
// from onPostResume().
|
||||
if (checkPermissions()) onPermissionsGranted.run();
|
||||
}
|
||||
|
||||
private boolean gotPermission(String permission,
|
||||
Map<String, Boolean> result) {
|
||||
Boolean permissionResult = result.get(permission);
|
||||
return permissionResult == null ?
|
||||
isGranted(permission) : permissionResult;
|
||||
}
|
||||
|
||||
private boolean isGranted(String permission) {
|
||||
return checkSelfPermission(ctx, permission) == PERMISSION_GRANTED;
|
||||
}
|
||||
|
||||
private boolean shouldShowRationale(String permission) {
|
||||
return shouldShowRequestPermissionRationale(ctx, permission);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,532 @@
|
||||
package org.briarproject.briar.android.contact.add.nearby;
|
||||
|
||||
import android.app.Application;
|
||||
import android.bluetooth.BluetoothAdapter;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.graphics.Bitmap;
|
||||
import android.util.DisplayMetrics;
|
||||
import android.widget.Toast;
|
||||
|
||||
import com.google.zxing.Result;
|
||||
|
||||
import org.briarproject.bramble.api.UnsupportedVersionException;
|
||||
import org.briarproject.bramble.api.connection.ConnectionManager;
|
||||
import org.briarproject.bramble.api.contact.Contact;
|
||||
import org.briarproject.bramble.api.contact.ContactExchangeManager;
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.db.ContactExistsException;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
import org.briarproject.bramble.api.event.Event;
|
||||
import org.briarproject.bramble.api.event.EventBus;
|
||||
import org.briarproject.bramble.api.event.EventListener;
|
||||
import org.briarproject.bramble.api.keyagreement.KeyAgreementResult;
|
||||
import org.briarproject.bramble.api.keyagreement.KeyAgreementTask;
|
||||
import org.briarproject.bramble.api.keyagreement.Payload;
|
||||
import org.briarproject.bramble.api.keyagreement.PayloadEncoder;
|
||||
import org.briarproject.bramble.api.keyagreement.PayloadParser;
|
||||
import org.briarproject.bramble.api.keyagreement.event.KeyAgreementAbortedEvent;
|
||||
import org.briarproject.bramble.api.keyagreement.event.KeyAgreementFailedEvent;
|
||||
import org.briarproject.bramble.api.keyagreement.event.KeyAgreementFinishedEvent;
|
||||
import org.briarproject.bramble.api.keyagreement.event.KeyAgreementListeningEvent;
|
||||
import org.briarproject.bramble.api.keyagreement.event.KeyAgreementStartedEvent;
|
||||
import org.briarproject.bramble.api.keyagreement.event.KeyAgreementWaitingEvent;
|
||||
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.BluetoothConstants;
|
||||
import org.briarproject.bramble.api.plugin.LanTcpConstants;
|
||||
import org.briarproject.bramble.api.plugin.Plugin;
|
||||
import org.briarproject.bramble.api.plugin.Plugin.State;
|
||||
import org.briarproject.bramble.api.plugin.PluginManager;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportStateEvent;
|
||||
import org.briarproject.bramble.api.system.AndroidExecutor;
|
||||
import org.briarproject.briar.R;
|
||||
import org.briarproject.briar.android.contact.add.nearby.AddContactState.ContactExchangeFinished;
|
||||
import org.briarproject.briar.android.contact.add.nearby.AddContactState.ContactExchangeResult.Error;
|
||||
import org.briarproject.briar.android.contact.add.nearby.AddContactState.ContactExchangeResult.Success;
|
||||
import org.briarproject.briar.android.contact.add.nearby.AddContactState.ContactExchangeStarted;
|
||||
import org.briarproject.briar.android.contact.add.nearby.AddContactState.KeyAgreementListening;
|
||||
import org.briarproject.briar.android.contact.add.nearby.AddContactState.KeyAgreementStarted;
|
||||
import org.briarproject.briar.android.contact.add.nearby.AddContactState.KeyAgreementWaiting;
|
||||
import org.briarproject.briar.android.viewmodel.LiveEvent;
|
||||
import org.briarproject.briar.android.viewmodel.MutableLiveEvent;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Provider;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.annotation.UiThread;
|
||||
import androidx.core.util.Supplier;
|
||||
import androidx.lifecycle.AndroidViewModel;
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
|
||||
import static android.bluetooth.BluetoothAdapter.ACTION_SCAN_MODE_CHANGED;
|
||||
import static android.bluetooth.BluetoothAdapter.EXTRA_SCAN_MODE;
|
||||
import static android.bluetooth.BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE;
|
||||
import static android.widget.Toast.LENGTH_LONG;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
import static java.util.logging.Level.INFO;
|
||||
import static java.util.logging.Level.WARNING;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
import static org.briarproject.bramble.api.plugin.Plugin.State.ACTIVE;
|
||||
import static org.briarproject.bramble.api.plugin.Plugin.State.DISABLED;
|
||||
import static org.briarproject.bramble.api.plugin.Plugin.State.INACTIVE;
|
||||
import static org.briarproject.bramble.api.plugin.Plugin.State.STARTING_STOPPING;
|
||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||
import static org.briarproject.briar.android.contact.add.nearby.AddNearbyContactPermissionManager.areEssentialPermissionsGranted;
|
||||
import static org.briarproject.briar.android.contact.add.nearby.AddNearbyContactPermissionManager.isLocationEnabled;
|
||||
import static org.briarproject.briar.android.contact.add.nearby.AddNearbyContactViewModel.BluetoothDecision.NO_ADAPTER;
|
||||
import static org.briarproject.briar.android.contact.add.nearby.AddNearbyContactViewModel.BluetoothDecision.REFUSED;
|
||||
import static org.briarproject.briar.android.contact.add.nearby.AddNearbyContactViewModel.BluetoothDecision.UNKNOWN;
|
||||
|
||||
@NotNullByDefault
|
||||
class AddNearbyContactViewModel extends AndroidViewModel
|
||||
implements EventListener, QrCodeDecoder.ResultCallback {
|
||||
|
||||
private static final Logger LOG =
|
||||
getLogger(AddNearbyContactViewModel.class.getName());
|
||||
|
||||
enum BluetoothDecision {
|
||||
/**
|
||||
* We haven't asked the user about Bluetooth discoverability.
|
||||
*/
|
||||
UNKNOWN,
|
||||
|
||||
/**
|
||||
* The device doesn't have a Bluetooth adapter.
|
||||
*/
|
||||
NO_ADAPTER,
|
||||
|
||||
/**
|
||||
* We're waiting for the user to accept or refuse discoverability.
|
||||
*/
|
||||
WAITING,
|
||||
|
||||
/**
|
||||
* The user has accepted discoverability.
|
||||
*/
|
||||
ACCEPTED,
|
||||
|
||||
/**
|
||||
* The user has refused discoverability.
|
||||
*/
|
||||
REFUSED
|
||||
}
|
||||
|
||||
@SuppressWarnings("CharsetObjectCanBeUsed") // Requires minSdkVersion >= 19
|
||||
private static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
|
||||
|
||||
private final EventBus eventBus;
|
||||
private final AndroidExecutor androidExecutor;
|
||||
private final Executor ioExecutor;
|
||||
private final PluginManager pluginManager;
|
||||
private final PayloadEncoder payloadEncoder;
|
||||
private final PayloadParser payloadParser;
|
||||
private final Provider<KeyAgreementTask> keyAgreementTaskProvider;
|
||||
private final ContactExchangeManager contactExchangeManager;
|
||||
private final ConnectionManager connectionManager;
|
||||
|
||||
private final MutableLiveEvent<Boolean> requestBluetoothDiscoverable =
|
||||
new MutableLiveEvent<>();
|
||||
private final MutableLiveEvent<Boolean> showQrCodeFragment =
|
||||
new MutableLiveEvent<>();
|
||||
private final MutableLiveData<AddContactState> state =
|
||||
new MutableLiveData<>();
|
||||
|
||||
private final QrCodeDecoder qrCodeDecoder;
|
||||
private final BroadcastReceiver bluetoothReceiver =
|
||||
new BluetoothStateReceiver();
|
||||
|
||||
@Nullable
|
||||
private final BluetoothAdapter bt;
|
||||
@Nullable
|
||||
private final Plugin wifiPlugin, bluetoothPlugin;
|
||||
|
||||
// UiThread
|
||||
private BluetoothDecision bluetoothDecision = BluetoothDecision.UNKNOWN;
|
||||
|
||||
private boolean wasContinueClicked = false;
|
||||
private boolean isActivityResumed = false;
|
||||
|
||||
/**
|
||||
* Records whether we've enabled the wifi plugin so we don't enable it more
|
||||
* than once.
|
||||
*/
|
||||
private boolean hasEnabledWifi = false;
|
||||
|
||||
/**
|
||||
* Records whether we've enabled the Bluetooth plugin so we don't enable it
|
||||
* more than once.
|
||||
*/
|
||||
private boolean hasEnabledBluetooth = false;
|
||||
|
||||
@Nullable
|
||||
private volatile KeyAgreementTask task;
|
||||
private volatile boolean gotLocalPayload = false, gotRemotePayload = false;
|
||||
|
||||
@Inject
|
||||
AddNearbyContactViewModel(Application app,
|
||||
EventBus eventBus,
|
||||
AndroidExecutor androidExecutor,
|
||||
@IoExecutor Executor ioExecutor,
|
||||
PluginManager pluginManager,
|
||||
PayloadEncoder payloadEncoder,
|
||||
PayloadParser payloadParser,
|
||||
Provider<KeyAgreementTask> keyAgreementTaskProvider,
|
||||
ContactExchangeManager contactExchangeManager,
|
||||
ConnectionManager connectionManager) {
|
||||
super(app);
|
||||
this.eventBus = eventBus;
|
||||
this.androidExecutor = androidExecutor;
|
||||
this.ioExecutor = ioExecutor;
|
||||
this.pluginManager = pluginManager;
|
||||
this.payloadEncoder = payloadEncoder;
|
||||
this.payloadParser = payloadParser;
|
||||
this.keyAgreementTaskProvider = keyAgreementTaskProvider;
|
||||
this.contactExchangeManager = contactExchangeManager;
|
||||
this.connectionManager = connectionManager;
|
||||
bt = BluetoothAdapter.getDefaultAdapter();
|
||||
wifiPlugin = pluginManager.getPlugin(LanTcpConstants.ID);
|
||||
bluetoothPlugin = pluginManager.getPlugin(BluetoothConstants.ID);
|
||||
qrCodeDecoder = new QrCodeDecoder(androidExecutor, ioExecutor, this);
|
||||
eventBus.addListener(this);
|
||||
IntentFilter filter = new IntentFilter(ACTION_SCAN_MODE_CHANGED);
|
||||
getApplication().registerReceiver(bluetoothReceiver, filter);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCleared() {
|
||||
super.onCleared();
|
||||
getApplication().unregisterReceiver(bluetoothReceiver);
|
||||
eventBus.removeListener(this);
|
||||
stopListening();
|
||||
}
|
||||
|
||||
@UiThread
|
||||
void onContinueClicked(Supplier<Boolean> checkPermissions) {
|
||||
if (bluetoothDecision == REFUSED) {
|
||||
bluetoothDecision = UNKNOWN; // Ask again
|
||||
}
|
||||
wasContinueClicked = true;
|
||||
if (checkPermissions.get()) showQrCodeFragmentIfAllowed();
|
||||
}
|
||||
|
||||
@UiThread
|
||||
boolean isBluetoothSupported() {
|
||||
return bt != null && bluetoothPlugin != null;
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private boolean isWifiReady() {
|
||||
if (wifiPlugin == null) return true; // Continue without wifi
|
||||
State state = wifiPlugin.getState();
|
||||
// Wait for plugin to become enabled
|
||||
return state == ACTIVE || state == INACTIVE;
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private boolean isBluetoothReady() {
|
||||
if (bt == null || bluetoothPlugin == null) {
|
||||
// Continue without Bluetooth
|
||||
return true;
|
||||
}
|
||||
if (bluetoothDecision == BluetoothDecision.UNKNOWN ||
|
||||
bluetoothDecision == BluetoothDecision.WAITING ||
|
||||
bluetoothDecision == BluetoothDecision.REFUSED) {
|
||||
// Wait for user to accept
|
||||
return false;
|
||||
}
|
||||
if (bt.getScanMode() != SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
|
||||
// Wait for adapter to become discoverable
|
||||
return false;
|
||||
}
|
||||
// Wait for plugin to become active
|
||||
return bluetoothPlugin.getState() == ACTIVE;
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void enableWifiIfWeShould() {
|
||||
if (hasEnabledWifi) return;
|
||||
if (wifiPlugin == null) return;
|
||||
State state = wifiPlugin.getState();
|
||||
if (state == STARTING_STOPPING || state == DISABLED) {
|
||||
LOG.info("Enabling wifi plugin");
|
||||
hasEnabledWifi = true;
|
||||
pluginManager.setPluginEnabled(LanTcpConstants.ID, true);
|
||||
}
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void enableBluetoothIfWeShould() {
|
||||
if (bluetoothDecision != BluetoothDecision.ACCEPTED) return;
|
||||
if (hasEnabledBluetooth) return;
|
||||
if (bluetoothPlugin == null || !isBluetoothSupported()) return;
|
||||
State state = bluetoothPlugin.getState();
|
||||
if (state == STARTING_STOPPING || state == DISABLED) {
|
||||
LOG.info("Enabling Bluetooth plugin");
|
||||
hasEnabledBluetooth = true;
|
||||
pluginManager.setPluginEnabled(BluetoothConstants.ID, true);
|
||||
}
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void startAddingContact() {
|
||||
// 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, ask for Bluetooth
|
||||
// discoverability again before showing the QR code fragment
|
||||
bluetoothDecision = UNKNOWN;
|
||||
// If we return to the intro fragment, we may need to enable wifi and
|
||||
// Bluetooth again
|
||||
hasEnabledWifi = false;
|
||||
hasEnabledBluetooth = false;
|
||||
// reset state, so we don't show an old QR code again
|
||||
state.setValue(null);
|
||||
// start to listen with a KeyAgreementTask
|
||||
startListening();
|
||||
showQrCodeFragment.setEvent(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Call this once Bluetooth and Wi-Fi are ready to be used.
|
||||
* It is possible to call this more than once over the ViewModel's lifetime.
|
||||
*/
|
||||
@UiThread
|
||||
private void startListening() {
|
||||
KeyAgreementTask oldTask = task;
|
||||
KeyAgreementTask newTask = keyAgreementTaskProvider.get();
|
||||
task = newTask;
|
||||
ioExecutor.execute(() -> {
|
||||
if (oldTask != null) oldTask.stopListening();
|
||||
newTask.listen();
|
||||
});
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void stopListening() {
|
||||
KeyAgreementTask oldTask = task;
|
||||
ioExecutor.execute(() -> {
|
||||
if (oldTask != null) oldTask.stopListening();
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void eventOccurred(Event e) {
|
||||
if (e instanceof TransportStateEvent) {
|
||||
TransportStateEvent t = (TransportStateEvent) e;
|
||||
if (t.getTransportId().equals(BluetoothConstants.ID)) {
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info("Bluetooth state changed to " + t.getState());
|
||||
}
|
||||
showQrCodeFragmentIfAllowed();
|
||||
} else if (t.getTransportId().equals(LanTcpConstants.ID)) {
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info("Wifi state changed to " + t.getState());
|
||||
}
|
||||
showQrCodeFragmentIfAllowed();
|
||||
}
|
||||
} else if (e instanceof KeyAgreementListeningEvent) {
|
||||
LOG.info("KeyAgreementListeningEvent received");
|
||||
KeyAgreementListeningEvent event = (KeyAgreementListeningEvent) e;
|
||||
onLocalPayloadReceived(event.getLocalPayload());
|
||||
} else if (e instanceof KeyAgreementWaitingEvent) {
|
||||
LOG.info("KeyAgreementWaitingEvent received");
|
||||
state.setValue(new KeyAgreementWaiting());
|
||||
} else if (e instanceof KeyAgreementStartedEvent) {
|
||||
LOG.info("KeyAgreementStartedEvent received");
|
||||
state.setValue(new KeyAgreementStarted());
|
||||
} else if (e instanceof KeyAgreementFinishedEvent) {
|
||||
LOG.info("KeyAgreementFinishedEvent received");
|
||||
KeyAgreementResult result =
|
||||
((KeyAgreementFinishedEvent) e).getResult();
|
||||
startContactExchange(result);
|
||||
state.setValue(new ContactExchangeStarted());
|
||||
} else if (e instanceof KeyAgreementAbortedEvent) {
|
||||
LOG.info("KeyAgreementAbortedEvent received");
|
||||
resetPayloadFlags();
|
||||
state.setValue(new AddContactState.Failed());
|
||||
} else if (e instanceof KeyAgreementFailedEvent) {
|
||||
LOG.info("KeyAgreementFailedEvent received");
|
||||
resetPayloadFlags();
|
||||
state.setValue(new AddContactState.Failed());
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("StatementWithEmptyBody")
|
||||
@UiThread
|
||||
void showQrCodeFragmentIfAllowed() {
|
||||
boolean permissionsGranted = areEssentialPermissionsGranted(
|
||||
getApplication(), isBluetoothSupported());
|
||||
boolean locationEnabled = isLocationEnabled(getApplication());
|
||||
if (isActivityResumed && wasContinueClicked && permissionsGranted &&
|
||||
locationEnabled) {
|
||||
if (isWifiReady() && isBluetoothReady()) {
|
||||
LOG.info("Wifi and Bluetooth are ready");
|
||||
startAddingContact();
|
||||
} else {
|
||||
enableWifiIfWeShould();
|
||||
if (bluetoothDecision == UNKNOWN) {
|
||||
if (isBluetoothSupported()) {
|
||||
requestBluetoothDiscoverable.setEvent(true);
|
||||
} else {
|
||||
bluetoothDecision = NO_ADAPTER;
|
||||
}
|
||||
} else if (bluetoothDecision == REFUSED) {
|
||||
// Ask again when the user clicks "continue"
|
||||
} else {
|
||||
enableBluetoothIfWeShould();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This sets the QR code by setting the state to KeyAgreementListening.
|
||||
*/
|
||||
private void onLocalPayloadReceived(Payload localPayload) {
|
||||
if (gotLocalPayload) return;
|
||||
DisplayMetrics dm = getApplication().getResources().getDisplayMetrics();
|
||||
ioExecutor.execute(() -> {
|
||||
byte[] payloadBytes = payloadEncoder.encode(localPayload);
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info("Local payload is " + payloadBytes.length
|
||||
+ " bytes");
|
||||
}
|
||||
// Use ISO 8859-1 to encode bytes directly as a string
|
||||
String content = new String(payloadBytes, ISO_8859_1);
|
||||
Bitmap qrCode = QrCodeUtils.createQrCode(dm, content);
|
||||
gotLocalPayload = true;
|
||||
state.postValue(new KeyAgreementListening(qrCode));
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
@IoExecutor
|
||||
public void onQrCodeDecoded(Result result) {
|
||||
LOG.info("Got result from decoder");
|
||||
// Ignore results until the KeyAgreementTask is ready
|
||||
if (!gotLocalPayload || gotRemotePayload) return;
|
||||
try {
|
||||
byte[] payloadBytes = result.getText().getBytes(ISO_8859_1);
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Remote payload is " + payloadBytes.length + " bytes");
|
||||
Payload remotePayload = payloadParser.parse(payloadBytes);
|
||||
gotRemotePayload = true;
|
||||
requireNonNull(task).connectAndRunProtocol(remotePayload);
|
||||
state.postValue(new AddContactState.QrCodeScanned());
|
||||
} catch (UnsupportedVersionException e) {
|
||||
resetPayloadFlags();
|
||||
state.postValue(new AddContactState.Failed(e.isTooOld()));
|
||||
} catch (IOException | IllegalArgumentException e) {
|
||||
LOG.log(WARNING, "QR Code Invalid", e);
|
||||
androidExecutor.runOnUiThread(() -> Toast.makeText(getApplication(),
|
||||
R.string.qr_code_invalid, LENGTH_LONG).show());
|
||||
resetPayloadFlags();
|
||||
state.postValue(new AddContactState.Failed());
|
||||
}
|
||||
}
|
||||
|
||||
private void resetPayloadFlags() {
|
||||
gotRemotePayload = false;
|
||||
gotLocalPayload = false;
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void startContactExchange(KeyAgreementResult result) {
|
||||
TransportId t = result.getTransportId();
|
||||
DuplexTransportConnection conn = result.getConnection();
|
||||
SecretKey masterKey = result.getMasterKey();
|
||||
boolean alice = result.wasAlice();
|
||||
ioExecutor.execute(() -> {
|
||||
try {
|
||||
Contact contact = contactExchangeManager.exchangeContacts(conn,
|
||||
masterKey, alice, true);
|
||||
// Reuse the connection as a transport connection
|
||||
connectionManager
|
||||
.manageOutgoingConnection(contact.getId(), t, conn);
|
||||
Success success = new Success(contact.getAuthor());
|
||||
state.postValue(new ContactExchangeFinished(success));
|
||||
} catch (ContactExistsException e) {
|
||||
tryToClose(conn);
|
||||
Error error = new Error(e.getRemoteAuthor());
|
||||
state.postValue(new ContactExchangeFinished(error));
|
||||
} catch (DbException | IOException e) {
|
||||
tryToClose(conn);
|
||||
logException(LOG, WARNING, e);
|
||||
Error error = new Error(null);
|
||||
state.postValue(new ContactExchangeFinished(error));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private class BluetoothStateReceiver extends BroadcastReceiver {
|
||||
@UiThread
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
int scanMode = intent.getIntExtra(EXTRA_SCAN_MODE, -1);
|
||||
LOG.info("Bluetooth scan mode changed: " + scanMode);
|
||||
showQrCodeFragmentIfAllowed();
|
||||
}
|
||||
}
|
||||
|
||||
private void tryToClose(DuplexTransportConnection conn) {
|
||||
try {
|
||||
conn.getReader().dispose(true, true);
|
||||
conn.getWriter().dispose(true);
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
@UiThread
|
||||
void setIsActivityResumed(boolean resumed) {
|
||||
isActivityResumed = resumed;
|
||||
// Workaround for
|
||||
// https://code.google.com/p/android/issues/detail?id=190966
|
||||
showQrCodeFragmentIfAllowed();
|
||||
}
|
||||
|
||||
@UiThread
|
||||
void setBluetoothDecision(BluetoothDecision decision) {
|
||||
bluetoothDecision = decision;
|
||||
showQrCodeFragmentIfAllowed();
|
||||
}
|
||||
|
||||
QrCodeDecoder getQrCodeDecoder() {
|
||||
return qrCodeDecoder;
|
||||
}
|
||||
|
||||
LiveEvent<Boolean> getRequestBluetoothDiscoverable() {
|
||||
return requestBluetoothDiscoverable;
|
||||
}
|
||||
|
||||
LiveEvent<Boolean> getShowQrCodeFragment() {
|
||||
return showQrCodeFragment;
|
||||
}
|
||||
|
||||
/**
|
||||
* This LiveData will be null initially.
|
||||
*/
|
||||
LiveData<AddContactState> getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
package org.briarproject.briar.android.keyagreement;
|
||||
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);
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.briarproject.briar.android.keyagreement;
|
||||
package org.briarproject.briar.android.contact.add.nearby;
|
||||
|
||||
import android.content.Context;
|
||||
import android.hardware.Camera;
|
||||
@@ -40,7 +40,6 @@ import static java.util.logging.Level.INFO;
|
||||
import static java.util.logging.Level.WARNING;
|
||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@MethodsNotNullByDefault
|
||||
@ParametersNotNullByDefault
|
||||
public class CameraView extends SurfaceView implements SurfaceHolder.Callback,
|
||||
@@ -126,8 +125,14 @@ public class CameraView extends SurfaceView implements SurfaceHolder.Callback,
|
||||
throw new CameraException(e);
|
||||
}
|
||||
setDisplayOrientation(getScreenRotationDegrees());
|
||||
if (camera == null) throw new CameraException("No camera found");
|
||||
// Use barcode scene mode if it's available
|
||||
Parameters params = camera.getParameters();
|
||||
Parameters params;
|
||||
try {
|
||||
params = camera.getParameters();
|
||||
} catch (RuntimeException e) {
|
||||
throw new CameraException(e);
|
||||
}
|
||||
params = setSceneMode(camera, params);
|
||||
if (SCENE_MODE_BARCODE.equals(params.getSceneMode())) {
|
||||
// If the scene mode enabled the flash, try to disable it
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.briarproject.briar.android.keyagreement;
|
||||
package org.briarproject.briar.android.contact.add.nearby;
|
||||
|
||||
import android.hardware.Camera;
|
||||
|
||||
@@ -6,7 +6,6 @@ import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import androidx.annotation.UiThread;
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@NotNullByDefault
|
||||
interface PreviewConsumer {
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
package org.briarproject.briar.android.keyagreement;
|
||||
package org.briarproject.briar.android.contact.add.nearby;
|
||||
|
||||
import android.hardware.Camera;
|
||||
import android.hardware.Camera.CameraInfo;
|
||||
import android.hardware.Camera.PreviewCallback;
|
||||
import android.hardware.Camera.Size;
|
||||
import android.os.AsyncTask;
|
||||
|
||||
import com.google.zxing.BinaryBitmap;
|
||||
import com.google.zxing.LuminanceSource;
|
||||
@@ -15,10 +14,13 @@ import com.google.zxing.Result;
|
||||
import com.google.zxing.common.HybridBinarizer;
|
||||
import com.google.zxing.qrcode.QRCodeReader;
|
||||
|
||||
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
|
||||
import org.briarproject.bramble.api.system.AndroidExecutor;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import androidx.annotation.UiThread;
|
||||
@@ -26,22 +28,26 @@ import androidx.annotation.UiThread;
|
||||
import static com.google.zxing.DecodeHintType.CHARACTER_SET;
|
||||
import static java.util.Collections.singletonMap;
|
||||
import static java.util.logging.Level.WARNING;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@MethodsNotNullByDefault
|
||||
@ParametersNotNullByDefault
|
||||
class QrCodeDecoder implements PreviewConsumer, PreviewCallback {
|
||||
public class QrCodeDecoder implements PreviewConsumer, PreviewCallback {
|
||||
|
||||
private static final Logger LOG =
|
||||
Logger.getLogger(QrCodeDecoder.class.getName());
|
||||
private static final Logger LOG = getLogger(QrCodeDecoder.class.getName());
|
||||
|
||||
private final AndroidExecutor androidExecutor;
|
||||
private final Executor ioExecutor;
|
||||
private final Reader reader = new QRCodeReader();
|
||||
private final ResultCallback callback;
|
||||
|
||||
private Camera camera = null;
|
||||
private int cameraIndex = 0;
|
||||
|
||||
QrCodeDecoder(ResultCallback callback) {
|
||||
public QrCodeDecoder(AndroidExecutor androidExecutor,
|
||||
@IoExecutor Executor ioExecutor, ResultCallback callback) {
|
||||
this.androidExecutor = androidExecutor;
|
||||
this.ioExecutor = ioExecutor;
|
||||
this.callback = callback;
|
||||
}
|
||||
|
||||
@@ -74,8 +80,7 @@ class QrCodeDecoder implements PreviewConsumer, PreviewCallback {
|
||||
if (data.length == size.width * size.height * 3 / 2) {
|
||||
CameraInfo info = new CameraInfo();
|
||||
Camera.getCameraInfo(cameraIndex, info);
|
||||
new DecoderTask(data, size.width, size.height,
|
||||
info.orientation).execute();
|
||||
decode(data, size.width, size.height, info.orientation);
|
||||
} else {
|
||||
// Camera parameters have changed - ask for a new preview
|
||||
LOG.info("Preview size does not match camera parameters");
|
||||
@@ -89,43 +94,23 @@ class QrCodeDecoder implements PreviewConsumer, PreviewCallback {
|
||||
}
|
||||
}
|
||||
|
||||
private class DecoderTask extends AsyncTask<Void, Void, Void> {
|
||||
|
||||
private final byte[] data;
|
||||
private final int width, height, orientation;
|
||||
|
||||
private DecoderTask(byte[] data, int width, int height,
|
||||
int orientation) {
|
||||
this.data = data;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.orientation = orientation;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Void doInBackground(Void... params) {
|
||||
private void decode(byte[] data, int width, int height, int orientation) {
|
||||
ioExecutor.execute(() -> {
|
||||
BinaryBitmap bitmap = binarize(data, width, height, orientation);
|
||||
Result result;
|
||||
try {
|
||||
result = reader.decode(bitmap,
|
||||
singletonMap(CHARACTER_SET, "ISO8859_1"));
|
||||
callback.onQrCodeDecoded(result);
|
||||
} catch (ReaderException e) {
|
||||
// No barcode found
|
||||
return null;
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warning("Invalid preview frame");
|
||||
return null;
|
||||
} finally {
|
||||
reader.reset();
|
||||
androidExecutor.runOnUiThread(this::askForPreviewFrame);
|
||||
}
|
||||
callback.handleResult(result);
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPostExecute(Void result) {
|
||||
askForPreviewFrame();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static BinaryBitmap binarize(byte[] data, int width, int height,
|
||||
@@ -142,8 +127,8 @@ class QrCodeDecoder implements PreviewConsumer, PreviewCallback {
|
||||
}
|
||||
|
||||
@NotNullByDefault
|
||||
interface ResultCallback {
|
||||
|
||||
void handleResult(Result result);
|
||||
public interface ResultCallback {
|
||||
@IoExecutor
|
||||
void onQrCodeDecoded(Result result);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.briarproject.briar.android.keyagreement;
|
||||
package org.briarproject.briar.android.contact.add.nearby;
|
||||
|
||||
import android.graphics.Bitmap;
|
||||
import android.util.DisplayMetrics;
|
||||
@@ -18,16 +18,16 @@ import static android.graphics.Color.BLACK;
|
||||
import static android.graphics.Color.WHITE;
|
||||
import static com.google.zxing.BarcodeFormat.QR_CODE;
|
||||
import static java.util.logging.Level.WARNING;
|
||||
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 =
|
||||
Logger.getLogger(QrCodeUtils.class.getName());
|
||||
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
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
package org.briarproject.briar.android.keyagreement;
|
||||
|
||||
import android.os.Bundle;
|
||||
import android.widget.Toast;
|
||||
|
||||
import org.briarproject.bramble.api.identity.Author;
|
||||
import org.briarproject.bramble.api.keyagreement.KeyAgreementResult;
|
||||
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 javax.annotation.Nullable;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import androidx.annotation.UiThread;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
import androidx.lifecycle.ViewModelProviders;
|
||||
|
||||
import static android.widget.Toast.LENGTH_LONG;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
@MethodsNotNullByDefault
|
||||
@ParametersNotNullByDefault
|
||||
public class ContactExchangeActivity extends KeyAgreementActivity {
|
||||
|
||||
@Inject
|
||||
ViewModelProvider.Factory viewModelFactory;
|
||||
|
||||
private ContactExchangeViewModel viewModel;
|
||||
|
||||
@Override
|
||||
public void injectActivity(ActivityComponent component) {
|
||||
component.inject(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate(@Nullable Bundle state) {
|
||||
super.onCreate(state);
|
||||
requireNonNull(getSupportActionBar())
|
||||
.setTitle(R.string.add_contact_title);
|
||||
viewModel = ViewModelProviders.of(this, viewModelFactory)
|
||||
.get(ContactExchangeViewModel.class);
|
||||
}
|
||||
|
||||
private void startContactExchange(KeyAgreementResult result) {
|
||||
viewModel.getSucceeded().observe(this, succeeded -> {
|
||||
if (succeeded == null) return;
|
||||
if (succeeded) {
|
||||
Author remote = requireNonNull(viewModel.getRemoteAuthor());
|
||||
contactExchangeSucceeded(remote);
|
||||
} else {
|
||||
Author duplicate = viewModel.getDuplicateAuthor();
|
||||
if (duplicate == null) contactExchangeFailed();
|
||||
else duplicateContact(duplicate);
|
||||
}
|
||||
});
|
||||
viewModel.startContactExchange(result.getTransportId(),
|
||||
result.getConnection(), result.getMasterKey(),
|
||||
result.wasAlice());
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void contactExchangeSucceeded(Author remoteAuthor) {
|
||||
String contactName = remoteAuthor.getName();
|
||||
String text = getString(R.string.contact_added_toast, contactName);
|
||||
Toast.makeText(this, text, LENGTH_LONG).show();
|
||||
supportFinishAfterTransition();
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void duplicateContact(Author remoteAuthor) {
|
||||
String contactName = remoteAuthor.getName();
|
||||
String format = getString(R.string.contact_already_exists);
|
||||
String text = String.format(format, contactName);
|
||||
Toast.makeText(this, text, LENGTH_LONG).show();
|
||||
finish();
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void contactExchangeFailed() {
|
||||
showErrorFragment();
|
||||
}
|
||||
|
||||
@UiThread
|
||||
@Override
|
||||
public void keyAgreementFailed() {
|
||||
showErrorFragment();
|
||||
}
|
||||
|
||||
@UiThread
|
||||
@Override
|
||||
public String keyAgreementWaiting() {
|
||||
return getString(R.string.waiting_for_contact_to_scan);
|
||||
}
|
||||
|
||||
@UiThread
|
||||
@Override
|
||||
public String keyAgreementStarted() {
|
||||
return getString(R.string.authenticating_with_device);
|
||||
}
|
||||
|
||||
@UiThread
|
||||
@Override
|
||||
public void keyAgreementAborted(boolean remoteAborted) {
|
||||
showErrorFragment();
|
||||
}
|
||||
|
||||
@UiThread
|
||||
@Override
|
||||
public String keyAgreementFinished(KeyAgreementResult result) {
|
||||
startContactExchange(result);
|
||||
return getString(R.string.exchanging_contact_details);
|
||||
}
|
||||
|
||||
private void showErrorFragment() {
|
||||
showNextFragment(new ContactExchangeErrorFragment());
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
package org.briarproject.briar.android.keyagreement;
|
||||
|
||||
import android.app.Application;
|
||||
|
||||
import org.briarproject.bramble.api.connection.ConnectionManager;
|
||||
import org.briarproject.bramble.api.contact.Contact;
|
||||
import org.briarproject.bramble.api.contact.ContactExchangeManager;
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.db.ContactExistsException;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
import org.briarproject.bramble.api.identity.Author;
|
||||
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import androidx.annotation.UiThread;
|
||||
import androidx.lifecycle.AndroidViewModel;
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
|
||||
import static java.util.logging.Level.WARNING;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||
|
||||
@NotNullByDefault
|
||||
class ContactExchangeViewModel extends AndroidViewModel {
|
||||
|
||||
private static final Logger LOG =
|
||||
getLogger(ContactExchangeViewModel.class.getName());
|
||||
|
||||
private final Executor ioExecutor;
|
||||
private final ContactExchangeManager contactExchangeManager;
|
||||
private final ConnectionManager connectionManager;
|
||||
private final MutableLiveData<Boolean> succeeded = new MutableLiveData<>();
|
||||
|
||||
@Nullable
|
||||
private volatile Author remoteAuthor, duplicateAuthor;
|
||||
|
||||
@Inject
|
||||
ContactExchangeViewModel(Application app, @IoExecutor Executor ioExecutor,
|
||||
ContactExchangeManager contactExchangeManager,
|
||||
ConnectionManager connectionManager) {
|
||||
super(app);
|
||||
this.ioExecutor = ioExecutor;
|
||||
this.contactExchangeManager = contactExchangeManager;
|
||||
this.connectionManager = connectionManager;
|
||||
}
|
||||
|
||||
@UiThread
|
||||
void startContactExchange(TransportId t, DuplexTransportConnection conn,
|
||||
SecretKey masterKey, boolean alice) {
|
||||
ioExecutor.execute(() -> {
|
||||
try {
|
||||
Contact contact = contactExchangeManager.exchangeContacts(conn,
|
||||
masterKey, alice, true);
|
||||
// Reuse the connection as a transport connection
|
||||
connectionManager.manageOutgoingConnection(contact.getId(),
|
||||
t, conn);
|
||||
remoteAuthor = contact.getAuthor();
|
||||
succeeded.postValue(true);
|
||||
} catch (ContactExistsException e) {
|
||||
tryToClose(conn);
|
||||
duplicateAuthor = e.getRemoteAuthor();
|
||||
succeeded.postValue(false);
|
||||
} catch (DbException | IOException e) {
|
||||
tryToClose(conn);
|
||||
logException(LOG, WARNING, e);
|
||||
succeeded.postValue(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void tryToClose(DuplexTransportConnection conn) {
|
||||
try {
|
||||
conn.getReader().dispose(true, true);
|
||||
conn.getWriter().dispose(true);
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
}
|
||||
}
|
||||
|
||||
@UiThread
|
||||
@Nullable
|
||||
Author getRemoteAuthor() {
|
||||
return remoteAuthor;
|
||||
}
|
||||
|
||||
@UiThread
|
||||
@Nullable
|
||||
Author getDuplicateAuthor() {
|
||||
return duplicateAuthor;
|
||||
}
|
||||
|
||||
LiveData<Boolean> getSucceeded() {
|
||||
return succeeded;
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
package org.briarproject.briar.android.keyagreement;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Bundle;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.ScrollView;
|
||||
|
||||
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.annotation.Nullable;
|
||||
|
||||
import static android.view.View.FOCUS_DOWN;
|
||||
|
||||
@MethodsNotNullByDefault
|
||||
@ParametersNotNullByDefault
|
||||
public class IntroFragment extends BaseFragment {
|
||||
|
||||
interface IntroScreenSeenListener {
|
||||
void showNextScreen();
|
||||
}
|
||||
|
||||
public static final String TAG = IntroFragment.class.getName();
|
||||
|
||||
private IntroScreenSeenListener screenSeenListener;
|
||||
private ScrollView scrollView;
|
||||
|
||||
public static IntroFragment newInstance() {
|
||||
|
||||
Bundle args = new Bundle();
|
||||
|
||||
IntroFragment fragment = new IntroFragment();
|
||||
fragment.setArguments(args);
|
||||
return fragment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAttach(Context context) {
|
||||
super.onAttach(context);
|
||||
screenSeenListener = (IntroScreenSeenListener) context;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUniqueTag() {
|
||||
return TAG;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(LayoutInflater inflater,
|
||||
@Nullable ViewGroup container,
|
||||
@Nullable Bundle savedInstanceState) {
|
||||
|
||||
View v = inflater.inflate(R.layout.fragment_keyagreement_id, container,
|
||||
false);
|
||||
scrollView = v.findViewById(R.id.scrollView);
|
||||
View button = v.findViewById(R.id.continueButton);
|
||||
button.setOnClickListener(view -> screenSeenListener.showNextScreen());
|
||||
return v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStart() {
|
||||
super.onStart();
|
||||
scrollView.post(() -> scrollView.fullScroll(FOCUS_DOWN));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,484 +0,0 @@
|
||||
package org.briarproject.briar.android.keyagreement;
|
||||
|
||||
import android.bluetooth.BluetoothAdapter;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.os.Bundle;
|
||||
import android.view.MenuItem;
|
||||
|
||||
import org.briarproject.bramble.api.event.Event;
|
||||
import org.briarproject.bramble.api.event.EventBus;
|
||||
import org.briarproject.bramble.api.event.EventListener;
|
||||
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
|
||||
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.BluetoothConstants;
|
||||
import org.briarproject.bramble.api.plugin.LanTcpConstants;
|
||||
import org.briarproject.bramble.api.plugin.Plugin;
|
||||
import org.briarproject.bramble.api.plugin.Plugin.State;
|
||||
import org.briarproject.bramble.api.plugin.PluginManager;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportStateEvent;
|
||||
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.android.fragment.BaseFragment.BaseFragmentListener;
|
||||
import org.briarproject.briar.android.keyagreement.IntroFragment.IntroScreenSeenListener;
|
||||
import org.briarproject.briar.android.keyagreement.KeyAgreementFragment.KeyAgreementEventListener;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import androidx.annotation.StringRes;
|
||||
import androidx.annotation.UiThread;
|
||||
import androidx.appcompat.app.AlertDialog.Builder;
|
||||
import androidx.appcompat.widget.Toolbar;
|
||||
import androidx.core.app.ActivityCompat;
|
||||
import androidx.fragment.app.FragmentManager;
|
||||
|
||||
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
|
||||
import static android.Manifest.permission.CAMERA;
|
||||
import static android.bluetooth.BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE;
|
||||
import static android.bluetooth.BluetoothAdapter.ACTION_SCAN_MODE_CHANGED;
|
||||
import static android.bluetooth.BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE;
|
||||
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
|
||||
import static android.os.Build.VERSION.SDK_INT;
|
||||
import static java.util.logging.Level.INFO;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
import static org.briarproject.bramble.api.nullsafety.NullSafety.requireNonNull;
|
||||
import static org.briarproject.bramble.api.plugin.Plugin.State.ACTIVE;
|
||||
import static org.briarproject.bramble.api.plugin.Plugin.State.DISABLED;
|
||||
import static org.briarproject.bramble.api.plugin.Plugin.State.INACTIVE;
|
||||
import static org.briarproject.bramble.api.plugin.Plugin.State.STARTING_STOPPING;
|
||||
import static org.briarproject.briar.android.activity.RequestCodes.REQUEST_BLUETOOTH_DISCOVERABLE;
|
||||
import static org.briarproject.briar.android.activity.RequestCodes.REQUEST_PERMISSION_CAMERA_LOCATION;
|
||||
import static org.briarproject.briar.android.util.UiUtils.getGoToSettingsListener;
|
||||
|
||||
@MethodsNotNullByDefault
|
||||
@ParametersNotNullByDefault
|
||||
public abstract class KeyAgreementActivity extends BriarActivity implements
|
||||
BaseFragmentListener, IntroScreenSeenListener,
|
||||
KeyAgreementEventListener, EventListener {
|
||||
|
||||
private enum BluetoothDecision {
|
||||
/**
|
||||
* We haven't asked the user about Bluetooth discoverability.
|
||||
*/
|
||||
UNKNOWN,
|
||||
|
||||
/**
|
||||
* The device doesn't have a Bluetooth adapter.
|
||||
*/
|
||||
NO_ADAPTER,
|
||||
|
||||
/**
|
||||
* We're waiting for the user to accept or refuse discoverability.
|
||||
*/
|
||||
WAITING,
|
||||
|
||||
/**
|
||||
* The user has accepted discoverability.
|
||||
*/
|
||||
ACCEPTED,
|
||||
|
||||
/**
|
||||
* The user has refused discoverability.
|
||||
*/
|
||||
REFUSED
|
||||
}
|
||||
|
||||
private enum Permission {
|
||||
UNKNOWN, GRANTED, SHOW_RATIONALE, PERMANENTLY_DENIED
|
||||
}
|
||||
|
||||
private static final Logger LOG =
|
||||
getLogger(KeyAgreementActivity.class.getName());
|
||||
|
||||
@Inject
|
||||
EventBus eventBus;
|
||||
|
||||
@Inject
|
||||
PluginManager pluginManager;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
private boolean isResumed = false;
|
||||
|
||||
/**
|
||||
* Set to true when the continue button is clicked, and false when the QR
|
||||
* code fragment is shown. This prevents the QR code fragment from being
|
||||
* shown automatically before the continue button has been clicked.
|
||||
*/
|
||||
private boolean continueClicked = false;
|
||||
|
||||
/**
|
||||
* Records whether we've enabled the wifi plugin so we don't enable it more
|
||||
* than once.
|
||||
*/
|
||||
private boolean hasEnabledWifi = false;
|
||||
|
||||
/**
|
||||
* Records whether we've enabled the Bluetooth plugin so we don't enable it
|
||||
* more than once.
|
||||
*/
|
||||
private boolean hasEnabledBluetooth = false;
|
||||
|
||||
private Permission cameraPermission = Permission.UNKNOWN;
|
||||
private Permission locationPermission = Permission.UNKNOWN;
|
||||
private BluetoothDecision bluetoothDecision = BluetoothDecision.UNKNOWN;
|
||||
private BroadcastReceiver bluetoothReceiver = null;
|
||||
private Plugin wifiPlugin = null, bluetoothPlugin = null;
|
||||
private BluetoothAdapter bt = null;
|
||||
|
||||
@Override
|
||||
public void injectActivity(ActivityComponent component) {
|
||||
component.inject(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate(@Nullable Bundle state) {
|
||||
super.onCreate(state);
|
||||
setContentView(R.layout.activity_fragment_container_toolbar);
|
||||
Toolbar toolbar = findViewById(R.id.toolbar);
|
||||
setSupportActionBar(toolbar);
|
||||
requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
|
||||
if (state == null) {
|
||||
showInitialFragment(IntroFragment.newInstance());
|
||||
}
|
||||
IntentFilter filter = new IntentFilter(ACTION_SCAN_MODE_CHANGED);
|
||||
bluetoothReceiver = new BluetoothStateReceiver();
|
||||
registerReceiver(bluetoothReceiver, filter);
|
||||
wifiPlugin = pluginManager.getPlugin(LanTcpConstants.ID);
|
||||
bluetoothPlugin = pluginManager.getPlugin(BluetoothConstants.ID);
|
||||
bt = BluetoothAdapter.getDefaultAdapter();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
super.onDestroy();
|
||||
if (bluetoothReceiver != null) unregisterReceiver(bluetoothReceiver);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(MenuItem item) {
|
||||
if (item.getItemId() == android.R.id.home) {
|
||||
onBackPressed();
|
||||
return true;
|
||||
}
|
||||
return super.onOptionsItemSelected(item);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStart() {
|
||||
super.onStart();
|
||||
eventBus.addListener(this);
|
||||
// Permissions may have been granted manually while we were stopped
|
||||
cameraPermission = Permission.UNKNOWN;
|
||||
locationPermission = Permission.UNKNOWN;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPostResume() {
|
||||
super.onPostResume();
|
||||
isResumed = true;
|
||||
// Workaround for
|
||||
// https://code.google.com/p/android/issues/detail?id=190966
|
||||
showQrCodeFragmentIfAllowed();
|
||||
}
|
||||
|
||||
@SuppressWarnings("StatementWithEmptyBody")
|
||||
private void showQrCodeFragmentIfAllowed() {
|
||||
if (isResumed && continueClicked && areEssentialPermissionsGranted()) {
|
||||
if (isWifiReady() && isBluetoothReady()) {
|
||||
LOG.info("Wifi and Bluetooth are ready");
|
||||
showQrCodeFragment();
|
||||
} else {
|
||||
if (shouldEnableWifi()) {
|
||||
LOG.info("Enabling wifi plugin");
|
||||
hasEnabledWifi = true;
|
||||
pluginManager.setPluginEnabled(LanTcpConstants.ID, true);
|
||||
}
|
||||
if (bluetoothDecision == BluetoothDecision.UNKNOWN) {
|
||||
requestBluetoothDiscoverable();
|
||||
} else if (bluetoothDecision == BluetoothDecision.REFUSED) {
|
||||
// Ask again when the user clicks "continue"
|
||||
} else if (shouldEnableBluetooth()) {
|
||||
LOG.info("Enabling Bluetooth plugin");
|
||||
hasEnabledBluetooth = true;
|
||||
pluginManager.setPluginEnabled(BluetoothConstants.ID, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean areEssentialPermissionsGranted() {
|
||||
return cameraPermission == Permission.GRANTED &&
|
||||
(SDK_INT < 23 || locationPermission == Permission.GRANTED ||
|
||||
!isBluetoothSupported());
|
||||
}
|
||||
|
||||
private boolean isBluetoothSupported() {
|
||||
return bt != null && bluetoothPlugin != null;
|
||||
}
|
||||
|
||||
private boolean isWifiReady() {
|
||||
if (wifiPlugin == null) return true; // Continue without wifi
|
||||
State state = wifiPlugin.getState();
|
||||
// Wait for plugin to become enabled
|
||||
return state == ACTIVE || state == INACTIVE;
|
||||
}
|
||||
|
||||
private boolean isBluetoothReady() {
|
||||
if (!isBluetoothSupported()) {
|
||||
// Continue without Bluetooth
|
||||
return true;
|
||||
}
|
||||
if (bluetoothDecision == BluetoothDecision.UNKNOWN ||
|
||||
bluetoothDecision == BluetoothDecision.WAITING ||
|
||||
bluetoothDecision == BluetoothDecision.REFUSED) {
|
||||
// Wait for user to accept
|
||||
return false;
|
||||
}
|
||||
if (bt.getScanMode() != SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
|
||||
// Wait for adapter to become discoverable
|
||||
return false;
|
||||
}
|
||||
// Wait for plugin to become active
|
||||
return bluetoothPlugin.getState() == ACTIVE;
|
||||
}
|
||||
|
||||
private boolean shouldEnableWifi() {
|
||||
if (hasEnabledWifi) return false;
|
||||
if (wifiPlugin == null) return false;
|
||||
State state = wifiPlugin.getState();
|
||||
return state == STARTING_STOPPING || state == DISABLED;
|
||||
}
|
||||
|
||||
private void requestBluetoothDiscoverable() {
|
||||
if (!isBluetoothSupported()) {
|
||||
bluetoothDecision = BluetoothDecision.NO_ADAPTER;
|
||||
showQrCodeFragmentIfAllowed();
|
||||
} else {
|
||||
Intent i = new Intent(ACTION_REQUEST_DISCOVERABLE);
|
||||
if (i.resolveActivity(getPackageManager()) != null) {
|
||||
LOG.info("Asking for Bluetooth discoverability");
|
||||
bluetoothDecision = BluetoothDecision.WAITING;
|
||||
startActivityForResult(i, REQUEST_BLUETOOTH_DISCOVERABLE);
|
||||
} else {
|
||||
bluetoothDecision = BluetoothDecision.NO_ADAPTER;
|
||||
showQrCodeFragmentIfAllowed();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean shouldEnableBluetooth() {
|
||||
if (bluetoothDecision != BluetoothDecision.ACCEPTED) return false;
|
||||
if (hasEnabledBluetooth) return false;
|
||||
if (!isBluetoothSupported()) return false;
|
||||
State state = bluetoothPlugin.getState();
|
||||
return state == STARTING_STOPPING || state == DISABLED;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPause() {
|
||||
super.onPause();
|
||||
isResumed = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStop() {
|
||||
super.onStop();
|
||||
eventBus.removeListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void showNextScreen() {
|
||||
continueClicked = true;
|
||||
if (bluetoothDecision == BluetoothDecision.REFUSED) {
|
||||
bluetoothDecision = BluetoothDecision.UNKNOWN; // Ask again
|
||||
}
|
||||
if (checkPermissions()) showQrCodeFragmentIfAllowed();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onActivityResult(int request, int result,
|
||||
@Nullable Intent data) {
|
||||
if (request == REQUEST_BLUETOOTH_DISCOVERABLE) {
|
||||
if (result == RESULT_CANCELED) {
|
||||
LOG.info("Bluetooth discoverability was refused");
|
||||
bluetoothDecision = BluetoothDecision.REFUSED;
|
||||
} else {
|
||||
LOG.info("Bluetooth discoverability was accepted");
|
||||
bluetoothDecision = BluetoothDecision.ACCEPTED;
|
||||
}
|
||||
showQrCodeFragmentIfAllowed();
|
||||
} else super.onActivityResult(request, result, data);
|
||||
}
|
||||
|
||||
private void showQrCodeFragment() {
|
||||
// If we return to the intro fragment, the continue button needs to be
|
||||
// clicked again before showing the QR code fragment
|
||||
continueClicked = false;
|
||||
// If we return to the intro fragment, ask for Bluetooth
|
||||
// discoverability again before showing the QR code fragment
|
||||
bluetoothDecision = BluetoothDecision.UNKNOWN;
|
||||
// If we return to the intro fragment, we may need to enable wifi and
|
||||
// Bluetooth again
|
||||
hasEnabledWifi = false;
|
||||
hasEnabledBluetooth = false;
|
||||
|
||||
// FIXME #824
|
||||
FragmentManager fm = getSupportFragmentManager();
|
||||
if (fm.findFragmentByTag(KeyAgreementFragment.TAG) == null) {
|
||||
BaseFragment f = KeyAgreementFragment.newInstance();
|
||||
fm.beginTransaction()
|
||||
.replace(R.id.fragmentContainer, f, f.getUniqueTag())
|
||||
.addToBackStack(f.getUniqueTag())
|
||||
.commit();
|
||||
}
|
||||
}
|
||||
|
||||
private boolean checkPermissions() {
|
||||
if (areEssentialPermissionsGranted()) return true;
|
||||
// If an essential permission has been permanently denied, ask the
|
||||
// user to change the setting
|
||||
if (cameraPermission == Permission.PERMANENTLY_DENIED) {
|
||||
showDenialDialog(R.string.permission_camera_title,
|
||||
R.string.permission_camera_denied_body);
|
||||
return false;
|
||||
}
|
||||
if (isBluetoothSupported() &&
|
||||
locationPermission == Permission.PERMANENTLY_DENIED) {
|
||||
showDenialDialog(R.string.permission_location_title,
|
||||
R.string.permission_location_denied_body);
|
||||
return false;
|
||||
}
|
||||
// Should we show the rationale for one or both permissions?
|
||||
if (cameraPermission == Permission.SHOW_RATIONALE &&
|
||||
locationPermission == Permission.SHOW_RATIONALE) {
|
||||
showRationale(R.string.permission_camera_location_title,
|
||||
R.string.permission_camera_location_request_body);
|
||||
} else if (cameraPermission == Permission.SHOW_RATIONALE) {
|
||||
showRationale(R.string.permission_camera_title,
|
||||
R.string.permission_camera_request_body);
|
||||
} else if (locationPermission == Permission.SHOW_RATIONALE) {
|
||||
showRationale(R.string.permission_location_title,
|
||||
R.string.permission_location_request_body);
|
||||
} else {
|
||||
requestPermissions();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void showDenialDialog(@StringRes int title, @StringRes int body) {
|
||||
Builder builder = new Builder(this, R.style.BriarDialogTheme);
|
||||
builder.setTitle(title);
|
||||
builder.setMessage(body);
|
||||
builder.setPositiveButton(R.string.ok, getGoToSettingsListener(this));
|
||||
builder.setNegativeButton(R.string.cancel,
|
||||
(dialog, which) -> supportFinishAfterTransition());
|
||||
builder.show();
|
||||
}
|
||||
|
||||
private void showRationale(@StringRes int title, @StringRes int body) {
|
||||
Builder builder = new Builder(this, R.style.BriarDialogTheme);
|
||||
builder.setTitle(title);
|
||||
builder.setMessage(body);
|
||||
builder.setNeutralButton(R.string.continue_button,
|
||||
(dialog, which) -> requestPermissions());
|
||||
builder.show();
|
||||
}
|
||||
|
||||
private void requestPermissions() {
|
||||
String[] permissions;
|
||||
if (isBluetoothSupported()) {
|
||||
permissions = new String[] {CAMERA, ACCESS_FINE_LOCATION};
|
||||
} else {
|
||||
permissions = new String[] {CAMERA};
|
||||
}
|
||||
ActivityCompat.requestPermissions(this, permissions,
|
||||
REQUEST_PERMISSION_CAMERA_LOCATION);
|
||||
}
|
||||
|
||||
@Override
|
||||
@UiThread
|
||||
public void onRequestPermissionsResult(int requestCode,
|
||||
String[] permissions, int[] grantResults) {
|
||||
super.onRequestPermissionsResult(requestCode, permissions,
|
||||
grantResults);
|
||||
if (requestCode != REQUEST_PERMISSION_CAMERA_LOCATION)
|
||||
throw new AssertionError();
|
||||
if (gotPermission(CAMERA, permissions, grantResults)) {
|
||||
cameraPermission = Permission.GRANTED;
|
||||
} else if (shouldShowRationale(CAMERA)) {
|
||||
cameraPermission = Permission.SHOW_RATIONALE;
|
||||
} else {
|
||||
cameraPermission = Permission.PERMANENTLY_DENIED;
|
||||
}
|
||||
if (isBluetoothSupported()) {
|
||||
if (gotPermission(ACCESS_FINE_LOCATION, permissions,
|
||||
grantResults)) {
|
||||
locationPermission = Permission.GRANTED;
|
||||
} else if (shouldShowRationale(ACCESS_FINE_LOCATION)) {
|
||||
locationPermission = Permission.SHOW_RATIONALE;
|
||||
} else {
|
||||
locationPermission = Permission.PERMANENTLY_DENIED;
|
||||
}
|
||||
}
|
||||
// If a permission dialog has been shown, showing the QR code fragment
|
||||
// on this call path would cause a crash due to
|
||||
// https://code.google.com/p/android/issues/detail?id=190966.
|
||||
// In that case the isResumed flag prevents the fragment from being
|
||||
// shown here, and showQrCodeFragmentIfAllowed() will be called again
|
||||
// from onPostResume().
|
||||
if (checkPermissions()) showQrCodeFragmentIfAllowed();
|
||||
}
|
||||
|
||||
private boolean gotPermission(String permission, String[] permissions,
|
||||
int[] grantResults) {
|
||||
for (int i = 0; i < permissions.length; i++) {
|
||||
if (permission.equals(permissions[i]))
|
||||
return grantResults[i] == PERMISSION_GRANTED;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean shouldShowRationale(String permission) {
|
||||
return ActivityCompat.shouldShowRequestPermissionRationale(this,
|
||||
permission);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void eventOccurred(Event e) {
|
||||
if (e instanceof TransportStateEvent) {
|
||||
TransportStateEvent t = (TransportStateEvent) e;
|
||||
if (t.getTransportId().equals(BluetoothConstants.ID)) {
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info("Bluetooth state changed to " + t.getState());
|
||||
}
|
||||
showQrCodeFragmentIfAllowed();
|
||||
} else if (t.getTransportId().equals(LanTcpConstants.ID)) {
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info("Wifi state changed to " + t.getState());
|
||||
}
|
||||
showQrCodeFragmentIfAllowed();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class BluetoothStateReceiver extends BroadcastReceiver {
|
||||
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
LOG.info("Bluetooth scan mode changed");
|
||||
showQrCodeFragmentIfAllowed();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,375 +0,0 @@
|
||||
package org.briarproject.briar.android.keyagreement;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Bitmap;
|
||||
import android.os.Bundle;
|
||||
import android.util.DisplayMetrics;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.LinearLayout.LayoutParams;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import com.google.zxing.Result;
|
||||
|
||||
import org.briarproject.bramble.api.UnsupportedVersionException;
|
||||
import org.briarproject.bramble.api.event.Event;
|
||||
import org.briarproject.bramble.api.event.EventBus;
|
||||
import org.briarproject.bramble.api.keyagreement.KeyAgreementResult;
|
||||
import org.briarproject.bramble.api.keyagreement.KeyAgreementTask;
|
||||
import org.briarproject.bramble.api.keyagreement.Payload;
|
||||
import org.briarproject.bramble.api.keyagreement.PayloadEncoder;
|
||||
import org.briarproject.bramble.api.keyagreement.PayloadParser;
|
||||
import org.briarproject.bramble.api.keyagreement.event.KeyAgreementAbortedEvent;
|
||||
import org.briarproject.bramble.api.keyagreement.event.KeyAgreementFailedEvent;
|
||||
import org.briarproject.bramble.api.keyagreement.event.KeyAgreementFinishedEvent;
|
||||
import org.briarproject.bramble.api.keyagreement.event.KeyAgreementListeningEvent;
|
||||
import org.briarproject.bramble.api.keyagreement.event.KeyAgreementStartedEvent;
|
||||
import org.briarproject.bramble.api.keyagreement.event.KeyAgreementWaitingEvent;
|
||||
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
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.BaseEventFragment;
|
||||
import org.briarproject.briar.android.view.QrCodeView;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Provider;
|
||||
|
||||
import androidx.annotation.UiThread;
|
||||
|
||||
import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
|
||||
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.INFO;
|
||||
import static java.util.logging.Level.WARNING;
|
||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||
|
||||
@MethodsNotNullByDefault
|
||||
@ParametersNotNullByDefault
|
||||
public class KeyAgreementFragment extends BaseEventFragment
|
||||
implements QrCodeDecoder.ResultCallback, QrCodeView.FullscreenListener {
|
||||
|
||||
static final String TAG = KeyAgreementFragment.class.getName();
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(TAG);
|
||||
@SuppressWarnings("CharsetObjectCanBeUsed") // Requires minSdkVersion >= 19
|
||||
private static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
|
||||
|
||||
@Inject
|
||||
Provider<KeyAgreementTask> keyAgreementTaskProvider;
|
||||
@Inject
|
||||
PayloadEncoder payloadEncoder;
|
||||
@Inject
|
||||
PayloadParser payloadParser;
|
||||
@Inject
|
||||
@IoExecutor
|
||||
Executor ioExecutor;
|
||||
@Inject
|
||||
EventBus eventBus;
|
||||
|
||||
private CameraView cameraView;
|
||||
private LinearLayout cameraOverlay;
|
||||
private View statusView;
|
||||
private QrCodeView qrCodeView;
|
||||
private TextView status;
|
||||
|
||||
private boolean gotRemotePayload;
|
||||
private volatile boolean gotLocalPayload;
|
||||
private KeyAgreementTask task;
|
||||
private KeyAgreementEventListener listener;
|
||||
|
||||
public static KeyAgreementFragment newInstance() {
|
||||
Bundle args = new Bundle();
|
||||
KeyAgreementFragment fragment = new KeyAgreementFragment();
|
||||
fragment.setArguments(args);
|
||||
return fragment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAttach(Context context) {
|
||||
super.onAttach(context);
|
||||
listener = (KeyAgreementEventListener) context;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void injectFragment(ActivityComponent component) {
|
||||
component.inject(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUniqueTag() {
|
||||
return TAG;
|
||||
}
|
||||
|
||||
@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);
|
||||
qrCodeView = view.findViewById(R.id.qr_code_view);
|
||||
qrCodeView.setFullscreenListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
|
||||
super.onActivityCreated(savedInstanceState);
|
||||
requireActivity().setRequestedOrientation(SCREEN_ORIENTATION_NOSENSOR);
|
||||
cameraView.setPreviewConsumer(new QrCodeDecoder(this));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStart() {
|
||||
super.onStart();
|
||||
try {
|
||||
cameraView.start();
|
||||
} catch (CameraException e) {
|
||||
logCameraExceptionAndFinish(e);
|
||||
}
|
||||
startListening();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setFullscreen(boolean fullscreen) {
|
||||
LinearLayout.LayoutParams statusParams, qrCodeParams;
|
||||
if (fullscreen) {
|
||||
// Grow the QR code view to fill its parent
|
||||
statusParams = new LayoutParams(0, 0, 0f);
|
||||
qrCodeParams = new LayoutParams(MATCH_PARENT, MATCH_PARENT, 1f);
|
||||
} else {
|
||||
// Shrink the QR code view to fill half its parent
|
||||
if (cameraOverlay.getOrientation() == HORIZONTAL) {
|
||||
statusParams = new LayoutParams(0, MATCH_PARENT, 1f);
|
||||
qrCodeParams = new LayoutParams(0, MATCH_PARENT, 1f);
|
||||
} else {
|
||||
statusParams = new LayoutParams(MATCH_PARENT, 0, 1f);
|
||||
qrCodeParams = new LayoutParams(MATCH_PARENT, 0, 1f);
|
||||
}
|
||||
}
|
||||
statusView.setLayoutParams(statusParams);
|
||||
qrCodeView.setLayoutParams(qrCodeParams);
|
||||
cameraOverlay.invalidate();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStop() {
|
||||
super.onStop();
|
||||
stopListening();
|
||||
try {
|
||||
cameraView.stop();
|
||||
} catch (CameraException e) {
|
||||
logCameraExceptionAndFinish(e);
|
||||
}
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void logCameraExceptionAndFinish(CameraException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
Toast.makeText(getActivity(), R.string.camera_error,
|
||||
LENGTH_LONG).show();
|
||||
finish();
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void startListening() {
|
||||
KeyAgreementTask oldTask = task;
|
||||
KeyAgreementTask newTask = keyAgreementTaskProvider.get();
|
||||
task = newTask;
|
||||
ioExecutor.execute(() -> {
|
||||
if (oldTask != null) oldTask.stopListening();
|
||||
newTask.listen();
|
||||
});
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void stopListening() {
|
||||
KeyAgreementTask oldTask = task;
|
||||
ioExecutor.execute(() -> {
|
||||
if (oldTask != null) oldTask.stopListening();
|
||||
});
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void reset() {
|
||||
// If we've stopped the camera view, restart it
|
||||
if (gotRemotePayload) {
|
||||
try {
|
||||
cameraView.start();
|
||||
} catch (CameraException e) {
|
||||
logCameraExceptionAndFinish(e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
statusView.setVisibility(INVISIBLE);
|
||||
cameraView.setVisibility(VISIBLE);
|
||||
gotRemotePayload = false;
|
||||
gotLocalPayload = false;
|
||||
startListening();
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void qrCodeScanned(String content) {
|
||||
try {
|
||||
byte[] payloadBytes = content.getBytes(ISO_8859_1);
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Remote payload is " + payloadBytes.length + " bytes");
|
||||
Payload remotePayload = payloadParser.parse(payloadBytes);
|
||||
gotRemotePayload = true;
|
||||
cameraView.stop();
|
||||
cameraView.setVisibility(INVISIBLE);
|
||||
statusView.setVisibility(VISIBLE);
|
||||
status.setText(R.string.connecting_to_device);
|
||||
task.connectAndRunProtocol(remotePayload);
|
||||
} catch (UnsupportedVersionException e) {
|
||||
reset();
|
||||
String msg;
|
||||
if (e.isTooOld()) {
|
||||
msg = getString(R.string.qr_code_too_old,
|
||||
getString(R.string.app_name));
|
||||
} else {
|
||||
msg = getString(R.string.qr_code_too_new,
|
||||
getString(R.string.app_name));
|
||||
}
|
||||
showNextFragment(ContactExchangeErrorFragment.newInstance(msg));
|
||||
} catch (CameraException e) {
|
||||
logCameraExceptionAndFinish(e);
|
||||
} catch (IOException | IllegalArgumentException e) {
|
||||
LOG.log(WARNING, "QR Code Invalid", e);
|
||||
reset();
|
||||
Toast.makeText(getActivity(), R.string.qr_code_invalid,
|
||||
LENGTH_LONG).show();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void eventOccurred(Event e) {
|
||||
if (e instanceof KeyAgreementListeningEvent) {
|
||||
KeyAgreementListeningEvent event = (KeyAgreementListeningEvent) e;
|
||||
gotLocalPayload = true;
|
||||
setQrCode(event.getLocalPayload());
|
||||
} else if (e instanceof KeyAgreementFailedEvent) {
|
||||
keyAgreementFailed();
|
||||
} else if (e instanceof KeyAgreementWaitingEvent) {
|
||||
keyAgreementWaiting();
|
||||
} else if (e instanceof KeyAgreementStartedEvent) {
|
||||
keyAgreementStarted();
|
||||
} else if (e instanceof KeyAgreementAbortedEvent) {
|
||||
KeyAgreementAbortedEvent event = (KeyAgreementAbortedEvent) e;
|
||||
keyAgreementAborted(event.didRemoteAbort());
|
||||
} else if (e instanceof KeyAgreementFinishedEvent) {
|
||||
keyAgreementFinished(((KeyAgreementFinishedEvent) e).getResult());
|
||||
}
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void keyAgreementFailed() {
|
||||
reset();
|
||||
listener.keyAgreementFailed();
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void keyAgreementWaiting() {
|
||||
status.setText(listener.keyAgreementWaiting());
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void keyAgreementStarted() {
|
||||
qrCodeView.setVisibility(INVISIBLE);
|
||||
statusView.setVisibility(VISIBLE);
|
||||
status.setText(listener.keyAgreementStarted());
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void keyAgreementAborted(boolean remoteAborted) {
|
||||
reset();
|
||||
listener.keyAgreementAborted(remoteAborted);
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void keyAgreementFinished(KeyAgreementResult result) {
|
||||
statusView.setVisibility(VISIBLE);
|
||||
status.setText(listener.keyAgreementFinished(result));
|
||||
}
|
||||
|
||||
private void setQrCode(Payload localPayload) {
|
||||
Context context = getContext();
|
||||
if (context == null) return;
|
||||
DisplayMetrics dm = context.getResources().getDisplayMetrics();
|
||||
ioExecutor.execute(() -> {
|
||||
byte[] payloadBytes = payloadEncoder.encode(localPayload);
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info("Local payload is " + payloadBytes.length
|
||||
+ " bytes");
|
||||
}
|
||||
// Use ISO 8859-1 to encode bytes directly as a string
|
||||
String content = new String(payloadBytes, ISO_8859_1);
|
||||
Bitmap qrCode = QrCodeUtils.createQrCode(dm, content);
|
||||
runOnUiThreadUnlessDestroyed(() -> qrCodeView.setQrCode(qrCode));
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleResult(Result result) {
|
||||
runOnUiThreadUnlessDestroyed(() -> {
|
||||
LOG.info("Got result from decoder");
|
||||
// Ignore results until the KeyAgreementTask is ready
|
||||
if (!gotLocalPayload) return;
|
||||
if (!gotRemotePayload) qrCodeScanned(result.getText());
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void finish() {
|
||||
getActivity().getSupportFragmentManager().popBackStack();
|
||||
}
|
||||
|
||||
@NotNullByDefault
|
||||
interface KeyAgreementEventListener {
|
||||
|
||||
@UiThread
|
||||
void keyAgreementFailed();
|
||||
|
||||
// Should return a string to be displayed as status.
|
||||
@UiThread
|
||||
@Nullable
|
||||
String keyAgreementWaiting();
|
||||
|
||||
// Should return a string to be displayed as status.
|
||||
@UiThread
|
||||
@Nullable
|
||||
String keyAgreementStarted();
|
||||
|
||||
// Will show an error fragment.
|
||||
@UiThread
|
||||
void keyAgreementAborted(boolean remoteAborted);
|
||||
|
||||
// Should return a string to be displayed as status.
|
||||
@UiThread
|
||||
@Nullable
|
||||
String keyAgreementFinished(KeyAgreementResult result);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package org.briarproject.briar.android.socialbackup;
|
||||
|
||||
import androidx.annotation.UiThread;
|
||||
|
||||
public interface ExplainerDismissedListener {
|
||||
@UiThread
|
||||
void explainerDismissed();
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package org.briarproject.briar.android.socialbackup;
|
||||
|
||||
import androidx.annotation.UiThread;
|
||||
|
||||
public interface ScanQrButtonListener {
|
||||
@UiThread
|
||||
void scanQrButtonClicked();
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user