mirror of
https://code.briarproject.org/briar/briar.git
synced 2026-02-12 02:39:05 +01:00
Compare commits
2 Commits
remove-off
...
export-acc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4dbdd724ad | ||
|
|
0122282a72 |
5
.idea/codeStyles/Project.xml
generated
5
.idea/codeStyles/Project.xml
generated
@@ -28,11 +28,6 @@
|
||||
<option name="JD_ALIGN_EXCEPTION_COMMENTS" value="false" />
|
||||
</JavaCodeStyleSettings>
|
||||
<JetCodeStyleSettings>
|
||||
<option name="PACKAGES_TO_USE_STAR_IMPORTS">
|
||||
<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" />
|
||||
</JetCodeStyleSettings>
|
||||
<XML>
|
||||
|
||||
1
bramble-android/.gitignore
vendored
1
bramble-android/.gitignore
vendored
@@ -3,4 +3,3 @@ gen
|
||||
build
|
||||
.settings
|
||||
src/main/res/raw/*.zip
|
||||
src/main/jniLibs
|
||||
@@ -5,14 +5,14 @@ apply plugin: 'witness'
|
||||
apply from: 'witness.gradle'
|
||||
|
||||
android {
|
||||
compileSdkVersion rootProject.ext.compileSdkVersion
|
||||
buildToolsVersion rootProject.ext.buildToolsVersion
|
||||
compileSdkVersion 29
|
||||
buildToolsVersion '29.0.2'
|
||||
|
||||
defaultConfig {
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
versionCode rootProject.ext.versionCode
|
||||
versionName rootProject.ext.versionName
|
||||
minSdkVersion 16
|
||||
targetSdkVersion 28
|
||||
versionCode 10209
|
||||
versionName "1.2.9"
|
||||
consumerProguardFiles 'proguard-rules.txt'
|
||||
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
@@ -53,12 +53,10 @@ dependencies {
|
||||
}
|
||||
|
||||
def torBinariesDir = 'src/main/res/raw'
|
||||
def torLibsDir = 'src/main/jniLibs'
|
||||
|
||||
task cleanTorBinaries {
|
||||
doLast {
|
||||
delete fileTree(torBinariesDir) { include '*.zip' }
|
||||
delete fileTree(torLibsDir) { include '**/*.so' }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,36 +67,8 @@ task unpackTorBinaries {
|
||||
copy {
|
||||
from configurations.tor.collect { zipTree(it) }
|
||||
into torBinariesDir
|
||||
include 'geoip.zip'
|
||||
}
|
||||
configurations.tor.each { outer ->
|
||||
zipTree(outer).each { inner ->
|
||||
if (inner.name.endsWith('_arm_pie.zip')) {
|
||||
copy {
|
||||
from zipTree(inner)
|
||||
into torLibsDir
|
||||
rename '(.*)', 'armeabi-v7a/lib$1.so'
|
||||
}
|
||||
} else if (inner.name.endsWith('_arm64_pie.zip')) {
|
||||
copy {
|
||||
from zipTree(inner)
|
||||
into torLibsDir
|
||||
rename '(.*)', 'arm64-v8a/lib$1.so'
|
||||
}
|
||||
} else if (inner.name.endsWith('_x86_pie.zip')) {
|
||||
copy {
|
||||
from zipTree(inner)
|
||||
into torLibsDir
|
||||
rename '(.*)', 'x86/lib$1.so'
|
||||
}
|
||||
} else if (inner.name.endsWith('_x86_64_pie.zip')) {
|
||||
copy {
|
||||
from zipTree(inner)
|
||||
into torLibsDir
|
||||
rename '(.*)', 'x86_64/lib$1.so'
|
||||
}
|
||||
}
|
||||
}
|
||||
// TODO: Remove after next Tor upgrade, which won't include non-PIE binaries
|
||||
include 'geoip.zip', '*_pie.zip'
|
||||
}
|
||||
}
|
||||
dependsOn cleanTorBinaries
|
||||
@@ -106,6 +76,5 @@ task unpackTorBinaries {
|
||||
|
||||
tasks.withType(MergeResources) {
|
||||
inputs.dir torBinariesDir
|
||||
inputs.dir torLibsDir
|
||||
dependsOn unpackTorBinaries
|
||||
}
|
||||
|
||||
@@ -71,6 +71,7 @@ class AndroidBluetoothPlugin
|
||||
private final Application app;
|
||||
private final Clock clock;
|
||||
|
||||
private volatile boolean wasEnabledByUs = false;
|
||||
private volatile BluetoothStateReceiver receiver = null;
|
||||
|
||||
// Non-null if the plugin started successfully
|
||||
@@ -132,10 +133,41 @@ class AndroidBluetoothPlugin
|
||||
return adapter != null && adapter.isEnabled();
|
||||
}
|
||||
|
||||
@Override
|
||||
void enableAdapter() {
|
||||
if (adapter != null && !adapter.isEnabled()) {
|
||||
if (adapter.enable()) {
|
||||
LOG.info("Enabling Bluetooth");
|
||||
wasEnabledByUs = true;
|
||||
} else {
|
||||
LOG.info("Could not enable Bluetooth");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
void disableAdapterIfEnabledByUs() {
|
||||
if (isAdapterEnabled() && wasEnabledByUs) {
|
||||
if (adapter.disable()) LOG.info("Disabling Bluetooth");
|
||||
else LOG.info("Could not disable Bluetooth");
|
||||
wasEnabledByUs = false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
void setEnabledByUs() {
|
||||
wasEnabledByUs = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
void onAdapterDisabled() {
|
||||
super.onAdapterDisabled();
|
||||
wasEnabledByUs = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
String getBluetoothAddress() {
|
||||
if (adapter == null) return null;
|
||||
String address = AndroidUtils.getBluetoothAddress(app, adapter);
|
||||
return address.isEmpty() ? null : address;
|
||||
}
|
||||
|
||||
@@ -16,42 +16,19 @@ import org.briarproject.bramble.api.system.AndroidWakeLockManager;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
import org.briarproject.bramble.api.system.LocationUtils;
|
||||
import org.briarproject.bramble.api.system.ResourceProvider;
|
||||
import org.briarproject.bramble.util.AndroidUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
import javax.net.SocketFactory;
|
||||
|
||||
import static android.os.Build.VERSION.SDK_INT;
|
||||
import static java.util.Arrays.asList;
|
||||
import static java.util.logging.Level.INFO;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
|
||||
@MethodsNotNullByDefault
|
||||
@ParametersNotNullByDefault
|
||||
class AndroidTorPlugin extends TorPlugin {
|
||||
|
||||
private static final List<String> LIBRARY_ARCHITECTURES =
|
||||
asList("armeabi-v7a", "arm64-v8a", "x86", "x86_64");
|
||||
|
||||
private static final String TOR_LIB_NAME = "libtor.so";
|
||||
private static final String OBFS4_LIB_NAME = "libobfs4proxy.so";
|
||||
|
||||
private static final Logger LOG =
|
||||
getLogger(AndroidTorPlugin.class.getName());
|
||||
|
||||
private final Application app;
|
||||
private final AndroidWakeLock wakeLock;
|
||||
private final File torLib, obfs4Lib;
|
||||
|
||||
AndroidTorPlugin(Executor ioExecutor,
|
||||
Executor wakefulIoExecutor,
|
||||
@@ -78,9 +55,6 @@ class AndroidTorPlugin extends TorPlugin {
|
||||
maxIdleTime, torDirectory);
|
||||
this.app = app;
|
||||
wakeLock = wakeLockManager.createWakeLock("TorPlugin");
|
||||
String nativeLibDir = app.getApplicationInfo().nativeLibraryDir;
|
||||
torLib = new File(nativeLibDir, TOR_LIB_NAME);
|
||||
obfs4Lib = new File(nativeLibDir, OBFS4_LIB_NAME);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -111,112 +85,4 @@ class AndroidTorPlugin extends TorPlugin {
|
||||
super.stop();
|
||||
wakeLock.release();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected File getTorExecutableFile() {
|
||||
return torLib.exists() ? torLib : super.getTorExecutableFile();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected File getObfs4ExecutableFile() {
|
||||
return obfs4Lib.exists() ? obfs4Lib : super.getObfs4ExecutableFile();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void installTorExecutable() throws IOException {
|
||||
File extracted = super.getTorExecutableFile();
|
||||
if (torLib.exists()) {
|
||||
// If an older version left behind a Tor binary, delete it
|
||||
if (extracted.exists()) {
|
||||
if (extracted.delete()) LOG.info("Deleted Tor binary");
|
||||
else LOG.info("Failed to delete Tor binary");
|
||||
}
|
||||
} else if (SDK_INT < 29) {
|
||||
// The binary wasn't extracted at install time. Try to extract it
|
||||
extractLibraryFromApk(TOR_LIB_NAME, extracted);
|
||||
} else {
|
||||
// No point extracting the binary, we won't be allowed to execute it
|
||||
throw new FileNotFoundException(torLib.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void installObfs4Executable() throws IOException {
|
||||
File extracted = super.getObfs4ExecutableFile();
|
||||
if (obfs4Lib.exists()) {
|
||||
// If an older version left behind an obfs4 binary, delete it
|
||||
if (extracted.exists()) {
|
||||
if (extracted.delete()) LOG.info("Deleted obfs4 binary");
|
||||
else LOG.info("Failed to delete obfs4 binary");
|
||||
}
|
||||
} else if (SDK_INT < 29) {
|
||||
// The binary wasn't extracted at install time. Try to extract it
|
||||
extractLibraryFromApk(OBFS4_LIB_NAME, extracted);
|
||||
} else {
|
||||
// No point extracting the binary, we won't be allowed to execute it
|
||||
throw new FileNotFoundException(obfs4Lib.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
|
||||
private void extractLibraryFromApk(String libName, File dest)
|
||||
throws IOException {
|
||||
File sourceDir = new File(app.getApplicationInfo().sourceDir);
|
||||
if (sourceDir.isFile()) {
|
||||
// Look for other APK files in the same directory, if we're allowed
|
||||
File parent = sourceDir.getParentFile();
|
||||
if (parent != null) sourceDir = parent;
|
||||
}
|
||||
List<String> libPaths = getSupportedLibraryPaths(libName);
|
||||
for (File apk : findApkFiles(sourceDir)) {
|
||||
ZipInputStream zin = new ZipInputStream(new FileInputStream(apk));
|
||||
for (ZipEntry e = zin.getNextEntry(); e != null;
|
||||
e = zin.getNextEntry()) {
|
||||
if (libPaths.contains(e.getName())) {
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info("Extracting " + e.getName()
|
||||
+ " from " + apk.getAbsolutePath());
|
||||
}
|
||||
extract(zin, dest); // Zip input stream will be closed
|
||||
return;
|
||||
}
|
||||
}
|
||||
zin.close();
|
||||
}
|
||||
throw new FileNotFoundException(libName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all files with the extension .apk or .APK under the given root.
|
||||
*/
|
||||
private List<File> findApkFiles(File root) {
|
||||
List<File> files = new ArrayList<>();
|
||||
findApkFiles(root, files);
|
||||
return files;
|
||||
}
|
||||
|
||||
private void findApkFiles(File f, List<File> files) {
|
||||
if (f.isFile() && f.getName().toLowerCase().endsWith(".apk")) {
|
||||
files.add(f);
|
||||
} else if (f.isDirectory()) {
|
||||
File[] children = f.listFiles();
|
||||
if (children != null) {
|
||||
for (File child : children) findApkFiles(child, files);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the paths at which libraries with the given name would be found
|
||||
* inside an APK file, for all architectures supported by the device, in
|
||||
* order of preference.
|
||||
*/
|
||||
private List<String> getSupportedLibraryPaths(String libName) {
|
||||
List<String> architectures = new ArrayList<>();
|
||||
for (String abi : AndroidUtils.getSupportedArchitectures()) {
|
||||
if (LIBRARY_ARCHITECTURES.contains(abi)) {
|
||||
architectures.add("lib/" + abi + "/" + libName);
|
||||
}
|
||||
}
|
||||
return architectures;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
package org.briarproject.bramble.api;
|
||||
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
/**
|
||||
* An item that can be consumed once.
|
||||
*/
|
||||
@NotNullByDefault
|
||||
public class Consumable<T> {
|
||||
|
||||
private final AtomicReference<T> reference;
|
||||
|
||||
public Consumable(T item) {
|
||||
reference = new AtomicReference<>(item);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public T consume() {
|
||||
return reference.getAndSet(null);
|
||||
}
|
||||
}
|
||||
@@ -35,24 +35,24 @@ public interface ClientHelper {
|
||||
|
||||
Message createMessageForStoringMetadata(GroupId g);
|
||||
|
||||
Message getSmallMessage(MessageId m) throws DbException;
|
||||
Message getMessage(MessageId m) throws DbException;
|
||||
|
||||
Message getSmallMessage(Transaction txn, MessageId m) throws DbException;
|
||||
Message getMessage(Transaction txn, MessageId m) throws DbException;
|
||||
|
||||
BdfList getSmallMessageAsList(MessageId m)
|
||||
throws DbException, FormatException;
|
||||
BdfList getMessageAsList(MessageId m) throws DbException, FormatException;
|
||||
|
||||
BdfList getSmallMessageAsList(Transaction txn, MessageId m)
|
||||
throws DbException, FormatException;
|
||||
BdfList getMessageAsList(Transaction txn, MessageId m) throws DbException,
|
||||
FormatException;
|
||||
|
||||
BdfDictionary getGroupMetadataAsDictionary(GroupId g)
|
||||
throws DbException, FormatException;
|
||||
BdfDictionary getGroupMetadataAsDictionary(GroupId g) throws DbException,
|
||||
FormatException;
|
||||
|
||||
BdfDictionary getGroupMetadataAsDictionary(Transaction txn, GroupId g)
|
||||
throws DbException, FormatException;
|
||||
|
||||
BdfDictionary getMessageMetadataAsDictionary(MessageId m)
|
||||
throws DbException, FormatException;
|
||||
throws DbException,
|
||||
FormatException;
|
||||
|
||||
BdfDictionary getMessageMetadataAsDictionary(Transaction txn, MessageId m)
|
||||
throws DbException, FormatException;
|
||||
@@ -67,8 +67,8 @@ public interface ClientHelper {
|
||||
BdfDictionary query) throws DbException, FormatException;
|
||||
|
||||
Map<MessageId, BdfDictionary> getMessageMetadataAsDictionary(
|
||||
Transaction txn, GroupId g, BdfDictionary query)
|
||||
throws DbException, FormatException;
|
||||
Transaction txn, GroupId g, BdfDictionary query) throws DbException,
|
||||
FormatException;
|
||||
|
||||
void mergeGroupMetadata(GroupId g, BdfDictionary metadata)
|
||||
throws DbException, FormatException;
|
||||
|
||||
@@ -5,6 +5,9 @@ import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
/**
|
||||
* Interface for strengthening a password-based key, for example by using a
|
||||
* key stored in a key management service or hardware security module.
|
||||
*
|
||||
* TODO: Remove after a reasonable migration period unless we can work around
|
||||
* Android keymaster bugs. Added 2020-02-24
|
||||
*/
|
||||
@NotNullByDefault
|
||||
public interface KeyStrengthener {
|
||||
|
||||
@@ -163,23 +163,27 @@ public interface DatabaseComponent extends TransactionManager {
|
||||
* less than or equal to the given length, for transmission over a
|
||||
* transport with the given maximum latency. Returns null if there are no
|
||||
* sendable messages that fit in the given length.
|
||||
*
|
||||
* @param small True if only single-block messages should be sent
|
||||
*/
|
||||
@Nullable
|
||||
Collection<Message> generateBatch(Transaction txn, ContactId c,
|
||||
int maxLength, int maxLatency, boolean small) throws DbException;
|
||||
int maxLength, int maxLatency) throws DbException;
|
||||
|
||||
/**
|
||||
* Returns an offer for the given contact for transmission over a
|
||||
* transport with the given maximum latency, or null if there are no
|
||||
* messages to offer.
|
||||
*
|
||||
* @param small True if only single-block messages should be offered
|
||||
*/
|
||||
@Nullable
|
||||
Offer generateOffer(Transaction txn, ContactId c, int maxMessages,
|
||||
int maxLatency, boolean small) throws DbException;
|
||||
int maxLatency) throws DbException;
|
||||
|
||||
/**
|
||||
* Returns a request for the given contact, or null if there are no
|
||||
* messages to request.
|
||||
*/
|
||||
@Nullable
|
||||
Request generateRequest(Transaction txn, ContactId c, int maxMessages)
|
||||
throws DbException;
|
||||
|
||||
/**
|
||||
* Returns a batch of messages for the given contact, with a total length
|
||||
@@ -268,14 +272,13 @@ public interface DatabaseComponent extends TransactionManager {
|
||||
Collection<Identity> getIdentities(Transaction txn) throws DbException;
|
||||
|
||||
/**
|
||||
* Returns the single-block message with the given ID.
|
||||
* Returns the message with the given ID.
|
||||
* <p/>
|
||||
* Read-only.
|
||||
*
|
||||
* @throws MessageDeletedException if the message has been deleted
|
||||
* @throws MessageTooLargeException if the message has more than one block
|
||||
*/
|
||||
Message getSmallMessage(Transaction txn, MessageId m) throws DbException;
|
||||
Message getMessage(Transaction txn, MessageId m) throws DbException;
|
||||
|
||||
/**
|
||||
* Returns the IDs of all delivered messages in the given group.
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
package org.briarproject.bramble.api.db;
|
||||
|
||||
/**
|
||||
* Thrown when a multi-block message is requested from the database via a
|
||||
* method that is only suitable for requesting single-block messages.
|
||||
*/
|
||||
public class MessageTooLargeException extends DbException {
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package org.briarproject.bramble.api.plugin.event;
|
||||
|
||||
import org.briarproject.bramble.api.event.Event;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
|
||||
/**
|
||||
* An event that informs the Bluetooth plugin that we have enabled the
|
||||
* Bluetooth adapter.
|
||||
*/
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
public class BluetoothEnabledEvent extends Event {
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package org.briarproject.bramble.api.plugin.event;
|
||||
|
||||
import org.briarproject.bramble.api.event.Event;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
|
||||
/**
|
||||
* An event that asks the Bluetooth plugin to disable the Bluetooth adapter if
|
||||
* we previously enabled it.
|
||||
*/
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
public class DisableBluetoothEvent extends Event {
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package org.briarproject.bramble.api.plugin.event;
|
||||
|
||||
import org.briarproject.bramble.api.event.Event;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
|
||||
/**
|
||||
* An event that asks the Bluetooth plugin to enable the Bluetooth adapter.
|
||||
*/
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
public class EnableBluetoothEvent extends Event {
|
||||
}
|
||||
@@ -29,15 +29,10 @@ public interface SyncConstants {
|
||||
*/
|
||||
int MESSAGE_HEADER_LENGTH = UniqueId.LENGTH + 8;
|
||||
|
||||
/**
|
||||
* The maximum length of a block in bytes.
|
||||
*/
|
||||
int MAX_BLOCK_LENGTH = 32 * 1024; // 32 KiB
|
||||
|
||||
/**
|
||||
* The maximum length of a message body in bytes.
|
||||
*/
|
||||
int MAX_MESSAGE_BODY_LENGTH = MAX_BLOCK_LENGTH;
|
||||
int MAX_MESSAGE_BODY_LENGTH = 32 * 1024; // 32 KiB
|
||||
|
||||
/**
|
||||
* The maximum length of a message in bytes.
|
||||
|
||||
@@ -7,16 +7,16 @@ import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
|
||||
/**
|
||||
* An event that is broadcast when one or more messages are received from, or
|
||||
* offered by, a contact and need to be acknowledged.
|
||||
* An event that is broadcast when a message is received from, or offered by, a
|
||||
* contact and needs to be acknowledged.
|
||||
*/
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
public class MessagesToAckEvent extends Event {
|
||||
public class MessageToAckEvent extends Event {
|
||||
|
||||
private final ContactId contactId;
|
||||
|
||||
public MessagesToAckEvent(ContactId contactId) {
|
||||
public MessageToAckEvent(ContactId contactId) {
|
||||
this.contactId = contactId;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package org.briarproject.bramble.api.sync.event;
|
||||
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.event.Event;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
|
||||
/**
|
||||
* An event that is broadcast when a message is offered by a contact and needs
|
||||
* to be requested.
|
||||
*/
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
public class MessageToRequestEvent extends Event {
|
||||
|
||||
private final ContactId contactId;
|
||||
|
||||
public MessageToRequestEvent(ContactId contactId) {
|
||||
this.contactId = contactId;
|
||||
}
|
||||
|
||||
public ContactId getContactId() {
|
||||
return contactId;
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package org.briarproject.bramble.api.sync.event;
|
||||
|
||||
import org.briarproject.bramble.api.Consumable;
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.event.Event;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.sync.MessageId;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
|
||||
/**
|
||||
* An event that is broadcast when one or more messages are offered by a
|
||||
* contact and need to be requested.
|
||||
*/
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
public class MessagesToRequestEvent extends Event {
|
||||
|
||||
private final ContactId contactId;
|
||||
private final Consumable<Collection<MessageId>> ids;
|
||||
|
||||
public MessagesToRequestEvent(ContactId contactId,
|
||||
Collection<MessageId> ids) {
|
||||
this.contactId = contactId;
|
||||
this.ids = new Consumable<>(ids);
|
||||
}
|
||||
|
||||
public ContactId getContactId() {
|
||||
return contactId;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Collection<MessageId> consumeIds() {
|
||||
return ids.consume();
|
||||
}
|
||||
}
|
||||
@@ -179,8 +179,9 @@ class AccountManagerImpl implements AccountManager {
|
||||
@GuardedBy("stateChangeLock")
|
||||
private boolean encryptAndStoreDatabaseKey(SecretKey key, String password) {
|
||||
byte[] plaintext = key.getBytes();
|
||||
byte[] ciphertext = crypto.encryptWithPassword(plaintext, password,
|
||||
databaseConfig.getKeyStrengthener());
|
||||
// Don't use a key strengthener as the Android keymaster isn't reliable
|
||||
byte[] ciphertext =
|
||||
crypto.encryptWithPassword(plaintext, password, null);
|
||||
return storeEncryptedDatabaseKey(toHexString(ciphertext));
|
||||
}
|
||||
|
||||
@@ -197,13 +198,13 @@ class AccountManagerImpl implements AccountManager {
|
||||
@Override
|
||||
public void signIn(String password) throws DecryptionException {
|
||||
synchronized (stateChangeLock) {
|
||||
databaseKey = loadAndDecryptDatabaseKey(password);
|
||||
databaseKey = loadAndDecryptDatabaseKey(password, false);
|
||||
}
|
||||
}
|
||||
|
||||
@GuardedBy("stateChangeLock")
|
||||
private SecretKey loadAndDecryptDatabaseKey(String password)
|
||||
throws DecryptionException {
|
||||
private SecretKey loadAndDecryptDatabaseKey(String password,
|
||||
boolean changing) throws DecryptionException {
|
||||
String hex = loadEncryptedDatabaseKey();
|
||||
if (hex == null) {
|
||||
LOG.warning("Failed to load encrypted database key");
|
||||
@@ -214,11 +215,11 @@ class AccountManagerImpl implements AccountManager {
|
||||
byte[] plaintext = crypto.decryptWithPassword(ciphertext, password,
|
||||
keyStrengthener);
|
||||
SecretKey key = new SecretKey(plaintext);
|
||||
// If the DB key was encrypted with a weak key and a key strengthener
|
||||
// is now available, re-encrypt the DB key with a strengthened key
|
||||
if (keyStrengthener != null &&
|
||||
!crypto.isEncryptedWithStrengthenedKey(ciphertext)) {
|
||||
LOG.info("Re-encrypting database key with strengthened key");
|
||||
// If the DB key was encrypted with a hardware-backed key, re-encrypt
|
||||
// it without the hardware-backed key so keymaster bugs don't delete
|
||||
// the user's account
|
||||
if (!changing && crypto.isEncryptedWithStrengthenedKey(ciphertext)) {
|
||||
LOG.info("Re-encrypting database key without strengthened key");
|
||||
encryptAndStoreDatabaseKey(key, password);
|
||||
}
|
||||
return key;
|
||||
@@ -228,7 +229,7 @@ class AccountManagerImpl implements AccountManager {
|
||||
public void changePassword(String oldPassword, String newPassword)
|
||||
throws DecryptionException {
|
||||
synchronized (stateChangeLock) {
|
||||
SecretKey key = loadAndDecryptDatabaseKey(oldPassword);
|
||||
SecretKey key = loadAndDecryptDatabaseKey(oldPassword, true);
|
||||
encryptAndStoreDatabaseKey(key, newPassword);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,27 +116,25 @@ class ClientHelperImpl implements ClientHelper {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Message getSmallMessage(MessageId m) throws DbException {
|
||||
return db.transactionWithResult(true, txn -> getSmallMessage(txn, m));
|
||||
public Message getMessage(MessageId m) throws DbException {
|
||||
return db.transactionWithResult(true, txn -> getMessage(txn, m));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Message getSmallMessage(Transaction txn, MessageId m)
|
||||
throws DbException {
|
||||
return db.getSmallMessage(txn, m);
|
||||
public Message getMessage(Transaction txn, MessageId m) throws DbException {
|
||||
return db.getMessage(txn, m);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BdfList getSmallMessageAsList(MessageId m)
|
||||
public BdfList getMessageAsList(MessageId m) throws DbException,
|
||||
FormatException {
|
||||
return db.transactionWithResult(true, txn -> getMessageAsList(txn, m));
|
||||
}
|
||||
|
||||
@Override
|
||||
public BdfList getMessageAsList(Transaction txn, MessageId m)
|
||||
throws DbException, FormatException {
|
||||
return db.transactionWithResult(true, txn ->
|
||||
getSmallMessageAsList(txn, m));
|
||||
}
|
||||
|
||||
@Override
|
||||
public BdfList getSmallMessageAsList(Transaction txn, MessageId m)
|
||||
throws DbException, FormatException {
|
||||
return toList(db.getSmallMessage(txn, m).getBody());
|
||||
return toList(db.getMessage(txn, m).getBody());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -12,7 +12,6 @@ import org.briarproject.bramble.api.db.DataTooOldException;
|
||||
import org.briarproject.bramble.api.db.DatabaseComponent;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
import org.briarproject.bramble.api.db.MessageDeletedException;
|
||||
import org.briarproject.bramble.api.db.MessageTooLargeException;
|
||||
import org.briarproject.bramble.api.db.Metadata;
|
||||
import org.briarproject.bramble.api.db.MigrationListener;
|
||||
import org.briarproject.bramble.api.identity.Author;
|
||||
@@ -126,6 +125,11 @@ interface Database<T> {
|
||||
void addMessageDependency(T txn, Message dependent, MessageId dependency,
|
||||
MessageState dependentState) throws DbException;
|
||||
|
||||
/**
|
||||
* Records that a message has been offered by the given contact.
|
||||
*/
|
||||
void addOfferedMessage(T txn, ContactId c, MessageId m) throws DbException;
|
||||
|
||||
/**
|
||||
* Stores a pending contact.
|
||||
*/
|
||||
@@ -214,6 +218,13 @@ interface Database<T> {
|
||||
boolean containsVisibleMessage(T txn, ContactId c, MessageId m)
|
||||
throws DbException;
|
||||
|
||||
/**
|
||||
* Returns the number of messages offered by the given contact.
|
||||
* <p/>
|
||||
* Read-only.
|
||||
*/
|
||||
int countOfferedMessages(T txn, ContactId c) throws DbException;
|
||||
|
||||
/**
|
||||
* Deletes the message with the given ID. Unlike
|
||||
* {@link #removeMessage(Object, MessageId)}, the message ID and any other
|
||||
@@ -321,14 +332,13 @@ interface Database<T> {
|
||||
Collection<Identity> getIdentities(T txn) throws DbException;
|
||||
|
||||
/**
|
||||
* Returns the single-block message with the given ID.
|
||||
* Returns the message with the given ID.
|
||||
* <p/>
|
||||
* Read-only.
|
||||
*
|
||||
* @throws MessageDeletedException if the message has been deleted
|
||||
* @throws MessageTooLargeException if the message has more than one block
|
||||
*/
|
||||
Message getSmallMessage(T txn, MessageId m) throws DbException;
|
||||
Message getMessage(T txn, MessageId m) throws DbException;
|
||||
|
||||
/**
|
||||
* Returns the IDs and states of all dependencies of the given message.
|
||||
@@ -447,13 +457,13 @@ interface Database<T> {
|
||||
int maxMessages, int maxLatency) throws DbException;
|
||||
|
||||
/**
|
||||
* Returns the IDs of some single-block messages that are eligible to be
|
||||
* offered to the given contact, up to the given number of messages.
|
||||
* Returns the IDs of some messages that are eligible to be requested from
|
||||
* the given contact, up to the given number of messages.
|
||||
* <p/>
|
||||
* Read-only.
|
||||
*/
|
||||
Collection<MessageId> getSmallMessagesToOffer(T txn, ContactId c,
|
||||
int maxMessages, int maxLatency) throws DbException;
|
||||
Collection<MessageId> getMessagesToRequest(T txn, ContactId c,
|
||||
int maxMessages) throws DbException;
|
||||
|
||||
/**
|
||||
* Returns the IDs of some messages that are eligible to be sent to the
|
||||
@@ -464,15 +474,6 @@ interface Database<T> {
|
||||
Collection<MessageId> getMessagesToSend(T txn, ContactId c, int maxLength,
|
||||
int maxLatency) throws DbException;
|
||||
|
||||
/**
|
||||
* Returns the IDs of some single-block messages that are eligible to be
|
||||
* sent to the given contact, up to the given total length.
|
||||
* <p/>
|
||||
* Read-only.
|
||||
*/
|
||||
Collection<MessageId> getSmallMessagesToSend(T txn, ContactId c,
|
||||
int maxLength, int maxLatency) throws DbException;
|
||||
|
||||
/**
|
||||
* Returns the IDs of any messages that need to be validated.
|
||||
* <p/>
|
||||
@@ -635,6 +636,13 @@ interface Database<T> {
|
||||
*/
|
||||
void removeMessage(T txn, MessageId m) throws DbException;
|
||||
|
||||
/**
|
||||
* Removes the given offered messages that were offered by the given
|
||||
* contact.
|
||||
*/
|
||||
void removeOfferedMessages(T txn, ContactId c,
|
||||
Collection<MessageId> requested) throws DbException;
|
||||
|
||||
/**
|
||||
* Removes a pending contact (and all associated state) from the database.
|
||||
*/
|
||||
|
||||
@@ -61,10 +61,10 @@ import org.briarproject.bramble.api.sync.event.MessageAddedEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessageRequestedEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessageSharedEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessageStateChangedEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessageToAckEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessageToRequestEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessagesAckedEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessagesSentEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessagesToAckEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessagesToRequestEvent;
|
||||
import org.briarproject.bramble.api.sync.event.SyncVersionsUpdatedEvent;
|
||||
import org.briarproject.bramble.api.sync.validation.MessageState;
|
||||
import org.briarproject.bramble.api.transport.KeySetId;
|
||||
@@ -91,6 +91,7 @@ import static org.briarproject.bramble.api.sync.Group.Visibility.INVISIBLE;
|
||||
import static org.briarproject.bramble.api.sync.Group.Visibility.SHARED;
|
||||
import static org.briarproject.bramble.api.sync.validation.MessageState.DELIVERED;
|
||||
import static org.briarproject.bramble.api.sync.validation.MessageState.UNKNOWN;
|
||||
import static org.briarproject.bramble.db.DatabaseConstants.MAX_OFFERED_MESSAGES;
|
||||
import static org.briarproject.bramble.util.LogUtils.logDuration;
|
||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||
import static org.briarproject.bramble.util.LogUtils.now;
|
||||
@@ -405,22 +406,19 @@ class DatabaseComponentImpl<T> implements DatabaseComponent {
|
||||
@Nullable
|
||||
@Override
|
||||
public Collection<Message> generateBatch(Transaction transaction,
|
||||
ContactId c, int maxLength, int maxLatency, boolean small)
|
||||
throws DbException {
|
||||
ContactId c, int maxLength, int maxLatency) throws DbException {
|
||||
if (transaction.isReadOnly()) throw new IllegalArgumentException();
|
||||
T txn = unbox(transaction);
|
||||
if (!db.containsContact(txn, c))
|
||||
throw new NoSuchContactException();
|
||||
Collection<MessageId> ids;
|
||||
if (small)
|
||||
ids = db.getSmallMessagesToSend(txn, c, maxLength, maxLatency);
|
||||
else ids = db.getMessagesToSend(txn, c, maxLength, maxLatency);
|
||||
if (ids.isEmpty()) return null;
|
||||
Collection<MessageId> ids =
|
||||
db.getMessagesToSend(txn, c, maxLength, maxLatency);
|
||||
List<Message> messages = new ArrayList<>(ids.size());
|
||||
for (MessageId m : ids) {
|
||||
messages.add(db.getSmallMessage(txn, m));
|
||||
messages.add(db.getMessage(txn, m));
|
||||
db.updateExpiryTimeAndEta(txn, c, m, maxLatency);
|
||||
}
|
||||
if (ids.isEmpty()) return null;
|
||||
db.lowerRequestedFlag(txn, c, ids);
|
||||
transaction.attach(new MessagesSentEvent(c, ids));
|
||||
return messages;
|
||||
@@ -429,21 +427,34 @@ class DatabaseComponentImpl<T> implements DatabaseComponent {
|
||||
@Nullable
|
||||
@Override
|
||||
public Offer generateOffer(Transaction transaction, ContactId c,
|
||||
int maxMessages, int maxLatency, boolean small) throws DbException {
|
||||
int maxMessages, int maxLatency) throws DbException {
|
||||
if (transaction.isReadOnly()) throw new IllegalArgumentException();
|
||||
T txn = unbox(transaction);
|
||||
if (!db.containsContact(txn, c))
|
||||
throw new NoSuchContactException();
|
||||
Collection<MessageId> ids;
|
||||
if (small)
|
||||
ids = db.getSmallMessagesToOffer(txn, c, maxMessages, maxLatency);
|
||||
else ids = db.getMessagesToOffer(txn, c, maxMessages, maxLatency);
|
||||
Collection<MessageId> ids =
|
||||
db.getMessagesToOffer(txn, c, maxMessages, maxLatency);
|
||||
if (ids.isEmpty()) return null;
|
||||
for (MessageId m : ids)
|
||||
db.updateExpiryTimeAndEta(txn, c, m, maxLatency);
|
||||
return new Offer(ids);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public Request generateRequest(Transaction transaction, ContactId c,
|
||||
int maxMessages) throws DbException {
|
||||
if (transaction.isReadOnly()) throw new IllegalArgumentException();
|
||||
T txn = unbox(transaction);
|
||||
if (!db.containsContact(txn, c))
|
||||
throw new NoSuchContactException();
|
||||
Collection<MessageId> ids = db.getMessagesToRequest(txn, c,
|
||||
maxMessages);
|
||||
if (ids.isEmpty()) return null;
|
||||
db.removeOfferedMessages(txn, c, ids);
|
||||
return new Request(ids);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public Collection<Message> generateRequestedBatch(Transaction transaction,
|
||||
@@ -454,12 +465,12 @@ class DatabaseComponentImpl<T> implements DatabaseComponent {
|
||||
throw new NoSuchContactException();
|
||||
Collection<MessageId> ids =
|
||||
db.getRequestedMessagesToSend(txn, c, maxLength, maxLatency);
|
||||
if (ids.isEmpty()) return null;
|
||||
List<Message> messages = new ArrayList<>(ids.size());
|
||||
for (MessageId m : ids) {
|
||||
messages.add(db.getSmallMessage(txn, m));
|
||||
messages.add(db.getMessage(txn, m));
|
||||
db.updateExpiryTimeAndEta(txn, c, m, maxLatency);
|
||||
}
|
||||
if (ids.isEmpty()) return null;
|
||||
db.lowerRequestedFlag(txn, c, ids);
|
||||
transaction.attach(new MessagesSentEvent(c, ids));
|
||||
return messages;
|
||||
@@ -548,12 +559,12 @@ class DatabaseComponentImpl<T> implements DatabaseComponent {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Message getSmallMessage(Transaction transaction, MessageId m)
|
||||
public Message getMessage(Transaction transaction, MessageId m)
|
||||
throws DbException {
|
||||
T txn = unbox(transaction);
|
||||
if (!db.containsMessage(txn, m))
|
||||
throw new NoSuchMessageException();
|
||||
return db.getSmallMessage(txn, m);
|
||||
return db.getMessage(txn, m);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -808,7 +819,7 @@ class DatabaseComponentImpl<T> implements DatabaseComponent {
|
||||
db.addMessage(txn, m, UNKNOWN, false, false, c);
|
||||
transaction.attach(new MessageAddedEvent(m, c));
|
||||
}
|
||||
transaction.attach(new MessagesToAckEvent(c));
|
||||
transaction.attach(new MessageToAckEvent(c));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -819,20 +830,21 @@ class DatabaseComponentImpl<T> implements DatabaseComponent {
|
||||
T txn = unbox(transaction);
|
||||
if (!db.containsContact(txn, c))
|
||||
throw new NoSuchContactException();
|
||||
boolean ack = false;
|
||||
List<MessageId> request = new ArrayList<>(o.getMessageIds().size());
|
||||
boolean ack = false, request = false;
|
||||
int count = db.countOfferedMessages(txn, c);
|
||||
for (MessageId m : o.getMessageIds()) {
|
||||
if (db.containsVisibleMessage(txn, c, m)) {
|
||||
db.raiseSeenFlag(txn, c, m);
|
||||
db.raiseAckFlag(txn, c, m);
|
||||
ack = true;
|
||||
} else {
|
||||
request.add(m);
|
||||
} else if (count < MAX_OFFERED_MESSAGES) {
|
||||
db.addOfferedMessage(txn, c, m);
|
||||
request = true;
|
||||
count++;
|
||||
}
|
||||
}
|
||||
if (ack) transaction.attach(new MessagesToAckEvent(c));
|
||||
if (!request.isEmpty())
|
||||
transaction.attach(new MessagesToRequestEvent(c, request));
|
||||
if (ack) transaction.attach(new MessageToAckEvent(c));
|
||||
if (request) transaction.attach(new MessageToRequestEvent(c));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -6,6 +6,13 @@ import static java.util.concurrent.TimeUnit.DAYS;
|
||||
|
||||
interface DatabaseConstants {
|
||||
|
||||
/**
|
||||
* The maximum number of offered messages from each contact that will be
|
||||
* stored. If offers arrive more quickly than requests can be sent and this
|
||||
* limit is reached, additional offers will not be stored.
|
||||
*/
|
||||
int MAX_OFFERED_MESSAGES = 1000;
|
||||
|
||||
/**
|
||||
* The namespace of the {@link Settings} where the database schema version
|
||||
* is stored.
|
||||
|
||||
@@ -6,6 +6,7 @@ import org.briarproject.bramble.api.db.TransactionManager;
|
||||
import org.briarproject.bramble.api.event.EventBus;
|
||||
import org.briarproject.bramble.api.event.EventExecutor;
|
||||
import org.briarproject.bramble.api.lifecycle.ShutdownManager;
|
||||
import org.briarproject.bramble.api.sync.MessageFactory;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
|
||||
import java.sql.Connection;
|
||||
@@ -21,8 +22,9 @@ public class DatabaseModule {
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
Database<Connection> provideDatabase(DatabaseConfig config, Clock clock) {
|
||||
return new H2Database(config, clock);
|
||||
Database<Connection> provideDatabase(DatabaseConfig config,
|
||||
MessageFactory messageFactory, Clock clock) {
|
||||
return new H2Database(config, messageFactory, clock);
|
||||
}
|
||||
|
||||
@Provides
|
||||
|
||||
@@ -6,6 +6,7 @@ import org.briarproject.bramble.api.db.DbClosedException;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
import org.briarproject.bramble.api.db.MigrationListener;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.sync.MessageFactory;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
import org.briarproject.bramble.util.StringUtils;
|
||||
|
||||
@@ -50,8 +51,9 @@ class H2Database extends JdbcDatabase {
|
||||
private volatile SecretKey key = null;
|
||||
|
||||
@Inject
|
||||
H2Database(DatabaseConfig config, Clock clock) {
|
||||
super(dbTypes, clock);
|
||||
H2Database(DatabaseConfig config, MessageFactory messageFactory,
|
||||
Clock clock) {
|
||||
super(dbTypes, messageFactory, clock);
|
||||
this.config = config;
|
||||
File dir = config.getDatabaseDirectory();
|
||||
String path = new File(dir, "db").getAbsolutePath();
|
||||
|
||||
@@ -6,6 +6,7 @@ import org.briarproject.bramble.api.db.DbClosedException;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
import org.briarproject.bramble.api.db.MigrationListener;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.sync.MessageFactory;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
import org.briarproject.bramble.util.StringUtils;
|
||||
|
||||
@@ -50,8 +51,9 @@ class HyperSqlDatabase extends JdbcDatabase {
|
||||
private volatile SecretKey key = null;
|
||||
|
||||
@Inject
|
||||
HyperSqlDatabase(DatabaseConfig config, Clock clock) {
|
||||
super(dbTypes, clock);
|
||||
HyperSqlDatabase(DatabaseConfig config, MessageFactory messageFactory,
|
||||
Clock clock) {
|
||||
super(dbTypes, messageFactory, clock);
|
||||
this.config = config;
|
||||
File dir = config.getDatabaseDirectory();
|
||||
String path = new File(dir, "db").getAbsolutePath();
|
||||
|
||||
@@ -16,7 +16,6 @@ import org.briarproject.bramble.api.db.DataTooOldException;
|
||||
import org.briarproject.bramble.api.db.DbClosedException;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
import org.briarproject.bramble.api.db.MessageDeletedException;
|
||||
import org.briarproject.bramble.api.db.MessageTooLargeException;
|
||||
import org.briarproject.bramble.api.db.Metadata;
|
||||
import org.briarproject.bramble.api.db.MigrationListener;
|
||||
import org.briarproject.bramble.api.identity.Author;
|
||||
@@ -31,6 +30,7 @@ import org.briarproject.bramble.api.sync.Group;
|
||||
import org.briarproject.bramble.api.sync.Group.Visibility;
|
||||
import org.briarproject.bramble.api.sync.GroupId;
|
||||
import org.briarproject.bramble.api.sync.Message;
|
||||
import org.briarproject.bramble.api.sync.MessageFactory;
|
||||
import org.briarproject.bramble.api.sync.MessageId;
|
||||
import org.briarproject.bramble.api.sync.MessageStatus;
|
||||
import org.briarproject.bramble.api.sync.validation.MessageState;
|
||||
@@ -76,7 +76,6 @@ import static org.briarproject.bramble.api.db.Metadata.REMOVE;
|
||||
import static org.briarproject.bramble.api.sync.Group.Visibility.INVISIBLE;
|
||||
import static org.briarproject.bramble.api.sync.Group.Visibility.SHARED;
|
||||
import static org.briarproject.bramble.api.sync.Group.Visibility.VISIBLE;
|
||||
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_BLOCK_LENGTH;
|
||||
import static org.briarproject.bramble.api.sync.SyncConstants.MESSAGE_HEADER_LENGTH;
|
||||
import static org.briarproject.bramble.api.sync.validation.MessageState.DELIVERED;
|
||||
import static org.briarproject.bramble.api.sync.validation.MessageState.PENDING;
|
||||
@@ -99,7 +98,7 @@ import static org.briarproject.bramble.util.LogUtils.now;
|
||||
abstract class JdbcDatabase implements Database<Connection> {
|
||||
|
||||
// Package access for testing
|
||||
static final int CODE_SCHEMA_VERSION = 49;
|
||||
static final int CODE_SCHEMA_VERSION = 47;
|
||||
|
||||
// Time period offsets for incoming transport keys
|
||||
private static final int OFFSET_PREV = -1;
|
||||
@@ -181,9 +180,8 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
+ " state INT NOT NULL,"
|
||||
+ " shared BOOLEAN NOT NULL,"
|
||||
+ " temporary BOOLEAN NOT NULL,"
|
||||
+ " length INT NOT NULL," // Includes message header
|
||||
+ " deleted BOOLEAN NOT NULL,"
|
||||
+ " blockCount INT NOT NULL,"
|
||||
+ " length INT NOT NULL,"
|
||||
+ " raw BLOB," // Null if message has been deleted
|
||||
+ " PRIMARY KEY (messageId),"
|
||||
+ " FOREIGN KEY (groupId)"
|
||||
+ " REFERENCES groups (groupId)"
|
||||
@@ -220,15 +218,13 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
+ " REFERENCES messages (messageId)"
|
||||
+ " ON DELETE CASCADE)";
|
||||
|
||||
private static final String CREATE_BLOCKS =
|
||||
"CREATE TABLE blocks"
|
||||
+ " (messageId _HASH NOT NULL,"
|
||||
+ " blockNumber INT NOT NULL,"
|
||||
+ " blockLength INT NOT NULL," // Excludes block header
|
||||
+ " data BLOB," // Null if message has been deleted
|
||||
+ " PRIMARY KEY (messageId, blockNumber),"
|
||||
+ " FOREIGN KEY (messageId)"
|
||||
+ " REFERENCES messages (messageId)"
|
||||
private static final String CREATE_OFFERS =
|
||||
"CREATE TABLE offers"
|
||||
+ " (messageId _HASH NOT NULL," // Not a foreign key
|
||||
+ " contactId INT NOT NULL,"
|
||||
+ " PRIMARY KEY (messageId, contactId),"
|
||||
+ " FOREIGN KEY (contactId)"
|
||||
+ " REFERENCES contacts (contactId)"
|
||||
+ " ON DELETE CASCADE)";
|
||||
|
||||
private static final String CREATE_STATUSES =
|
||||
@@ -343,6 +339,7 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
private static final Logger LOG =
|
||||
getLogger(JdbcDatabase.class.getName());
|
||||
|
||||
private final MessageFactory messageFactory;
|
||||
private final Clock clock;
|
||||
private final DatabaseTypes dbTypes;
|
||||
|
||||
@@ -362,8 +359,10 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
|
||||
protected abstract void compactAndClose() throws DbException;
|
||||
|
||||
JdbcDatabase(DatabaseTypes databaseTypes, Clock clock) {
|
||||
JdbcDatabase(DatabaseTypes databaseTypes, MessageFactory messageFactory,
|
||||
Clock clock) {
|
||||
this.dbTypes = databaseTypes;
|
||||
this.messageFactory = messageFactory;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@@ -441,12 +440,10 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Migrating from schema " + start + " to " + end);
|
||||
if (listener != null) listener.onDatabaseMigration();
|
||||
long startTime = now();
|
||||
// Apply the migration
|
||||
m.migrate(txn);
|
||||
// Store the new schema version
|
||||
storeSchemaVersion(txn, end);
|
||||
logDuration(LOG, "Migration", startTime);
|
||||
dataSchemaVersion = end;
|
||||
}
|
||||
}
|
||||
@@ -466,9 +463,7 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
new Migration43_44(dbTypes),
|
||||
new Migration44_45(),
|
||||
new Migration45_46(),
|
||||
new Migration46_47(dbTypes),
|
||||
new Migration47_48(dbTypes),
|
||||
new Migration48_49()
|
||||
new Migration46_47(dbTypes)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -513,7 +508,7 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
s.executeUpdate(dbTypes.replaceTypes(CREATE_MESSAGES));
|
||||
s.executeUpdate(dbTypes.replaceTypes(CREATE_MESSAGE_METADATA));
|
||||
s.executeUpdate(dbTypes.replaceTypes(CREATE_MESSAGE_DEPENDENCIES));
|
||||
s.executeUpdate(dbTypes.replaceTypes(CREATE_BLOCKS));
|
||||
s.executeUpdate(dbTypes.replaceTypes(CREATE_OFFERS));
|
||||
s.executeUpdate(dbTypes.replaceTypes(CREATE_STATUSES));
|
||||
s.executeUpdate(dbTypes.replaceTypes(CREATE_TRANSPORTS));
|
||||
s.executeUpdate(dbTypes.replaceTypes(CREATE_PENDING_CONTACTS));
|
||||
@@ -731,7 +726,7 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
ResultSet rs = null;
|
||||
try {
|
||||
String sql = "SELECT messageId, timestamp, state, shared,"
|
||||
+ " length, deleted"
|
||||
+ " length, raw IS NULL"
|
||||
+ " FROM messages"
|
||||
+ " WHERE groupId = ?";
|
||||
ps = txn.prepareStatement(sql);
|
||||
@@ -744,8 +739,9 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
boolean messageShared = rs.getBoolean(4);
|
||||
int length = rs.getInt(5);
|
||||
boolean deleted = rs.getBoolean(6);
|
||||
boolean seen = removeOfferedMessage(txn, c, id);
|
||||
addStatus(txn, id, c, g, timestamp, length, state, groupShared,
|
||||
messageShared, deleted, false);
|
||||
messageShared, deleted, seen);
|
||||
}
|
||||
rs.close();
|
||||
ps.close();
|
||||
@@ -792,8 +788,8 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
PreparedStatement ps = null;
|
||||
try {
|
||||
String sql = "INSERT INTO messages (messageId, groupId, timestamp,"
|
||||
+ " state, shared, temporary, length, deleted, blockCount)"
|
||||
+ " VALUES (?, ?, ?, ?, ?, ?, ?, FALSE, 1)";
|
||||
+ " state, shared, temporary, length, raw)"
|
||||
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
|
||||
ps = txn.prepareStatement(sql);
|
||||
ps.setBytes(1, m.getId().getBytes());
|
||||
ps.setBytes(2, m.getGroupId().getBytes());
|
||||
@@ -801,29 +797,21 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
ps.setInt(4, state.getValue());
|
||||
ps.setBoolean(5, shared);
|
||||
ps.setBoolean(6, temporary);
|
||||
ps.setInt(7, m.getRawLength());
|
||||
byte[] raw = messageFactory.getRawMessage(m);
|
||||
ps.setInt(7, raw.length);
|
||||
ps.setBytes(8, raw);
|
||||
int affected = ps.executeUpdate();
|
||||
if (affected != 1) throw new DbStateException();
|
||||
ps.close();
|
||||
sql = "INSERT INTO blocks (messageId, blockNumber, blockLength,"
|
||||
+ " data)"
|
||||
+ " VALUES (?, 0, ?, ?)";
|
||||
ps = txn.prepareStatement(sql);
|
||||
ps.setBytes(1, m.getId().getBytes());
|
||||
ps.setInt(2, m.getBody().length);
|
||||
ps.setBytes(3, m.getBody());
|
||||
affected = ps.executeUpdate();
|
||||
if (affected != 1) throw new DbStateException();
|
||||
ps.close();
|
||||
// Create a status row for each contact that can see the group
|
||||
Map<ContactId, Boolean> visibility =
|
||||
getGroupVisibility(txn, m.getGroupId());
|
||||
for (Entry<ContactId, Boolean> e : visibility.entrySet()) {
|
||||
ContactId c = e.getKey();
|
||||
boolean seen = c.equals(sender);
|
||||
boolean offered = removeOfferedMessage(txn, c, m.getId());
|
||||
boolean seen = offered || c.equals(sender);
|
||||
addStatus(txn, m.getId(), c, m.getGroupId(), m.getTimestamp(),
|
||||
m.getRawLength(), state, e.getValue(), shared, false,
|
||||
seen);
|
||||
raw.length, state, e.getValue(), shared, false, seen);
|
||||
}
|
||||
// Update denormalised column in messageDependencies if dependency
|
||||
// is in same group as dependent
|
||||
@@ -842,6 +830,37 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addOfferedMessage(Connection txn, ContactId c, MessageId m)
|
||||
throws DbException {
|
||||
PreparedStatement ps = null;
|
||||
ResultSet rs = null;
|
||||
try {
|
||||
String sql = "SELECT NULL FROM offers"
|
||||
+ " WHERE messageId = ? AND contactId = ?";
|
||||
ps = txn.prepareStatement(sql);
|
||||
ps.setBytes(1, m.getBytes());
|
||||
ps.setInt(2, c.getInt());
|
||||
rs = ps.executeQuery();
|
||||
boolean found = rs.next();
|
||||
if (rs.next()) throw new DbStateException();
|
||||
rs.close();
|
||||
ps.close();
|
||||
if (found) return;
|
||||
sql = "INSERT INTO offers (messageId, contactId) VALUES (?, ?)";
|
||||
ps = txn.prepareStatement(sql);
|
||||
ps.setBytes(1, m.getBytes());
|
||||
ps.setInt(2, c.getInt());
|
||||
int affected = ps.executeUpdate();
|
||||
if (affected != 1) throw new DbStateException();
|
||||
ps.close();
|
||||
} catch (SQLException e) {
|
||||
tryToClose(rs, LOG, WARNING);
|
||||
tryToClose(ps, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private void addStatus(Connection txn, MessageId m, ContactId c, GroupId g,
|
||||
long timestamp, int length, MessageState state, boolean groupShared,
|
||||
boolean messageShared, boolean deleted, boolean seen)
|
||||
@@ -1243,22 +1262,40 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int countOfferedMessages(Connection txn, ContactId c)
|
||||
throws DbException {
|
||||
PreparedStatement ps = null;
|
||||
ResultSet rs = null;
|
||||
try {
|
||||
String sql = "SELECT COUNT (messageId) FROM offers "
|
||||
+ " WHERE contactId = ?";
|
||||
ps = txn.prepareStatement(sql);
|
||||
ps.setInt(1, c.getInt());
|
||||
rs = ps.executeQuery();
|
||||
if (!rs.next()) throw new DbException();
|
||||
int count = rs.getInt(1);
|
||||
if (rs.next()) throw new DbException();
|
||||
rs.close();
|
||||
ps.close();
|
||||
return count;
|
||||
} catch (SQLException e) {
|
||||
tryToClose(rs, LOG, WARNING);
|
||||
tryToClose(ps, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteMessage(Connection txn, MessageId m) throws DbException {
|
||||
PreparedStatement ps = null;
|
||||
try {
|
||||
String sql = "UPDATE messages SET deleted = TRUE"
|
||||
+ " WHERE messageId = ?";
|
||||
String sql = "UPDATE messages SET raw = NULL WHERE messageId = ?";
|
||||
ps = txn.prepareStatement(sql);
|
||||
ps.setBytes(1, m.getBytes());
|
||||
int affected = ps.executeUpdate();
|
||||
if (affected < 0 || affected > 1) throw new DbStateException();
|
||||
ps.close();
|
||||
sql = "UPDATE blocks SET data = NULL WHERE messageId = ?";
|
||||
ps = txn.prepareStatement(sql);
|
||||
ps.setBytes(1, m.getBytes());
|
||||
affected = ps.executeUpdate();
|
||||
if (affected < 0) throw new DbStateException();
|
||||
if (affected > 1) throw new DbStateException();
|
||||
ps.close();
|
||||
// Update denormalised column in statuses
|
||||
sql = "UPDATE statuses SET deleted = TRUE WHERE messageId = ?";
|
||||
@@ -1651,13 +1688,11 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Message getSmallMessage(Connection txn, MessageId m)
|
||||
throws DbException {
|
||||
public Message getMessage(Connection txn, MessageId m) throws DbException {
|
||||
PreparedStatement ps = null;
|
||||
ResultSet rs = null;
|
||||
try {
|
||||
String sql = "SELECT groupId, timestamp, deleted, blockCount"
|
||||
+ " FROM messages"
|
||||
String sql = "SELECT groupId, timestamp, raw FROM messages"
|
||||
+ " WHERE messageId = ?";
|
||||
ps = txn.prepareStatement(sql);
|
||||
ps.setBytes(1, m.getBytes());
|
||||
@@ -1665,25 +1700,15 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
if (!rs.next()) throw new DbStateException();
|
||||
GroupId g = new GroupId(rs.getBytes(1));
|
||||
long timestamp = rs.getLong(2);
|
||||
boolean deleted = rs.getBoolean(3);
|
||||
int blockCount = rs.getInt(4);
|
||||
byte[] raw = rs.getBytes(3);
|
||||
if (rs.next()) throw new DbStateException();
|
||||
rs.close();
|
||||
ps.close();
|
||||
if (deleted) throw new MessageDeletedException();
|
||||
if (blockCount > 1) throw new MessageTooLargeException();
|
||||
sql = "SELECT data FROM blocks"
|
||||
+ " WHERE messageId = ? AND blockNumber = 0";
|
||||
ps = txn.prepareStatement(sql);
|
||||
ps.setBytes(1, m.getBytes());
|
||||
rs = ps.executeQuery();
|
||||
if (!rs.next()) throw new DbStateException();
|
||||
byte[] data = rs.getBytes(1);
|
||||
if (data == null) throw new DbStateException();
|
||||
if (rs.next()) throw new DbStateException();
|
||||
rs.close();
|
||||
ps.close();
|
||||
return new Message(m, g, timestamp, data);
|
||||
if (raw == null) throw new MessageDeletedException();
|
||||
if (raw.length <= MESSAGE_HEADER_LENGTH) throw new AssertionError();
|
||||
byte[] body = new byte[raw.length - MESSAGE_HEADER_LENGTH];
|
||||
System.arraycopy(raw, MESSAGE_HEADER_LENGTH, body, 0, body.length);
|
||||
return new Message(m, g, timestamp, body);
|
||||
} catch (SQLException e) {
|
||||
tryToClose(rs, LOG, WARNING);
|
||||
tryToClose(ps, LOG, WARNING);
|
||||
@@ -2076,28 +2101,17 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<MessageId> getSmallMessagesToOffer(Connection txn,
|
||||
ContactId c, int maxMessages, int maxLatency) throws DbException {
|
||||
long now = clock.currentTimeMillis();
|
||||
long eta = now + maxLatency;
|
||||
public Collection<MessageId> getMessagesToRequest(Connection txn,
|
||||
ContactId c, int maxMessages) throws DbException {
|
||||
PreparedStatement ps = null;
|
||||
ResultSet rs = null;
|
||||
try {
|
||||
String sql = "SELECT messageId FROM statuses"
|
||||
+ " WHERE contactId = ? AND state = ?"
|
||||
+ " AND length <= ?"
|
||||
+ " AND groupShared = TRUE AND messageShared = TRUE"
|
||||
+ " AND deleted = FALSE"
|
||||
+ " AND seen = FALSE AND requested = FALSE"
|
||||
+ " AND (expiry <= ? OR eta > ?)"
|
||||
+ " ORDER BY timestamp LIMIT ?";
|
||||
String sql = "SELECT messageId FROM offers"
|
||||
+ " WHERE contactId = ?"
|
||||
+ " LIMIT ?";
|
||||
ps = txn.prepareStatement(sql);
|
||||
ps.setInt(1, c.getInt());
|
||||
ps.setInt(2, DELIVERED.getValue());
|
||||
ps.setInt(3, MESSAGE_HEADER_LENGTH + MAX_BLOCK_LENGTH);
|
||||
ps.setLong(4, now);
|
||||
ps.setLong(5, eta);
|
||||
ps.setInt(6, maxMessages);
|
||||
ps.setInt(2, maxMessages);
|
||||
rs = ps.executeQuery();
|
||||
List<MessageId> ids = new ArrayList<>();
|
||||
while (rs.next()) ids.add(new MessageId(rs.getBytes(1)));
|
||||
@@ -2150,47 +2164,6 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<MessageId> getSmallMessagesToSend(Connection txn,
|
||||
ContactId c, int maxLength, int maxLatency) throws DbException {
|
||||
long now = clock.currentTimeMillis();
|
||||
long eta = now + maxLatency;
|
||||
PreparedStatement ps = null;
|
||||
ResultSet rs = null;
|
||||
try {
|
||||
String sql = "SELECT length, messageId FROM statuses"
|
||||
+ " WHERE contactId = ? AND state = ?"
|
||||
+ " AND length <= ?"
|
||||
+ " AND groupShared = TRUE AND messageShared = TRUE"
|
||||
+ " AND deleted = FALSE"
|
||||
+ " AND seen = FALSE"
|
||||
+ " AND (expiry <= ? OR eta > ?)"
|
||||
+ " ORDER BY timestamp";
|
||||
ps = txn.prepareStatement(sql);
|
||||
ps.setInt(1, c.getInt());
|
||||
ps.setInt(2, DELIVERED.getValue());
|
||||
ps.setInt(3, MESSAGE_HEADER_LENGTH + MAX_BLOCK_LENGTH);
|
||||
ps.setLong(4, now);
|
||||
ps.setLong(5, eta);
|
||||
rs = ps.executeQuery();
|
||||
List<MessageId> ids = new ArrayList<>();
|
||||
int total = 0;
|
||||
while (rs.next()) {
|
||||
int length = rs.getInt(1);
|
||||
if (total + length > maxLength) break;
|
||||
ids.add(new MessageId(rs.getBytes(2)));
|
||||
total += length;
|
||||
}
|
||||
rs.close();
|
||||
ps.close();
|
||||
return ids;
|
||||
} catch (SQLException e) {
|
||||
tryToClose(rs, LOG, WARNING);
|
||||
tryToClose(ps, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<MessageId> getMessagesToValidate(Connection txn)
|
||||
throws DbException {
|
||||
@@ -2209,7 +2182,7 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
ResultSet rs = null;
|
||||
try {
|
||||
String sql = "SELECT messageId FROM messages"
|
||||
+ " WHERE state = ? AND deleted = FALSE";
|
||||
+ " WHERE state = ? AND raw IS NOT NULL";
|
||||
ps = txn.prepareStatement(sql);
|
||||
ps.setInt(1, state.getValue());
|
||||
rs = ps.executeQuery();
|
||||
@@ -2914,6 +2887,50 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
}
|
||||
}
|
||||
|
||||
private boolean removeOfferedMessage(Connection txn, ContactId c,
|
||||
MessageId m) throws DbException {
|
||||
PreparedStatement ps = null;
|
||||
try {
|
||||
String sql = "DELETE FROM offers"
|
||||
+ " WHERE contactId = ? AND messageId = ?";
|
||||
ps = txn.prepareStatement(sql);
|
||||
ps.setInt(1, c.getInt());
|
||||
ps.setBytes(2, m.getBytes());
|
||||
int affected = ps.executeUpdate();
|
||||
if (affected < 0 || affected > 1) throw new DbStateException();
|
||||
ps.close();
|
||||
return affected == 1;
|
||||
} catch (SQLException e) {
|
||||
tryToClose(ps, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeOfferedMessages(Connection txn, ContactId c,
|
||||
Collection<MessageId> requested) throws DbException {
|
||||
PreparedStatement ps = null;
|
||||
try {
|
||||
String sql = "DELETE FROM offers"
|
||||
+ " WHERE contactId = ? AND messageId = ?";
|
||||
ps = txn.prepareStatement(sql);
|
||||
ps.setInt(1, c.getInt());
|
||||
for (MessageId m : requested) {
|
||||
ps.setBytes(2, m.getBytes());
|
||||
ps.addBatch();
|
||||
}
|
||||
int[] batchAffected = ps.executeBatch();
|
||||
if (batchAffected.length != requested.size())
|
||||
throw new DbStateException();
|
||||
for (int rows : batchAffected)
|
||||
if (rows != 1) throw new DbStateException();
|
||||
ps.close();
|
||||
} catch (SQLException e) {
|
||||
tryToClose(ps, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removePendingContact(Connection txn, PendingContactId p)
|
||||
throws DbException {
|
||||
|
||||
@@ -37,7 +37,6 @@ class Migration38_39 implements Migration<Connection> {
|
||||
s.execute("ALTER TABLE incomingKeys"
|
||||
+ " ALTER COLUMN contactId"
|
||||
+ " SET NOT NULL");
|
||||
s.close();
|
||||
} catch (SQLException e) {
|
||||
tryToClose(s, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
|
||||
@@ -36,7 +36,6 @@ class Migration39_40 implements Migration<Connection> {
|
||||
s.execute("ALTER TABLE statuses"
|
||||
+ " ALTER COLUMN eta"
|
||||
+ " SET NOT NULL");
|
||||
s.close();
|
||||
} catch (SQLException e) {
|
||||
tryToClose(s, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
|
||||
@@ -38,7 +38,6 @@ class Migration40_41 implements Migration<Connection> {
|
||||
s = txn.createStatement();
|
||||
s.execute("ALTER TABLE contacts"
|
||||
+ dbTypes.replaceTypes(" ADD alias _STRING"));
|
||||
s.close();
|
||||
} catch (SQLException e) {
|
||||
tryToClose(s, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
|
||||
@@ -89,7 +89,6 @@ class Migration41_42 implements Migration<Connection> {
|
||||
+ " FOREIGN KEY (keySetId)"
|
||||
+ " REFERENCES outgoingHandshakeKeys (keySetId)"
|
||||
+ " ON DELETE CASCADE)"));
|
||||
s.close();
|
||||
} catch (SQLException e) {
|
||||
tryToClose(s, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
|
||||
@@ -44,7 +44,6 @@ class Migration42_43 implements Migration<Connection> {
|
||||
+ " ADD COLUMN handshakePublicKey _BINARY"));
|
||||
s.execute("ALTER TABLE contacts"
|
||||
+ " DROP COLUMN active");
|
||||
s.close();
|
||||
} catch (SQLException e) {
|
||||
tryToClose(s, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
|
||||
@@ -50,7 +50,6 @@ class Migration43_44 implements Migration<Connection> {
|
||||
+ " ADD COLUMN rootKey _SECRET"));
|
||||
s.execute("ALTER TABLE outgoingKeys"
|
||||
+ " ADD COLUMN alice BOOLEAN");
|
||||
s.close();
|
||||
} catch (SQLException e) {
|
||||
tryToClose(s, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
|
||||
@@ -31,7 +31,6 @@ class Migration44_45 implements Migration<Connection> {
|
||||
try {
|
||||
s = txn.createStatement();
|
||||
s.execute("ALTER TABLE pendingContacts DROP COLUMN state");
|
||||
s.close();
|
||||
} catch (SQLException e) {
|
||||
tryToClose(s, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
|
||||
@@ -32,7 +32,6 @@ class Migration45_46 implements Migration<Connection> {
|
||||
s = txn.createStatement();
|
||||
s.execute("ALTER TABLE messages"
|
||||
+ " ADD COLUMN temporary BOOLEAN DEFAULT FALSE NOT NULL");
|
||||
s.close();
|
||||
} catch (SQLException e) {
|
||||
tryToClose(s, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
|
||||
@@ -39,7 +39,6 @@ class Migration46_47 implements Migration<Connection> {
|
||||
s.execute(dbTypes.replaceTypes("ALTER TABLE contacts"
|
||||
+ " ADD COLUMN syncVersions"
|
||||
+ " _BINARY DEFAULT '00' NOT NULL"));
|
||||
s.close();
|
||||
} catch (SQLException e) {
|
||||
tryToClose(s, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
package org.briarproject.bramble.db;
|
||||
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static java.lang.System.arraycopy;
|
||||
import static java.sql.Types.BINARY;
|
||||
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.sync.SyncConstants.MESSAGE_HEADER_LENGTH;
|
||||
import static org.briarproject.bramble.db.JdbcUtils.tryToClose;
|
||||
|
||||
class Migration47_48 implements Migration<Connection> {
|
||||
|
||||
private static final Logger LOG = getLogger(Migration47_48.class.getName());
|
||||
|
||||
private final DatabaseTypes dbTypes;
|
||||
|
||||
Migration47_48(DatabaseTypes dbTypes) {
|
||||
this.dbTypes = dbTypes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getStartVersion() {
|
||||
return 47;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getEndVersion() {
|
||||
return 48;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void migrate(Connection txn) throws DbException {
|
||||
Statement s = null;
|
||||
ResultSet rs = null;
|
||||
PreparedStatement ps = null;
|
||||
try {
|
||||
s = txn.createStatement();
|
||||
s.execute("ALTER TABLE messages"
|
||||
+ " ADD COLUMN deleted BOOLEAN DEFAULT FALSE NOT NULL");
|
||||
s.execute("UPDATE messages SET deleted = TRUE WHERE raw IS NULL");
|
||||
s.execute("ALTER TABLE messages"
|
||||
+ " ADD COLUMN blockCount INT DEFAULT 1 NOT NULL");
|
||||
s.execute(dbTypes.replaceTypes("CREATE TABLE blocks"
|
||||
+ " (messageId _HASH NOT NULL,"
|
||||
+ " blockNumber INT NOT NULL,"
|
||||
+ " blockLength INT NOT NULL," // Excludes block header
|
||||
+ " data BLOB," // Null if message has been deleted
|
||||
+ " PRIMARY KEY (messageId, blockNumber),"
|
||||
+ " FOREIGN KEY (messageId)"
|
||||
+ " REFERENCES messages (messageId)"
|
||||
+ " ON DELETE CASCADE)"));
|
||||
rs = s.executeQuery("SELECT messageId, length, raw FROM messages");
|
||||
ps = txn.prepareStatement("INSERT INTO blocks"
|
||||
+ " (messageId, blockNumber, blockLength, data)"
|
||||
+ " VALUES (?, 0, ?, ?)");
|
||||
int migrated = 0;
|
||||
while (rs.next()) {
|
||||
byte[] id = rs.getBytes(1);
|
||||
int length = rs.getInt(2);
|
||||
byte[] raw = rs.getBytes(3);
|
||||
ps.setBytes(1, id);
|
||||
ps.setInt(2, length - MESSAGE_HEADER_LENGTH);
|
||||
if (raw == null) {
|
||||
ps.setNull(3, BINARY);
|
||||
} else {
|
||||
byte[] data = new byte[raw.length - MESSAGE_HEADER_LENGTH];
|
||||
arraycopy(raw, MESSAGE_HEADER_LENGTH, data, 0, data.length);
|
||||
ps.setBytes(3, data);
|
||||
}
|
||||
if (ps.executeUpdate() != 1) throw new DbStateException();
|
||||
migrated++;
|
||||
}
|
||||
ps.close();
|
||||
rs.close();
|
||||
s.execute("ALTER TABLE messages DROP COLUMN raw");
|
||||
s.close();
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Migrated " + migrated + " messages");
|
||||
} catch (SQLException e) {
|
||||
tryToClose(ps, LOG, WARNING);
|
||||
tryToClose(rs, LOG, WARNING);
|
||||
tryToClose(s, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package org.briarproject.bramble.db;
|
||||
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static java.util.logging.Level.WARNING;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
import static org.briarproject.bramble.db.JdbcUtils.tryToClose;
|
||||
|
||||
class Migration48_49 implements Migration<Connection> {
|
||||
|
||||
private static final Logger LOG = getLogger(Migration48_49.class.getName());
|
||||
|
||||
@Override
|
||||
public int getStartVersion() {
|
||||
return 48;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getEndVersion() {
|
||||
return 49;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void migrate(Connection txn) throws DbException {
|
||||
Statement s = null;
|
||||
try {
|
||||
s = txn.createStatement();
|
||||
s.execute("DROP TABLE offers");
|
||||
s.close();
|
||||
} catch (SQLException e) {
|
||||
tryToClose(s, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package org.briarproject.bramble.keyagreement;
|
||||
|
||||
import org.briarproject.bramble.api.Pair;
|
||||
import org.briarproject.bramble.api.crypto.KeyAgreementCrypto;
|
||||
import org.briarproject.bramble.api.crypto.KeyPair;
|
||||
import org.briarproject.bramble.api.data.BdfList;
|
||||
@@ -9,8 +8,6 @@ import org.briarproject.bramble.api.keyagreement.KeyAgreementListener;
|
||||
import org.briarproject.bramble.api.keyagreement.Payload;
|
||||
import org.briarproject.bramble.api.keyagreement.TransportDescriptor;
|
||||
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.PluginManager;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
@@ -22,9 +19,7 @@ import org.briarproject.bramble.api.record.RecordWriterFactory;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
@@ -33,10 +28,8 @@ import java.util.logging.Logger;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
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.keyagreement.KeyAgreementConstants.CONNECTION_TIMEOUT;
|
||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||
|
||||
@@ -48,10 +41,7 @@ class KeyAgreementConnector {
|
||||
}
|
||||
|
||||
private static final Logger LOG =
|
||||
getLogger(KeyAgreementConnector.class.getName());
|
||||
|
||||
private static final List<TransportId> PREFERRED_TRANSPORTS =
|
||||
asList(BluetoothConstants.ID, LanTcpConstants.ID);
|
||||
Logger.getLogger(KeyAgreementConnector.class.getName());
|
||||
|
||||
private final Callbacks callbacks;
|
||||
private final KeyAgreementCrypto keyAgreementCrypto;
|
||||
@@ -115,35 +105,24 @@ class KeyAgreementConnector {
|
||||
this.alice = alice;
|
||||
aliceLatch.countDown();
|
||||
|
||||
// Start connecting over supported transports in order of preference
|
||||
// Start connecting over supported transports
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info("Starting outgoing BQP connections as "
|
||||
+ (alice ? "Alice" : "Bob"));
|
||||
}
|
||||
Map<TransportId, TransportDescriptor> descriptors = new HashMap<>();
|
||||
for (TransportDescriptor d : remotePayload.getTransportDescriptors()) {
|
||||
descriptors.put(d.getId(), d);
|
||||
}
|
||||
List<Pair<DuplexPlugin, BdfList>> transports = new ArrayList<>();
|
||||
for (TransportId id : PREFERRED_TRANSPORTS) {
|
||||
TransportDescriptor d = descriptors.get(id);
|
||||
Plugin p = pluginManager.getPlugin(id);
|
||||
if (d != null && p instanceof DuplexPlugin) {
|
||||
Plugin p = pluginManager.getPlugin(d.getId());
|
||||
if (p instanceof DuplexPlugin) {
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Connecting via " + id);
|
||||
transports.add(new Pair<>((DuplexPlugin) p, d.getDescriptor()));
|
||||
LOG.info("Connecting via " + d.getId());
|
||||
DuplexPlugin plugin = (DuplexPlugin) p;
|
||||
byte[] commitment = remotePayload.getCommitment();
|
||||
BdfList descriptor = d.getDescriptor();
|
||||
connectionChooser.submit(new ReadableTask(
|
||||
new ConnectorTask(plugin, commitment, descriptor)));
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: If we don't have any transports in common with the peer,
|
||||
// warn the user and give up (#1224)
|
||||
|
||||
if (!transports.isEmpty()) {
|
||||
byte[] commitment = remotePayload.getCommitment();
|
||||
connectionChooser.submit(new ReadableTask(new ConnectorTask(
|
||||
transports, commitment)));
|
||||
}
|
||||
|
||||
// Get chosen connection
|
||||
try {
|
||||
KeyAgreementConnection chosen =
|
||||
@@ -169,13 +148,15 @@ class KeyAgreementConnector {
|
||||
|
||||
private class ConnectorTask implements Callable<KeyAgreementConnection> {
|
||||
|
||||
private final List<Pair<DuplexPlugin, BdfList>> transports;
|
||||
private final byte[] commitment;
|
||||
private final BdfList descriptor;
|
||||
private final DuplexPlugin plugin;
|
||||
|
||||
private ConnectorTask(List<Pair<DuplexPlugin, BdfList>> transports,
|
||||
byte[] commitment) {
|
||||
this.transports = transports;
|
||||
private ConnectorTask(DuplexPlugin plugin, byte[] commitment,
|
||||
BdfList descriptor) {
|
||||
this.plugin = plugin;
|
||||
this.commitment = commitment;
|
||||
this.descriptor = descriptor;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@@ -183,18 +164,13 @@ class KeyAgreementConnector {
|
||||
public KeyAgreementConnection call() throws Exception {
|
||||
// Repeat attempts until we connect, get stopped, or get interrupted
|
||||
while (!stopped) {
|
||||
for (Pair<DuplexPlugin, BdfList> pair : transports) {
|
||||
if (stopped) return null;
|
||||
DuplexPlugin plugin = pair.getFirst();
|
||||
BdfList descriptor = pair.getSecond();
|
||||
DuplexTransportConnection conn =
|
||||
plugin.createKeyAgreementConnection(commitment,
|
||||
descriptor);
|
||||
if (conn != null) {
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info(plugin.getId() + ": Outgoing connection");
|
||||
return new KeyAgreementConnection(conn, plugin.getId());
|
||||
}
|
||||
DuplexTransportConnection conn =
|
||||
plugin.createKeyAgreementConnection(commitment,
|
||||
descriptor);
|
||||
if (conn != null) {
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info(plugin.getId() + ": Outgoing connection");
|
||||
return new KeyAgreementConnection(conn, plugin.getId());
|
||||
}
|
||||
// Wait 2s before retry (to circumvent transient failures)
|
||||
Thread.sleep(2000);
|
||||
|
||||
@@ -53,7 +53,6 @@ import static java.util.logging.Level.WARNING;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
import static org.briarproject.bramble.api.plugin.Plugin.PREF_PLUGIN_ENABLE;
|
||||
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.STARTING_STOPPING;
|
||||
import static org.briarproject.bramble.util.LogUtils.logDuration;
|
||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||
@@ -355,10 +354,6 @@ class PluginManagerImpl implements PluginManager, Service {
|
||||
} else if (oldState == ACTIVE) {
|
||||
eventBus.broadcast(new TransportInactiveEvent(id));
|
||||
}
|
||||
} else if (newState == DISABLED) {
|
||||
// Broadcast an event even though the state hasn't changed, as
|
||||
// the reasons for the plugin being disabled may have changed
|
||||
eventBus.broadcast(new TransportStateEvent(id, newState));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,9 @@ import org.briarproject.bramble.api.plugin.PluginException;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||
import org.briarproject.bramble.api.plugin.event.BluetoothEnabledEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.DisableBluetoothEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.EnableBluetoothEvent;
|
||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||
import org.briarproject.bramble.api.properties.event.RemoteTransportPropertiesUpdatedEvent;
|
||||
import org.briarproject.bramble.api.rendezvous.KeyMaterialSource;
|
||||
@@ -90,6 +93,12 @@ abstract class BluetoothPlugin<S, SS> implements DuplexPlugin, EventListener {
|
||||
|
||||
abstract boolean isAdapterEnabled();
|
||||
|
||||
abstract void enableAdapter();
|
||||
|
||||
abstract void disableAdapterIfEnabledByUs();
|
||||
|
||||
abstract void setEnabledByUs();
|
||||
|
||||
/**
|
||||
* Returns the local Bluetooth address, or null if no valid address can
|
||||
* be found.
|
||||
@@ -180,7 +189,10 @@ abstract class BluetoothPlugin<S, SS> implements DuplexPlugin, EventListener {
|
||||
throw new PluginException(e);
|
||||
}
|
||||
updateProperties();
|
||||
if (enabledByUser && isAdapterEnabled()) bind();
|
||||
if (enabledByUser) {
|
||||
if (isAdapterEnabled()) bind();
|
||||
else enableAdapter();
|
||||
}
|
||||
}
|
||||
|
||||
private void bind() {
|
||||
@@ -307,6 +319,7 @@ abstract class BluetoothPlugin<S, SS> implements DuplexPlugin, EventListener {
|
||||
public void stop() {
|
||||
SS ss = state.setStopped();
|
||||
tryToClose(ss);
|
||||
disableAdapterIfEnabledByUs();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -436,10 +449,8 @@ abstract class BluetoothPlugin<S, SS> implements DuplexPlugin, EventListener {
|
||||
String uuid = UUID.nameUUIDFromBytes(commitment).toString();
|
||||
DuplexTransportConnection conn;
|
||||
if (descriptor.size() == 1) {
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info("Discovering address for key agreement UUID " +
|
||||
uuid);
|
||||
}
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Discovering address for key agreement UUID " + uuid);
|
||||
conn = discoverAndConnect(uuid);
|
||||
} else {
|
||||
String address;
|
||||
@@ -479,7 +490,13 @@ abstract class BluetoothPlugin<S, SS> implements DuplexPlugin, EventListener {
|
||||
|
||||
@Override
|
||||
public void eventOccurred(Event e) {
|
||||
if (e instanceof SettingsUpdatedEvent) {
|
||||
if (e instanceof EnableBluetoothEvent) {
|
||||
ioExecutor.execute(this::enableAdapter);
|
||||
} else if (e instanceof DisableBluetoothEvent) {
|
||||
ioExecutor.execute(this::disableAdapterIfEnabledByUs);
|
||||
} else if (e instanceof BluetoothEnabledEvent) {
|
||||
setEnabledByUs();
|
||||
} else if (e instanceof SettingsUpdatedEvent) {
|
||||
SettingsUpdatedEvent s = (SettingsUpdatedEvent) e;
|
||||
if (s.getNamespace().equals(ID.getString()))
|
||||
ioExecutor.execute(() -> onSettingsUpdated(s.getSettings()));
|
||||
@@ -505,13 +522,11 @@ abstract class BluetoothPlugin<S, SS> implements DuplexPlugin, EventListener {
|
||||
if (ss != null) {
|
||||
LOG.info("Disabled by user, closing server socket");
|
||||
tryToClose(ss);
|
||||
disableAdapterIfEnabledByUs();
|
||||
} else if (s == INACTIVE) {
|
||||
if (isAdapterEnabled()) {
|
||||
LOG.info("Enabled by user, opening server socket");
|
||||
bind();
|
||||
} else {
|
||||
LOG.info("Enabled by user but adapter is disabled");
|
||||
}
|
||||
LOG.info("Enabled by user, opening server socket");
|
||||
if (isAdapterEnabled()) bind();
|
||||
else enableAdapter();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -132,7 +132,7 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
private final CircumventionProvider circumventionProvider;
|
||||
private final ResourceProvider resourceProvider;
|
||||
private final int maxLatency, maxIdleTime, socketTimeout;
|
||||
private final File torDirectory, geoIpFile, configFile;
|
||||
private final File torDirectory, torFile, geoIpFile, obfs4File, configFile;
|
||||
private final File doneFile, cookieFile;
|
||||
private final AtomicBoolean used = new AtomicBoolean(false);
|
||||
|
||||
@@ -181,7 +181,9 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
socketTimeout = Integer.MAX_VALUE;
|
||||
else socketTimeout = maxIdleTime * 2;
|
||||
this.torDirectory = torDirectory;
|
||||
torFile = new File(torDirectory, "tor");
|
||||
geoIpFile = new File(torDirectory, "geoip");
|
||||
obfs4File = new File(torDirectory, "obfs4proxy");
|
||||
configFile = new File(torDirectory, "torrc");
|
||||
doneFile = new File(torDirectory, "done");
|
||||
cookieFile = new File(torDirectory, ".tor/control_auth_cookie");
|
||||
@@ -190,14 +192,6 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
new PoliteExecutor("TorPlugin", ioExecutor, 1);
|
||||
}
|
||||
|
||||
protected File getTorExecutableFile() {
|
||||
return new File(torDirectory, "tor");
|
||||
}
|
||||
|
||||
protected File getObfs4ExecutableFile() {
|
||||
return new File(torDirectory, "obfs4proxy");
|
||||
}
|
||||
|
||||
@Override
|
||||
public TransportId getId() {
|
||||
return TorConstants.ID;
|
||||
@@ -230,7 +224,6 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
LOG.warning("Old auth cookie not deleted");
|
||||
// Start a new Tor process
|
||||
LOG.info("Starting Tor");
|
||||
File torFile = getTorExecutableFile();
|
||||
String torPath = torFile.getAbsolutePath();
|
||||
String configPath = configFile.getAbsolutePath();
|
||||
String pid = String.valueOf(getProcessId());
|
||||
@@ -329,43 +322,44 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
}
|
||||
|
||||
private void installAssets() throws PluginException {
|
||||
InputStream in = null;
|
||||
OutputStream out = null;
|
||||
try {
|
||||
// The done file may already exist from a previous installation
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
doneFile.delete();
|
||||
installTorExecutable();
|
||||
installObfs4Executable();
|
||||
extract(getGeoIpInputStream(), geoIpFile);
|
||||
extract(getConfigInputStream(), configFile);
|
||||
// Unzip the Tor binary to the filesystem
|
||||
in = getTorInputStream();
|
||||
out = new FileOutputStream(torFile);
|
||||
copyAndClose(in, out);
|
||||
// Make the Tor binary executable
|
||||
if (!torFile.setExecutable(true, true)) throw new IOException();
|
||||
// Unzip the GeoIP database to the filesystem
|
||||
in = getGeoIpInputStream();
|
||||
out = new FileOutputStream(geoIpFile);
|
||||
copyAndClose(in, out);
|
||||
// Unzip the Obfs4 proxy to the filesystem
|
||||
in = getObfs4InputStream();
|
||||
out = new FileOutputStream(obfs4File);
|
||||
copyAndClose(in, out);
|
||||
// Make the Obfs4 proxy executable
|
||||
if (!obfs4File.setExecutable(true, true)) throw new IOException();
|
||||
// Copy the config file to the filesystem
|
||||
in = getConfigInputStream();
|
||||
out = new FileOutputStream(configFile);
|
||||
copyAndClose(in, out);
|
||||
if (!doneFile.createNewFile())
|
||||
LOG.warning("Failed to create done file");
|
||||
} catch (IOException e) {
|
||||
tryToClose(in, LOG, WARNING);
|
||||
tryToClose(out, LOG, WARNING);
|
||||
throw new PluginException(e);
|
||||
}
|
||||
}
|
||||
|
||||
protected void extract(InputStream in, File dest) throws IOException {
|
||||
OutputStream out = new FileOutputStream(dest);
|
||||
copyAndClose(in, out);
|
||||
}
|
||||
|
||||
protected void installTorExecutable() throws IOException {
|
||||
private InputStream getTorInputStream() throws IOException {
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Installing Tor binary for " + architecture);
|
||||
File torFile = getTorExecutableFile();
|
||||
extract(getTorInputStream(), torFile);
|
||||
if (!torFile.setExecutable(true, true)) throw new IOException();
|
||||
}
|
||||
|
||||
protected void installObfs4Executable() throws IOException {
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Installing obfs4proxy binary for " + architecture);
|
||||
File obfs4File = getObfs4ExecutableFile();
|
||||
extract(getObfs4InputStream(), obfs4File);
|
||||
if (!obfs4File.setExecutable(true, true)) throw new IOException();
|
||||
}
|
||||
|
||||
private InputStream getTorInputStream() throws IOException {
|
||||
InputStream in = resourceProvider
|
||||
.getResourceInputStream("tor_" + architecture, ".zip");
|
||||
ZipInputStream zin = new ZipInputStream(in);
|
||||
@@ -382,6 +376,8 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
}
|
||||
|
||||
private InputStream getObfs4InputStream() throws IOException {
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Installing obfs4proxy binary for " + architecture);
|
||||
InputStream in = resourceProvider
|
||||
.getResourceInputStream("obfs4proxy_" + architecture, ".zip");
|
||||
ZipInputStream zin = new ZipInputStream(in);
|
||||
@@ -573,7 +569,6 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
if (enable) {
|
||||
Collection<String> conf = new ArrayList<>();
|
||||
conf.add("UseBridges 1");
|
||||
File obfs4File = getObfs4ExecutableFile();
|
||||
if (needsMeek) {
|
||||
conf.add("ClientTransportPlugin meek_lite exec " +
|
||||
obfs4File.getAbsolutePath());
|
||||
|
||||
@@ -199,7 +199,7 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
|
||||
Map<TransportId, LatestUpdate> latest = findLatestLocal(txn);
|
||||
// Retrieve and parse the latest local properties
|
||||
for (Entry<TransportId, LatestUpdate> e : latest.entrySet()) {
|
||||
BdfList message = clientHelper.getSmallMessageAsList(txn,
|
||||
BdfList message = clientHelper.getMessageAsList(txn,
|
||||
e.getValue().messageId);
|
||||
local.put(e.getKey(), parseProperties(message));
|
||||
}
|
||||
@@ -220,7 +220,7 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
|
||||
true);
|
||||
if (latest != null) {
|
||||
// Retrieve and parse the latest local properties
|
||||
BdfList message = clientHelper.getSmallMessageAsList(txn,
|
||||
BdfList message = clientHelper.getMessageAsList(txn,
|
||||
latest.messageId);
|
||||
p = parseProperties(message);
|
||||
}
|
||||
@@ -250,7 +250,7 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
|
||||
if (latest == null) {
|
||||
local = new TransportProperties();
|
||||
} else {
|
||||
BdfList message = clientHelper.getSmallMessageAsList(txn,
|
||||
BdfList message = clientHelper.getMessageAsList(txn,
|
||||
latest.messageId);
|
||||
local = parseProperties(message);
|
||||
}
|
||||
@@ -271,8 +271,8 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
|
||||
remote = new TransportProperties();
|
||||
} else {
|
||||
// Retrieve and parse the latest remote properties
|
||||
BdfList message = clientHelper.getSmallMessageAsList(txn,
|
||||
latest.messageId);
|
||||
BdfList message =
|
||||
clientHelper.getMessageAsList(txn, latest.messageId);
|
||||
remote = parseProperties(message);
|
||||
}
|
||||
// Merge in any discovered properties
|
||||
@@ -315,7 +315,7 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
|
||||
}
|
||||
changed = true;
|
||||
} else {
|
||||
BdfList message = clientHelper.getSmallMessageAsList(txn,
|
||||
BdfList message = clientHelper.getMessageAsList(txn,
|
||||
latest.messageId);
|
||||
TransportProperties old = parseProperties(message);
|
||||
merged = new TransportProperties(old);
|
||||
|
||||
@@ -42,7 +42,6 @@ import org.briarproject.bramble.api.rendezvous.event.RendezvousConnectionOpenedE
|
||||
import org.briarproject.bramble.api.rendezvous.event.RendezvousPollEvent;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
import org.briarproject.bramble.api.system.TaskScheduler;
|
||||
import org.briarproject.bramble.api.system.TaskScheduler.Cancellable;
|
||||
import org.briarproject.bramble.api.system.Wakeful;
|
||||
|
||||
import java.security.GeneralSecurityException;
|
||||
@@ -69,7 +68,6 @@ import static org.briarproject.bramble.api.contact.PendingContactState.ADDING_CO
|
||||
import static org.briarproject.bramble.api.contact.PendingContactState.FAILED;
|
||||
import static org.briarproject.bramble.api.contact.PendingContactState.OFFLINE;
|
||||
import static org.briarproject.bramble.api.contact.PendingContactState.WAITING_FOR_CONNECTION;
|
||||
import static org.briarproject.bramble.api.nullsafety.NullSafety.requireNonNull;
|
||||
import static org.briarproject.bramble.api.nullsafety.NullSafety.requireNull;
|
||||
import static org.briarproject.bramble.rendezvous.RendezvousConstants.POLLING_INTERVAL_MS;
|
||||
import static org.briarproject.bramble.rendezvous.RendezvousConstants.RENDEZVOUS_TIMEOUT_MS;
|
||||
@@ -104,8 +102,6 @@ class RendezvousPollerImpl implements RendezvousPoller, Service, EventListener {
|
||||
new HashMap<>();
|
||||
@Nullable
|
||||
private KeyPair handshakeKeyPair = null;
|
||||
@Nullable
|
||||
private Cancellable pollTask = null;
|
||||
|
||||
@Inject
|
||||
RendezvousPollerImpl(@IoExecutor Executor ioExecutor,
|
||||
@@ -148,6 +144,8 @@ class RendezvousPollerImpl implements RendezvousPoller, Service, EventListener {
|
||||
} catch (DbException e) {
|
||||
throw new ServiceException(e);
|
||||
}
|
||||
scheduler.scheduleWithFixedDelay(this::poll, worker,
|
||||
POLLING_INTERVAL_MS, POLLING_INTERVAL_MS, MILLISECONDS);
|
||||
}
|
||||
|
||||
@EventExecutor
|
||||
@@ -188,12 +186,6 @@ class RendezvousPollerImpl implements RendezvousPoller, Service, EventListener {
|
||||
}
|
||||
if (cs.numEndpoints == 0) broadcastState(p.getId(), OFFLINE);
|
||||
else broadcastState(p.getId(), WAITING_FOR_CONNECTION);
|
||||
if (cryptoStates.size() == 1) {
|
||||
LOG.info("Starting poller");
|
||||
requireNull(pollTask);
|
||||
pollTask = scheduler.scheduleWithFixedDelay(this::poll, worker,
|
||||
POLLING_INTERVAL_MS, POLLING_INTERVAL_MS, MILLISECONDS);
|
||||
}
|
||||
} catch (DbException | GeneralSecurityException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
}
|
||||
@@ -216,7 +208,6 @@ class RendezvousPollerImpl implements RendezvousPoller, Service, EventListener {
|
||||
// Worker
|
||||
@Wakeful
|
||||
private void poll() {
|
||||
LOG.info("Polling");
|
||||
removeExpiredPendingContacts();
|
||||
for (PluginState ps : pluginStates.values()) poll(ps);
|
||||
}
|
||||
@@ -243,11 +234,6 @@ class RendezvousPollerImpl implements RendezvousPoller, Service, EventListener {
|
||||
RendezvousEndpoint endpoint = ps.endpoints.remove(p);
|
||||
if (endpoint != null) tryToClose(endpoint, LOG, INFO);
|
||||
}
|
||||
if (cryptoStates.isEmpty()) {
|
||||
LOG.info("Stopping poller");
|
||||
requireNonNull(pollTask).cancel();
|
||||
pollTask = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Worker
|
||||
|
||||
@@ -15,7 +15,6 @@ import org.briarproject.bramble.api.plugin.TransportId;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportInactiveEvent;
|
||||
import org.briarproject.bramble.api.sync.Ack;
|
||||
import org.briarproject.bramble.api.sync.Message;
|
||||
import org.briarproject.bramble.api.sync.MessageId;
|
||||
import org.briarproject.bramble.api.sync.Offer;
|
||||
import org.briarproject.bramble.api.sync.Priority;
|
||||
import org.briarproject.bramble.api.sync.Request;
|
||||
@@ -26,8 +25,8 @@ import org.briarproject.bramble.api.sync.event.CloseSyncConnectionsEvent;
|
||||
import org.briarproject.bramble.api.sync.event.GroupVisibilityUpdatedEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessageRequestedEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessageSharedEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessagesToAckEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessagesToRequestEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessageToAckEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessageToRequestEvent;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
import org.briarproject.bramble.api.transport.StreamWriter;
|
||||
|
||||
@@ -88,6 +87,8 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
|
||||
private final AtomicBoolean generateAckQueued = new AtomicBoolean(false);
|
||||
private final AtomicBoolean generateBatchQueued = new AtomicBoolean(false);
|
||||
private final AtomicBoolean generateOfferQueued = new AtomicBoolean(false);
|
||||
private final AtomicBoolean generateRequestQueued =
|
||||
new AtomicBoolean(false);
|
||||
private final AtomicLong nextSendTime = new AtomicLong(Long.MAX_VALUE);
|
||||
|
||||
private volatile boolean interrupted = false;
|
||||
@@ -124,6 +125,7 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
|
||||
generateAck();
|
||||
generateBatch();
|
||||
generateOffer();
|
||||
generateRequest();
|
||||
long now = clock.currentTimeMillis();
|
||||
long nextKeepalive = now + maxIdleTime;
|
||||
boolean dataToFlush = true;
|
||||
@@ -195,6 +197,11 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
|
||||
dbExecutor.execute(new GenerateOffer());
|
||||
}
|
||||
|
||||
private void generateRequest() {
|
||||
if (generateRequestQueued.compareAndSet(false, true))
|
||||
dbExecutor.execute(new GenerateRequest());
|
||||
}
|
||||
|
||||
private void setNextSendTime(long time) {
|
||||
long old = nextSendTime.getAndSet(time);
|
||||
if (time < old) writerTasks.add(NEXT_SEND_TIME_DECREASED);
|
||||
@@ -220,16 +227,12 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
|
||||
} else if (e instanceof MessageRequestedEvent) {
|
||||
if (((MessageRequestedEvent) e).getContactId().equals(contactId))
|
||||
generateBatch();
|
||||
} else if (e instanceof MessagesToAckEvent) {
|
||||
if (((MessagesToAckEvent) e).getContactId().equals(contactId))
|
||||
} else if (e instanceof MessageToAckEvent) {
|
||||
if (((MessageToAckEvent) e).getContactId().equals(contactId))
|
||||
generateAck();
|
||||
} else if (e instanceof MessagesToRequestEvent) {
|
||||
MessagesToRequestEvent m = (MessagesToRequestEvent) e;
|
||||
if (m.getContactId().equals(contactId)) {
|
||||
Collection<MessageId> ids = m.consumeIds();
|
||||
if (ids != null)
|
||||
writerTasks.add(new WriteRequest(new Request(ids)));
|
||||
}
|
||||
} else if (e instanceof MessageToRequestEvent) {
|
||||
if (((MessageToRequestEvent) e).getContactId().equals(contactId))
|
||||
generateRequest();
|
||||
} else if (e instanceof LifecycleEvent) {
|
||||
LifecycleEvent l = (LifecycleEvent) e;
|
||||
if (l.getLifecycleState() == STOPPING) interrupt();
|
||||
@@ -337,7 +340,7 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
|
||||
try {
|
||||
Offer o = db.transactionWithNullableResult(false, txn -> {
|
||||
Offer offer = db.generateOffer(txn, contactId,
|
||||
MAX_MESSAGE_IDS, maxLatency, true);
|
||||
MAX_MESSAGE_IDS, maxLatency);
|
||||
setNextSendTime(db.getNextSendTime(txn, contactId));
|
||||
return offer;
|
||||
});
|
||||
@@ -369,6 +372,27 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
|
||||
}
|
||||
}
|
||||
|
||||
private class GenerateRequest implements Runnable {
|
||||
|
||||
@DatabaseExecutor
|
||||
@Override
|
||||
public void run() {
|
||||
if (interrupted) return;
|
||||
if (!generateRequestQueued.getAndSet(false))
|
||||
throw new AssertionError();
|
||||
try {
|
||||
Request r = db.transactionWithNullableResult(false, txn ->
|
||||
db.generateRequest(txn, contactId, MAX_MESSAGE_IDS));
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Generated request: " + (r != null));
|
||||
if (r != null) writerTasks.add(new WriteRequest(r));
|
||||
} catch (DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class WriteRequest implements ThrowingRunnable<IOException> {
|
||||
|
||||
private final Request request;
|
||||
@@ -383,6 +407,7 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
|
||||
if (interrupted) return;
|
||||
recordWriter.writeRequest(request);
|
||||
LOG.info("Sent request");
|
||||
generateRequest();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,8 +186,7 @@ class SimplexOutgoingSession implements SyncSession, EventListener {
|
||||
Collection<Message> b =
|
||||
db.transactionWithNullableResult(false, txn ->
|
||||
db.generateBatch(txn, contactId,
|
||||
MAX_RECORD_PAYLOAD_BYTES, maxLatency,
|
||||
true));
|
||||
MAX_RECORD_PAYLOAD_BYTES, maxLatency));
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Generated batch: " + (b != null));
|
||||
if (b == null) decrementOutstandingQueries();
|
||||
|
||||
@@ -120,7 +120,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
|
||||
Pair<Message, Group> mg = db.transactionWithResult(true, txn -> {
|
||||
MessageId id = unvalidated.poll();
|
||||
if (id == null) throw new AssertionError();
|
||||
Message m = db.getSmallMessage(txn, id);
|
||||
Message m = db.getMessage(txn, id);
|
||||
Group g = db.getGroup(txn, m.getGroupId());
|
||||
return new Pair<>(m, g);
|
||||
});
|
||||
@@ -179,7 +179,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
|
||||
invalidateMessage(txn, id);
|
||||
addDependentsToInvalidate(txn, id, invalidate);
|
||||
} else if (allDelivered) {
|
||||
Message m = db.getSmallMessage(txn, id);
|
||||
Message m = db.getMessage(txn, id);
|
||||
Group g = db.getGroup(txn, m.getGroupId());
|
||||
ClientId c = g.getClientId();
|
||||
int majorVersion = g.getMajorVersion();
|
||||
|
||||
@@ -298,8 +298,7 @@ class ClientVersioningManagerImpl implements ClientVersioningManager,
|
||||
private List<ClientVersion> loadClientVersions(Transaction txn,
|
||||
MessageId m) throws DbException {
|
||||
try {
|
||||
return parseClientVersions(
|
||||
clientHelper.getSmallMessageAsList(txn, m));
|
||||
return parseClientVersions(clientHelper.getMessageAsList(txn, m));
|
||||
} catch (FormatException e) {
|
||||
throw new DbException(e);
|
||||
}
|
||||
@@ -392,7 +391,7 @@ class ClientVersioningManagerImpl implements ClientVersioningManager,
|
||||
|
||||
private Update loadUpdate(Transaction txn, MessageId m) throws DbException {
|
||||
try {
|
||||
return parseUpdate(clientHelper.getSmallMessageAsList(txn, m));
|
||||
return parseUpdate(clientHelper.getMessageAsList(txn, m));
|
||||
} catch (FormatException e) {
|
||||
throw new DbException(e);
|
||||
}
|
||||
|
||||
@@ -134,7 +134,7 @@ public class AccountManagerImplTest extends BrambleMockTestCase {
|
||||
keyStrengthener);
|
||||
will(returnValue(key.getBytes()));
|
||||
oneOf(crypto).isEncryptedWithStrengthenedKey(encryptedKey);
|
||||
will(returnValue(true));
|
||||
will(returnValue(false));
|
||||
}});
|
||||
|
||||
storeDatabaseKey(keyFile, encryptedKeyHex);
|
||||
@@ -160,9 +160,8 @@ public class AccountManagerImplTest extends BrambleMockTestCase {
|
||||
keyStrengthener);
|
||||
will(returnValue(key.getBytes()));
|
||||
oneOf(crypto).isEncryptedWithStrengthenedKey(encryptedKey);
|
||||
will(returnValue(false));
|
||||
oneOf(crypto).encryptWithPassword(key.getBytes(), password,
|
||||
keyStrengthener);
|
||||
will(returnValue(true));
|
||||
oneOf(crypto).encryptWithPassword(key.getBytes(), password, null);
|
||||
will(returnValue(newEncryptedKey));
|
||||
}});
|
||||
|
||||
@@ -262,8 +261,7 @@ public class AccountManagerImplTest extends BrambleMockTestCase {
|
||||
oneOf(identityManager).registerIdentity(identity);
|
||||
oneOf(crypto).generateSecretKey();
|
||||
will(returnValue(key));
|
||||
oneOf(crypto).encryptWithPassword(key.getBytes(), password,
|
||||
keyStrengthener);
|
||||
oneOf(crypto).encryptWithPassword(key.getBytes(), password, null);
|
||||
will(returnValue(encryptedKey));
|
||||
}});
|
||||
|
||||
@@ -323,10 +321,8 @@ public class AccountManagerImplTest extends BrambleMockTestCase {
|
||||
oneOf(crypto).decryptWithPassword(encryptedKey, password,
|
||||
keyStrengthener);
|
||||
will(returnValue(key.getBytes()));
|
||||
oneOf(crypto).isEncryptedWithStrengthenedKey(encryptedKey);
|
||||
will(returnValue(true));
|
||||
oneOf(crypto).encryptWithPassword(key.getBytes(), newPassword,
|
||||
keyStrengthener);
|
||||
null);
|
||||
will(returnValue(newEncryptedKey));
|
||||
}});
|
||||
|
||||
|
||||
@@ -122,11 +122,11 @@ public class ClientHelperImplTest extends BrambleTestCase {
|
||||
expectToList(true);
|
||||
context.checking(new DbExpectations() {{
|
||||
oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
|
||||
oneOf(db).getSmallMessage(txn, messageId);
|
||||
oneOf(db).getMessage(txn, messageId);
|
||||
will(returnValue(message));
|
||||
}});
|
||||
|
||||
clientHelper.getSmallMessageAsList(messageId);
|
||||
clientHelper.getMessageAsList(messageId);
|
||||
context.assertIsSatisfied();
|
||||
}
|
||||
|
||||
|
||||
@@ -44,10 +44,10 @@ import org.briarproject.bramble.api.sync.event.MessageAddedEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessageRequestedEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessageSharedEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessageStateChangedEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessageToAckEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessageToRequestEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessagesAckedEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessagesSentEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessagesToAckEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessagesToRequestEvent;
|
||||
import org.briarproject.bramble.api.transport.IncomingKeys;
|
||||
import org.briarproject.bramble.api.transport.KeySetId;
|
||||
import org.briarproject.bramble.api.transport.OutgoingKeys;
|
||||
@@ -76,6 +76,7 @@ import static org.briarproject.bramble.api.sync.SyncConstants.MAX_MESSAGE_LENGTH
|
||||
import static org.briarproject.bramble.api.sync.validation.MessageState.DELIVERED;
|
||||
import static org.briarproject.bramble.api.sync.validation.MessageState.UNKNOWN;
|
||||
import static org.briarproject.bramble.api.transport.TransportConstants.REORDERING_WINDOW_SIZE;
|
||||
import static org.briarproject.bramble.db.DatabaseConstants.MAX_OFFERED_MESSAGES;
|
||||
import static org.briarproject.bramble.test.TestUtils.getAgreementPrivateKey;
|
||||
import static org.briarproject.bramble.test.TestUtils.getAgreementPublicKey;
|
||||
import static org.briarproject.bramble.test.TestUtils.getAuthor;
|
||||
@@ -294,11 +295,11 @@ public class DatabaseComponentImplTest extends BrambleMockTestCase {
|
||||
throws Exception {
|
||||
context.checking(new Expectations() {{
|
||||
// Check whether the contact is in the DB (which it's not)
|
||||
exactly(17).of(database).startTransaction();
|
||||
exactly(18).of(database).startTransaction();
|
||||
will(returnValue(txn));
|
||||
exactly(17).of(database).containsContact(txn, contactId);
|
||||
exactly(18).of(database).containsContact(txn, contactId);
|
||||
will(returnValue(false));
|
||||
exactly(17).of(database).abortTransaction(txn);
|
||||
exactly(18).of(database).abortTransaction(txn);
|
||||
}});
|
||||
DatabaseComponent db = createDatabaseComponent(database, eventBus,
|
||||
eventExecutor, shutdownManager);
|
||||
@@ -322,7 +323,7 @@ public class DatabaseComponentImplTest extends BrambleMockTestCase {
|
||||
|
||||
try {
|
||||
db.transaction(false, transaction ->
|
||||
db.generateBatch(transaction, contactId, 123, 456, true));
|
||||
db.generateBatch(transaction, contactId, 123, 456));
|
||||
fail();
|
||||
} catch (NoSuchContactException expected) {
|
||||
// Expected
|
||||
@@ -330,7 +331,15 @@ public class DatabaseComponentImplTest extends BrambleMockTestCase {
|
||||
|
||||
try {
|
||||
db.transaction(false, transaction ->
|
||||
db.generateOffer(transaction, contactId, 123, 456, true));
|
||||
db.generateOffer(transaction, contactId, 123, 456));
|
||||
fail();
|
||||
} catch (NoSuchContactException expected) {
|
||||
// Expected
|
||||
}
|
||||
|
||||
try {
|
||||
db.transaction(false, transaction ->
|
||||
db.generateRequest(transaction, contactId, 123));
|
||||
fail();
|
||||
} catch (NoSuchContactException expected) {
|
||||
// Expected
|
||||
@@ -615,7 +624,7 @@ public class DatabaseComponentImplTest extends BrambleMockTestCase {
|
||||
|
||||
try {
|
||||
db.transaction(false, transaction ->
|
||||
db.getSmallMessage(transaction, messageId));
|
||||
db.getMessage(transaction, messageId));
|
||||
fail();
|
||||
} catch (NoSuchMessageException expected) {
|
||||
// Expected
|
||||
@@ -856,14 +865,14 @@ public class DatabaseComponentImplTest extends BrambleMockTestCase {
|
||||
will(returnValue(txn));
|
||||
oneOf(database).containsContact(txn, contactId);
|
||||
will(returnValue(true));
|
||||
oneOf(database).getSmallMessagesToSend(txn, contactId,
|
||||
oneOf(database).getMessagesToSend(txn, contactId,
|
||||
MAX_MESSAGE_LENGTH * 2, maxLatency);
|
||||
will(returnValue(ids));
|
||||
oneOf(database).getSmallMessage(txn, messageId);
|
||||
oneOf(database).getMessage(txn, messageId);
|
||||
will(returnValue(message));
|
||||
oneOf(database).updateExpiryTimeAndEta(txn, contactId, messageId,
|
||||
maxLatency);
|
||||
oneOf(database).getSmallMessage(txn, messageId1);
|
||||
oneOf(database).getMessage(txn, messageId1);
|
||||
will(returnValue(message1));
|
||||
oneOf(database).updateExpiryTimeAndEta(txn, contactId, messageId1,
|
||||
maxLatency);
|
||||
@@ -876,7 +885,7 @@ public class DatabaseComponentImplTest extends BrambleMockTestCase {
|
||||
|
||||
db.transaction(false, transaction ->
|
||||
assertEquals(messages, db.generateBatch(transaction, contactId,
|
||||
MAX_MESSAGE_LENGTH * 2, maxLatency, true)));
|
||||
MAX_MESSAGE_LENGTH * 2, maxLatency)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -888,8 +897,7 @@ public class DatabaseComponentImplTest extends BrambleMockTestCase {
|
||||
will(returnValue(txn));
|
||||
oneOf(database).containsContact(txn, contactId);
|
||||
will(returnValue(true));
|
||||
oneOf(database).getSmallMessagesToOffer(txn, contactId, 123,
|
||||
maxLatency);
|
||||
oneOf(database).getMessagesToOffer(txn, contactId, 123, maxLatency);
|
||||
will(returnValue(ids));
|
||||
oneOf(database).updateExpiryTimeAndEta(txn, contactId, messageId,
|
||||
maxLatency);
|
||||
@@ -901,13 +909,36 @@ public class DatabaseComponentImplTest extends BrambleMockTestCase {
|
||||
eventExecutor, shutdownManager);
|
||||
|
||||
db.transaction(false, transaction -> {
|
||||
Offer o = db.generateOffer(transaction, contactId, 123, maxLatency,
|
||||
true);
|
||||
Offer o = db.generateOffer(transaction, contactId, 123, maxLatency);
|
||||
assertNotNull(o);
|
||||
assertEquals(ids, o.getMessageIds());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenerateRequest() throws Exception {
|
||||
MessageId messageId1 = new MessageId(getRandomId());
|
||||
Collection<MessageId> ids = asList(messageId, messageId1);
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(database).startTransaction();
|
||||
will(returnValue(txn));
|
||||
oneOf(database).containsContact(txn, contactId);
|
||||
will(returnValue(true));
|
||||
oneOf(database).getMessagesToRequest(txn, contactId, 123);
|
||||
will(returnValue(ids));
|
||||
oneOf(database).removeOfferedMessages(txn, contactId, ids);
|
||||
oneOf(database).commitTransaction(txn);
|
||||
}});
|
||||
DatabaseComponent db = createDatabaseComponent(database, eventBus,
|
||||
eventExecutor, shutdownManager);
|
||||
|
||||
db.transaction(false, transaction -> {
|
||||
Request r = db.generateRequest(transaction, contactId, 123);
|
||||
assertNotNull(r);
|
||||
assertEquals(ids, r.getMessageIds());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenerateRequestedBatch() throws Exception {
|
||||
Collection<MessageId> ids = asList(messageId, messageId1);
|
||||
@@ -920,11 +951,11 @@ public class DatabaseComponentImplTest extends BrambleMockTestCase {
|
||||
oneOf(database).getRequestedMessagesToSend(txn, contactId,
|
||||
MAX_MESSAGE_LENGTH * 2, maxLatency);
|
||||
will(returnValue(ids));
|
||||
oneOf(database).getSmallMessage(txn, messageId);
|
||||
oneOf(database).getMessage(txn, messageId);
|
||||
will(returnValue(message));
|
||||
oneOf(database).updateExpiryTimeAndEta(txn, contactId, messageId,
|
||||
maxLatency);
|
||||
oneOf(database).getSmallMessage(txn, messageId1);
|
||||
oneOf(database).getMessage(txn, messageId1);
|
||||
will(returnValue(message1));
|
||||
oneOf(database).updateExpiryTimeAndEta(txn, contactId, messageId1,
|
||||
maxLatency);
|
||||
@@ -987,10 +1018,10 @@ public class DatabaseComponentImplTest extends BrambleMockTestCase {
|
||||
oneOf(database).raiseAckFlag(txn, contactId, messageId);
|
||||
oneOf(database).commitTransaction(txn);
|
||||
// First time: the message was received and added
|
||||
oneOf(eventBus).broadcast(with(any(MessagesToAckEvent.class)));
|
||||
oneOf(eventBus).broadcast(with(any(MessageToAckEvent.class)));
|
||||
oneOf(eventBus).broadcast(with(any(MessageAddedEvent.class)));
|
||||
// Second time: the message needs to be acked
|
||||
oneOf(eventBus).broadcast(with(any(MessagesToAckEvent.class)));
|
||||
oneOf(eventBus).broadcast(with(any(MessageToAckEvent.class)));
|
||||
}});
|
||||
DatabaseComponent db = createDatabaseComponent(database, eventBus,
|
||||
eventExecutor, shutdownManager);
|
||||
@@ -1018,7 +1049,7 @@ public class DatabaseComponentImplTest extends BrambleMockTestCase {
|
||||
oneOf(database).raiseAckFlag(txn, contactId, messageId);
|
||||
oneOf(database).commitTransaction(txn);
|
||||
// The message was received but not added
|
||||
oneOf(eventBus).broadcast(with(any(MessagesToAckEvent.class)));
|
||||
oneOf(eventBus).broadcast(with(any(MessageToAckEvent.class)));
|
||||
}});
|
||||
DatabaseComponent db = createDatabaseComponent(database, eventBus,
|
||||
eventExecutor, shutdownManager);
|
||||
@@ -1049,15 +1080,19 @@ public class DatabaseComponentImplTest extends BrambleMockTestCase {
|
||||
public void testReceiveOffer() throws Exception {
|
||||
MessageId messageId1 = new MessageId(getRandomId());
|
||||
MessageId messageId2 = new MessageId(getRandomId());
|
||||
|
||||
MessageId messageId3 = new MessageId(getRandomId());
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(database).startTransaction();
|
||||
will(returnValue(txn));
|
||||
oneOf(database).containsContact(txn, contactId);
|
||||
will(returnValue(true));
|
||||
// There's room for two more offered messages
|
||||
oneOf(database).countOfferedMessages(txn, contactId);
|
||||
will(returnValue(MAX_OFFERED_MESSAGES - 2));
|
||||
// The first message isn't visible - request it
|
||||
oneOf(database).containsVisibleMessage(txn, contactId, messageId);
|
||||
will(returnValue(false));
|
||||
oneOf(database).addOfferedMessage(txn, contactId, messageId);
|
||||
// The second message is visible - ack it
|
||||
oneOf(database).containsVisibleMessage(txn, contactId, messageId1);
|
||||
will(returnValue(true));
|
||||
@@ -1066,14 +1101,19 @@ public class DatabaseComponentImplTest extends BrambleMockTestCase {
|
||||
// The third message isn't visible - request it
|
||||
oneOf(database).containsVisibleMessage(txn, contactId, messageId2);
|
||||
will(returnValue(false));
|
||||
oneOf(database).addOfferedMessage(txn, contactId, messageId2);
|
||||
// The fourth message isn't visible, but there's no room to store it
|
||||
oneOf(database).containsVisibleMessage(txn, contactId, messageId3);
|
||||
will(returnValue(false));
|
||||
oneOf(database).commitTransaction(txn);
|
||||
oneOf(eventBus).broadcast(with(any(MessagesToAckEvent.class)));
|
||||
oneOf(eventBus).broadcast(with(any(MessagesToRequestEvent.class)));
|
||||
oneOf(eventBus).broadcast(with(any(MessageToAckEvent.class)));
|
||||
oneOf(eventBus).broadcast(with(any(MessageToRequestEvent.class)));
|
||||
}});
|
||||
DatabaseComponent db = createDatabaseComponent(database, eventBus,
|
||||
eventExecutor, shutdownManager);
|
||||
|
||||
Offer o = new Offer(asList(messageId, messageId1, messageId2));
|
||||
Offer o = new Offer(asList(messageId, messageId1,
|
||||
messageId2, messageId3));
|
||||
db.transaction(false, transaction ->
|
||||
db.receiveOffer(transaction, contactId, o));
|
||||
}
|
||||
|
||||
@@ -3,9 +3,11 @@ package org.briarproject.bramble.db;
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.db.DatabaseConfig;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
import org.briarproject.bramble.api.sync.MessageFactory;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
import org.briarproject.bramble.system.SystemClock;
|
||||
import org.briarproject.bramble.test.TestDatabaseConfig;
|
||||
import org.briarproject.bramble.test.TestMessageFactory;
|
||||
import org.briarproject.bramble.test.UTest;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -30,7 +32,8 @@ public abstract class DatabasePerformanceComparisonTest
|
||||
private SecretKey databaseKey = getSecretKey();
|
||||
|
||||
abstract Database<Connection> createDatabase(boolean conditionA,
|
||||
DatabaseConfig databaseConfig, Clock clock);
|
||||
DatabaseConfig databaseConfig, MessageFactory messageFactory,
|
||||
Clock clock);
|
||||
|
||||
@Override
|
||||
protected void benchmark(String name,
|
||||
@@ -73,7 +76,8 @@ public abstract class DatabasePerformanceComparisonTest
|
||||
private Database<Connection> openDatabase(boolean conditionA)
|
||||
throws DbException {
|
||||
Database<Connection> db = createDatabase(conditionA,
|
||||
new TestDatabaseConfig(testDir), new SystemClock());
|
||||
new TestDatabaseConfig(testDir), new TestMessageFactory(),
|
||||
new SystemClock());
|
||||
db.open(databaseKey, null);
|
||||
return db;
|
||||
}
|
||||
|
||||
@@ -41,6 +41,7 @@ import static org.briarproject.bramble.test.TestUtils.getGroup;
|
||||
import static org.briarproject.bramble.test.TestUtils.getIdentity;
|
||||
import static org.briarproject.bramble.test.TestUtils.getMessage;
|
||||
import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
|
||||
import static org.briarproject.bramble.test.TestUtils.getRandomId;
|
||||
import static org.briarproject.bramble.test.TestUtils.getTestDirectory;
|
||||
import static org.briarproject.bramble.test.UTest.Result.INCONCLUSIVE;
|
||||
import static org.briarproject.bramble.test.UTest.Z_CRITICAL_0_1;
|
||||
@@ -80,6 +81,7 @@ public abstract class DatabasePerformanceTest extends BrambleTestCase {
|
||||
private static final int METADATA_KEYS_PER_MESSAGE = 5;
|
||||
private static final int METADATA_KEY_LENGTH = 10;
|
||||
private static final int METADATA_VALUE_LENGTH = 100;
|
||||
private static final int OFFERED_MESSAGES_PER_CONTACT = 100;
|
||||
|
||||
/**
|
||||
* How many benchmark iterations to run in each block.
|
||||
@@ -190,6 +192,16 @@ public abstract class DatabasePerformanceTest extends BrambleTestCase {
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCountOfferedMessages() throws Exception {
|
||||
String name = "countOfferedMessages(T, ContactId)";
|
||||
benchmark(name, db -> {
|
||||
Connection txn = db.startTransaction();
|
||||
db.countOfferedMessages(txn, pickRandom(contacts).getId());
|
||||
db.commitTransaction(txn);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetContact() throws Exception {
|
||||
String name = "getContact(T, ContactId)";
|
||||
@@ -442,6 +454,17 @@ public abstract class DatabasePerformanceTest extends BrambleTestCase {
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetMessagesToRequest() throws Exception {
|
||||
String name = "getMessagesToRequest(T, ContactId, int)";
|
||||
benchmark(name, db -> {
|
||||
Connection txn = db.startTransaction();
|
||||
db.getMessagesToRequest(txn, pickRandom(contacts).getId(),
|
||||
MAX_MESSAGE_IDS);
|
||||
db.commitTransaction(txn);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetMessagesToSend() throws Exception {
|
||||
String name = "getMessagesToSend(T, ContactId, int)";
|
||||
@@ -484,11 +507,11 @@ public abstract class DatabasePerformanceTest extends BrambleTestCase {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetSmallMessage() throws Exception {
|
||||
String name = "getSmallMessage(T, MessageId)";
|
||||
public void testGetMessage() throws Exception {
|
||||
String name = "getMessage(T, MessageId)";
|
||||
benchmark(name, db -> {
|
||||
Connection txn = db.startTransaction();
|
||||
db.getSmallMessage(txn, pickRandom(messages).getId());
|
||||
db.getMessage(txn, pickRandom(messages).getId());
|
||||
db.commitTransaction(txn);
|
||||
});
|
||||
}
|
||||
@@ -560,6 +583,9 @@ public abstract class DatabasePerformanceTest extends BrambleTestCase {
|
||||
groupMessages.get(g.getId()).add(m.getId());
|
||||
}
|
||||
}
|
||||
for (int j = 0; j < OFFERED_MESSAGES_PER_CONTACT; j++) {
|
||||
db.addOfferedMessage(txn, c, new MessageId(getRandomId()));
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < LOCAL_GROUPS; i++) {
|
||||
Group g = getGroup(clientIds.get(i % CLIENTS), 123);
|
||||
|
||||
@@ -3,9 +3,11 @@ package org.briarproject.bramble.db;
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.db.DatabaseConfig;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
import org.briarproject.bramble.api.sync.MessageFactory;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
import org.briarproject.bramble.system.SystemClock;
|
||||
import org.briarproject.bramble.test.TestDatabaseConfig;
|
||||
import org.briarproject.bramble.test.TestMessageFactory;
|
||||
import org.briarproject.bramble.util.IoUtils;
|
||||
|
||||
import java.io.File;
|
||||
@@ -24,7 +26,7 @@ public abstract class DatabaseTraceTest extends DatabasePerformanceTest {
|
||||
private SecretKey databaseKey = getSecretKey();
|
||||
|
||||
abstract Database<Connection> createDatabase(DatabaseConfig databaseConfig,
|
||||
Clock clock);
|
||||
MessageFactory messageFactory, Clock clock);
|
||||
|
||||
@Nullable
|
||||
protected abstract File getTraceFile();
|
||||
@@ -46,7 +48,8 @@ public abstract class DatabaseTraceTest extends DatabasePerformanceTest {
|
||||
|
||||
private Database<Connection> openDatabase() throws DbException {
|
||||
Database<Connection> db = createDatabase(
|
||||
new TestDatabaseConfig(testDir), new SystemClock());
|
||||
new TestDatabaseConfig(testDir), new TestMessageFactory(),
|
||||
new SystemClock());
|
||||
db.open(databaseKey, null);
|
||||
return db;
|
||||
}
|
||||
|
||||
@@ -16,6 +16,6 @@ public class H2DatabasePerformanceTest extends SingleDatabasePerformanceTest {
|
||||
@Override
|
||||
protected JdbcDatabase createDatabase(DatabaseConfig config,
|
||||
MessageFactory messageFactory, Clock clock) {
|
||||
return new H2Database(config, clock);
|
||||
return new H2Database(config, messageFactory, clock);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,6 @@ public class H2DatabaseTest extends JdbcDatabaseTest {
|
||||
@Override
|
||||
protected JdbcDatabase createDatabase(DatabaseConfig config,
|
||||
MessageFactory messageFactory, Clock clock) {
|
||||
return new H2Database(config, clock);
|
||||
return new H2Database(config, messageFactory, clock);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package org.briarproject.bramble.db;
|
||||
|
||||
import org.briarproject.bramble.api.db.DatabaseConfig;
|
||||
import org.briarproject.bramble.api.sync.MessageFactory;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
import org.junit.Ignore;
|
||||
|
||||
@@ -14,8 +15,8 @@ public class H2DatabaseTraceTest extends DatabaseTraceTest {
|
||||
|
||||
@Override
|
||||
Database<Connection> createDatabase(DatabaseConfig databaseConfig,
|
||||
Clock clock) {
|
||||
return new H2Database(databaseConfig, clock) {
|
||||
MessageFactory messageFactory, Clock clock) {
|
||||
return new H2Database(databaseConfig, messageFactory, clock) {
|
||||
@Override
|
||||
@Nonnull
|
||||
String getUrl() {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package org.briarproject.bramble.db;
|
||||
|
||||
import org.briarproject.bramble.api.db.DatabaseConfig;
|
||||
import org.briarproject.bramble.api.sync.MessageFactory;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
import org.junit.Ignore;
|
||||
|
||||
@@ -12,11 +13,11 @@ public class H2HyperSqlDatabasePerformanceComparisonTest
|
||||
|
||||
@Override
|
||||
Database<Connection> createDatabase(boolean conditionA,
|
||||
DatabaseConfig databaseConfig,
|
||||
DatabaseConfig databaseConfig, MessageFactory messageFactory,
|
||||
Clock clock) {
|
||||
if (conditionA)
|
||||
return new H2Database(databaseConfig, clock);
|
||||
else return new HyperSqlDatabase(databaseConfig, clock);
|
||||
return new H2Database(databaseConfig, messageFactory, clock);
|
||||
else return new HyperSqlDatabase(databaseConfig, messageFactory, clock);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -11,7 +11,7 @@ public class H2MigrationTest extends DatabaseMigrationTest {
|
||||
@Override
|
||||
Database<Connection> createDatabase(
|
||||
List<Migration<Connection>> migrations) {
|
||||
return new H2Database(config, clock) {
|
||||
return new H2Database(config, messageFactory, clock) {
|
||||
@Override
|
||||
List<Migration<Connection>> getMigrations() {
|
||||
return migrations;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package org.briarproject.bramble.db;
|
||||
|
||||
import org.briarproject.bramble.api.db.DatabaseConfig;
|
||||
import org.briarproject.bramble.api.sync.MessageFactory;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
import org.junit.Ignore;
|
||||
|
||||
@@ -17,9 +18,9 @@ public class H2SelfDatabasePerformanceComparisonTest
|
||||
|
||||
@Override
|
||||
Database<Connection> createDatabase(boolean conditionA,
|
||||
DatabaseConfig databaseConfig,
|
||||
DatabaseConfig databaseConfig, MessageFactory messageFactory,
|
||||
Clock clock) {
|
||||
return new H2Database(databaseConfig, clock);
|
||||
return new H2Database(databaseConfig, messageFactory, clock);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -3,6 +3,7 @@ package org.briarproject.bramble.db;
|
||||
import org.briarproject.bramble.api.db.DatabaseConfig;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.sync.MessageFactory;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
import org.junit.Ignore;
|
||||
|
||||
@@ -19,11 +20,12 @@ public class H2SleepDatabasePerformanceComparisonTest
|
||||
|
||||
@Override
|
||||
Database<Connection> createDatabase(boolean conditionA,
|
||||
DatabaseConfig databaseConfig, Clock clock) {
|
||||
DatabaseConfig databaseConfig, MessageFactory messageFactory,
|
||||
Clock clock) {
|
||||
if (conditionA) {
|
||||
return new H2Database(databaseConfig, clock);
|
||||
return new H2Database(databaseConfig, messageFactory, clock);
|
||||
} else {
|
||||
return new H2Database(databaseConfig, clock) {
|
||||
return new H2Database(databaseConfig, messageFactory, clock) {
|
||||
@Override
|
||||
@NotNullByDefault
|
||||
public void commitTransaction(Connection txn)
|
||||
|
||||
@@ -17,6 +17,6 @@ public class HyperSqlDatabasePerformanceTest
|
||||
@Override
|
||||
protected JdbcDatabase createDatabase(DatabaseConfig config,
|
||||
MessageFactory messageFactory, Clock clock) {
|
||||
return new HyperSqlDatabase(config, clock);
|
||||
return new HyperSqlDatabase(config, messageFactory, clock);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,6 @@ public class HyperSqlDatabaseTest extends JdbcDatabaseTest {
|
||||
@Override
|
||||
protected JdbcDatabase createDatabase(DatabaseConfig config,
|
||||
MessageFactory messageFactory, Clock clock) {
|
||||
return new HyperSqlDatabase(config, clock);
|
||||
return new HyperSqlDatabase(config, messageFactory ,clock);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ public class HyperSqlMigrationTest extends DatabaseMigrationTest {
|
||||
@Override
|
||||
Database<Connection> createDatabase(
|
||||
List<Migration<Connection>> migrations) {
|
||||
return new HyperSqlDatabase(config, clock) {
|
||||
return new HyperSqlDatabase(config, messageFactory, clock) {
|
||||
@Override
|
||||
List<Migration<Connection>> getMigrations() {
|
||||
return migrations;
|
||||
|
||||
@@ -41,6 +41,7 @@ import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.sql.Connection;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -165,7 +166,7 @@ public abstract class JdbcDatabaseTest extends BrambleTestCase {
|
||||
assertTrue(db.containsGroup(txn, groupId));
|
||||
assertTrue(db.containsMessage(txn, messageId));
|
||||
assertArrayEquals(message.getBody(),
|
||||
db.getSmallMessage(txn, messageId).getBody());
|
||||
db.getMessage(txn, messageId).getBody());
|
||||
|
||||
// Delete the records
|
||||
db.removeMessage(txn, messageId);
|
||||
@@ -1186,6 +1187,35 @@ public abstract class JdbcDatabaseTest extends BrambleTestCase {
|
||||
db.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOfferedMessages() throws Exception {
|
||||
Database<Connection> db = open(false);
|
||||
Connection txn = db.startTransaction();
|
||||
|
||||
// Add a contact - initially there should be no offered messages
|
||||
db.addIdentity(txn, identity);
|
||||
assertEquals(contactId,
|
||||
db.addContact(txn, author, localAuthor.getId(), null, true));
|
||||
assertEquals(0, db.countOfferedMessages(txn, contactId));
|
||||
|
||||
// Add some offered messages and count them
|
||||
List<MessageId> ids = new ArrayList<>();
|
||||
for (int i = 0; i < 10; i++) {
|
||||
MessageId m = new MessageId(getRandomId());
|
||||
db.addOfferedMessage(txn, contactId, m);
|
||||
ids.add(m);
|
||||
}
|
||||
assertEquals(10, db.countOfferedMessages(txn, contactId));
|
||||
|
||||
// Remove some of the offered messages and count again
|
||||
List<MessageId> half = ids.subList(0, 5);
|
||||
db.removeOfferedMessages(txn, contactId, half);
|
||||
assertEquals(5, db.countOfferedMessages(txn, contactId));
|
||||
|
||||
db.commitTransaction(txn);
|
||||
db.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGroupMetadata() throws Exception {
|
||||
Database<Connection> db = open(false);
|
||||
@@ -1899,7 +1929,7 @@ public abstract class JdbcDatabaseTest extends BrambleTestCase {
|
||||
assertEquals(singletonList(messageId), ids);
|
||||
|
||||
// The message should be available
|
||||
Message m = db.getSmallMessage(txn, messageId);
|
||||
Message m = db.getMessage(txn, messageId);
|
||||
assertEquals(messageId, m.getId());
|
||||
assertEquals(groupId, m.getGroupId());
|
||||
assertEquals(message.getTimestamp(), m.getTimestamp());
|
||||
@@ -1919,7 +1949,7 @@ public abstract class JdbcDatabaseTest extends BrambleTestCase {
|
||||
|
||||
// Requesting the message should throw an exception
|
||||
try {
|
||||
db.getSmallMessage(txn, messageId);
|
||||
db.getMessage(txn, messageId);
|
||||
fail();
|
||||
} catch (MessageDeletedException expected) {
|
||||
// Expected
|
||||
@@ -2057,7 +2087,7 @@ public abstract class JdbcDatabaseTest extends BrambleTestCase {
|
||||
Connection txn = db.startTransaction();
|
||||
try {
|
||||
// Ask for a nonexistent message - an exception should be thrown
|
||||
db.getSmallMessage(txn, messageId);
|
||||
db.getMessage(txn, messageId);
|
||||
fail();
|
||||
} catch (DbException expected) {
|
||||
// It should be possible to abort the transaction without error
|
||||
|
||||
@@ -402,7 +402,7 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
||||
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||
localGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, fooUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, fooUpdateId);
|
||||
will(returnValue(fooUpdate));
|
||||
oneOf(clientHelper).parseAndValidateTransportProperties(
|
||||
fooPropertiesDict);
|
||||
@@ -469,7 +469,7 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
||||
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||
contactGroup2.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, fooUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, fooUpdateId);
|
||||
will(returnValue(fooUpdate));
|
||||
oneOf(clientHelper).parseAndValidateTransportProperties(
|
||||
fooPropertiesDict);
|
||||
@@ -524,7 +524,7 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
||||
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||
contactGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, updateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, updateId);
|
||||
will(returnValue(update));
|
||||
oneOf(clientHelper).parseAndValidateTransportProperties(
|
||||
fooPropertiesDict);
|
||||
@@ -562,7 +562,7 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
||||
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||
localGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, updateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, updateId);
|
||||
will(returnValue(update));
|
||||
oneOf(clientHelper).parseAndValidateTransportProperties(
|
||||
fooPropertiesDict);
|
||||
@@ -693,7 +693,7 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
||||
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||
localGroup.getId());
|
||||
will(returnValue(localGroupMessageMetadata));
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, localGroupUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, localGroupUpdateId);
|
||||
will(returnValue(oldUpdate));
|
||||
oneOf(clientHelper).parseAndValidateTransportProperties(
|
||||
oldPropertiesDict);
|
||||
@@ -758,7 +758,7 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
||||
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||
localGroup.getId());
|
||||
will(returnValue(localGroupMessageMetadata));
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, localGroupUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, localGroupUpdateId);
|
||||
will(returnValue(oldUpdate));
|
||||
oneOf(clientHelper).parseAndValidateTransportProperties(
|
||||
oldPropertiesDict);
|
||||
@@ -817,12 +817,12 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
||||
localGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
// Retrieve and parse the latest local properties
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, fooVersion999);
|
||||
oneOf(clientHelper).getMessageAsList(txn, fooVersion999);
|
||||
will(returnValue(fooUpdate));
|
||||
oneOf(clientHelper).parseAndValidateTransportProperties(
|
||||
fooPropertiesDict);
|
||||
will(returnValue(fooProperties));
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, barVersion3);
|
||||
oneOf(clientHelper).getMessageAsList(txn, barVersion3);
|
||||
will(returnValue(barUpdate));
|
||||
oneOf(clientHelper).parseAndValidateTransportProperties(
|
||||
barPropertiesDict);
|
||||
|
||||
@@ -27,7 +27,6 @@ import org.briarproject.bramble.api.rendezvous.event.RendezvousConnectionOpenedE
|
||||
import org.briarproject.bramble.api.rendezvous.event.RendezvousPollEvent;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
import org.briarproject.bramble.api.system.TaskScheduler;
|
||||
import org.briarproject.bramble.api.system.TaskScheduler.Cancellable;
|
||||
import org.briarproject.bramble.test.BrambleMockTestCase;
|
||||
import org.briarproject.bramble.test.CaptureArgumentAction;
|
||||
import org.briarproject.bramble.test.DbExpectations;
|
||||
@@ -80,7 +79,6 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
context.mock(KeyMaterialSource.class);
|
||||
private final RendezvousEndpoint rendezvousEndpoint =
|
||||
context.mock(RendezvousEndpoint.class);
|
||||
private final Cancellable cancellable = context.mock(Cancellable.class);
|
||||
|
||||
private final Executor ioExecutor = new ImmediateExecutor();
|
||||
private final PendingContact pendingContact = getPendingContact();
|
||||
@@ -109,7 +107,7 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
long beforeExpiry = pendingContact.getTimestamp()
|
||||
+ RENDEZVOUS_TIMEOUT_MS - 1000;
|
||||
long afterExpiry = beforeExpiry + POLLING_INTERVAL_MS;
|
||||
AtomicReference<Runnable> capturePollTask;
|
||||
AtomicReference<Runnable> capturePollTask = new AtomicReference<>();
|
||||
|
||||
// Start the service
|
||||
context.checking(new DbExpectations() {{
|
||||
@@ -123,17 +121,21 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
oneOf(eventBus).broadcast(with(new PredicateMatcher<>(
|
||||
PendingContactStateChangedEvent.class, e ->
|
||||
e.getPendingContactState() == OFFLINE)));
|
||||
// Capture the poll task
|
||||
oneOf(scheduler).scheduleWithFixedDelay(with(any(Runnable.class)),
|
||||
with(any(Executor.class)), with(POLLING_INTERVAL_MS),
|
||||
with(POLLING_INTERVAL_MS), with(MILLISECONDS));
|
||||
will(new CaptureArgumentAction<>(capturePollTask, Runnable.class,
|
||||
0));
|
||||
}});
|
||||
|
||||
expectDeriveRendezvousKey();
|
||||
capturePollTask = expectSchedulePolling();
|
||||
|
||||
rendezvousPoller.startService();
|
||||
context.assertIsSatisfied();
|
||||
|
||||
// Run the poll task - pending contact expires, polling is cancelled
|
||||
// Run the poll task - pending contact expires
|
||||
expectPendingContactExpires(afterExpiry);
|
||||
expectCancelPolling();
|
||||
|
||||
capturePollTask.get().run();
|
||||
}
|
||||
@@ -155,6 +157,10 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
oneOf(eventBus).broadcast(with(new PredicateMatcher<>(
|
||||
PendingContactStateChangedEvent.class, e ->
|
||||
e.getPendingContactState() == FAILED)));
|
||||
// Schedule the poll task
|
||||
oneOf(scheduler).scheduleWithFixedDelay(with(any(Runnable.class)),
|
||||
with(any(Executor.class)), with(POLLING_INTERVAL_MS),
|
||||
with(POLLING_INTERVAL_MS), with(MILLISECONDS));
|
||||
}});
|
||||
|
||||
rendezvousPoller.startService();
|
||||
@@ -177,8 +183,7 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
rendezvousPoller.eventOccurred(new TransportActiveEvent(transportId));
|
||||
context.assertIsSatisfied();
|
||||
|
||||
// Add the pending contact - endpoint should be created and polled,
|
||||
// polling should be scheduled
|
||||
// Add the pending contact - endpoint should be created and polled
|
||||
expectAddPendingContact(beforeExpiry, WAITING_FOR_CONNECTION);
|
||||
expectDeriveRendezvousKey();
|
||||
expectCreateEndpoint();
|
||||
@@ -195,16 +200,12 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
any(ConnectionHandler.class)))));
|
||||
}});
|
||||
|
||||
expectSchedulePolling();
|
||||
|
||||
rendezvousPoller.eventOccurred(
|
||||
new PendingContactAddedEvent(pendingContact));
|
||||
context.assertIsSatisfied();
|
||||
|
||||
// Remove the pending contact - endpoint should be closed,
|
||||
// polling should be cancelled
|
||||
// Remove the pending contact - endpoint should be closed
|
||||
expectCloseEndpoint();
|
||||
expectCancelPolling();
|
||||
|
||||
rendezvousPoller.eventOccurred(
|
||||
new PendingContactRemovedEvent(pendingContact.getId()));
|
||||
@@ -220,10 +221,10 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
long beforeExpiry = pendingContact.getTimestamp()
|
||||
+ RENDEZVOUS_TIMEOUT_MS - 1000;
|
||||
long afterExpiry = beforeExpiry + POLLING_INTERVAL_MS;
|
||||
AtomicReference<Runnable> capturePollTask;
|
||||
|
||||
// Start the service
|
||||
expectStartupWithNoPendingContacts();
|
||||
// Start the service, capturing the poll task
|
||||
AtomicReference<Runnable> capturePollTask =
|
||||
expectStartupWithNoPendingContacts();
|
||||
|
||||
rendezvousPoller.startService();
|
||||
context.assertIsSatisfied();
|
||||
@@ -234,8 +235,7 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
rendezvousPoller.eventOccurred(new TransportActiveEvent(transportId));
|
||||
context.assertIsSatisfied();
|
||||
|
||||
// Add the pending contact - endpoint should be created and polled,
|
||||
// polling should be scheduled
|
||||
// Add the pending contact - endpoint should be created and polled
|
||||
expectAddPendingContact(beforeExpiry, WAITING_FOR_CONNECTION);
|
||||
expectDeriveRendezvousKey();
|
||||
expectCreateEndpoint();
|
||||
@@ -252,17 +252,13 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
any(ConnectionHandler.class)))));
|
||||
}});
|
||||
|
||||
capturePollTask = expectSchedulePolling();
|
||||
|
||||
rendezvousPoller.eventOccurred(
|
||||
new PendingContactAddedEvent(pendingContact));
|
||||
context.assertIsSatisfied();
|
||||
|
||||
// Run the poll task - pending contact expires, endpoint is closed,
|
||||
// polling is cancelled
|
||||
// Run the poll task - pending contact expires, endpoint is closed
|
||||
expectPendingContactExpires(afterExpiry);
|
||||
expectCloseEndpoint();
|
||||
expectCancelPolling();
|
||||
|
||||
capturePollTask.get().run();
|
||||
context.assertIsSatisfied();
|
||||
@@ -290,7 +286,6 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
// Add the pending contact - no endpoints should be created yet
|
||||
expectAddPendingContact(beforeExpiry, OFFLINE);
|
||||
expectDeriveRendezvousKey();
|
||||
expectSchedulePolling();
|
||||
|
||||
rendezvousPoller.eventOccurred(
|
||||
new PendingContactAddedEvent(pendingContact));
|
||||
@@ -312,8 +307,6 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
context.assertIsSatisfied();
|
||||
|
||||
// Remove the pending contact - endpoint is already closed
|
||||
expectCancelPolling();
|
||||
|
||||
rendezvousPoller.eventOccurred(
|
||||
new PendingContactRemovedEvent(pendingContact.getId()));
|
||||
}
|
||||
@@ -355,9 +348,8 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
rendezvousPoller.startService();
|
||||
context.assertIsSatisfied();
|
||||
|
||||
// Run the poll task - pending contact expires, polling is cancelled
|
||||
// Run the poll task - pending contact expires
|
||||
expectPendingContactExpires(afterExpiry);
|
||||
expectCancelPolling();
|
||||
|
||||
capturePollTask.get().run();
|
||||
context.assertIsSatisfied();
|
||||
@@ -393,9 +385,8 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
new RendezvousConnectionOpenedEvent(pendingContact.getId()));
|
||||
context.assertIsSatisfied();
|
||||
|
||||
// Run the poll task - pending contact expires, polling is cancelled
|
||||
// Run the poll task - pending contact expires
|
||||
expectPendingContactExpires(afterExpiry);
|
||||
expectCancelPolling();
|
||||
|
||||
capturePollTask.get().run();
|
||||
context.assertIsSatisfied();
|
||||
@@ -426,9 +417,8 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
new RendezvousConnectionOpenedEvent(pendingContact.getId()));
|
||||
context.assertIsSatisfied();
|
||||
|
||||
// Run the poll task - pending contact expires, polling is cancelled
|
||||
// Run the poll task - pending contact expires
|
||||
expectPendingContactExpires(afterExpiry);
|
||||
expectCancelPolling();
|
||||
|
||||
capturePollTask.get().run();
|
||||
context.assertIsSatisfied();
|
||||
@@ -457,8 +447,6 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
context.assertIsSatisfied();
|
||||
|
||||
// Pending contact is removed - no event should be broadcast
|
||||
expectCancelPolling();
|
||||
|
||||
rendezvousPoller.eventOccurred(
|
||||
new PendingContactRemovedEvent(pendingContact.getId()));
|
||||
context.assertIsSatisfied();
|
||||
@@ -468,35 +456,25 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
pendingContact.getId(), false));
|
||||
}
|
||||
|
||||
private AtomicReference<Runnable> expectSchedulePolling() {
|
||||
AtomicReference<Runnable> capturePollTask = new AtomicReference<>();
|
||||
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(scheduler).scheduleWithFixedDelay(with(any(Runnable.class)),
|
||||
with(any(Executor.class)), with(POLLING_INTERVAL_MS),
|
||||
with(POLLING_INTERVAL_MS), with(MILLISECONDS));
|
||||
will(doAll(new CaptureArgumentAction<>(capturePollTask,
|
||||
Runnable.class, 0), returnValue(cancellable)));
|
||||
}});
|
||||
|
||||
return capturePollTask;
|
||||
}
|
||||
|
||||
private void expectCancelPolling() {
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(cancellable).cancel();
|
||||
}});
|
||||
}
|
||||
|
||||
private void expectStartupWithNoPendingContacts() throws Exception {
|
||||
private AtomicReference<Runnable> expectStartupWithNoPendingContacts()
|
||||
throws Exception {
|
||||
Transaction txn = new Transaction(null, true);
|
||||
AtomicReference<Runnable> capturePollTask = new AtomicReference<>();
|
||||
|
||||
context.checking(new DbExpectations() {{
|
||||
// Load the pending contacts
|
||||
oneOf(db).transaction(with(true), withDbRunnable(txn));
|
||||
oneOf(db).getPendingContacts(txn);
|
||||
will(returnValue(emptyList()));
|
||||
// Capture the poll task
|
||||
oneOf(scheduler).scheduleWithFixedDelay(with(any(Runnable.class)),
|
||||
with(any(Executor.class)), with(POLLING_INTERVAL_MS),
|
||||
with(POLLING_INTERVAL_MS), with(MILLISECONDS));
|
||||
will(new CaptureArgumentAction<>(capturePollTask, Runnable.class,
|
||||
0));
|
||||
}});
|
||||
|
||||
return capturePollTask;
|
||||
}
|
||||
|
||||
private void expectAddPendingContact(long now,
|
||||
@@ -552,6 +530,7 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
private AtomicReference<Runnable> expectStartupWithPendingContact(long now)
|
||||
throws Exception {
|
||||
Transaction txn = new Transaction(null, true);
|
||||
AtomicReference<Runnable> capturePollTask = new AtomicReference<>();
|
||||
|
||||
context.checking(new DbExpectations() {{
|
||||
// Load the pending contacts
|
||||
@@ -564,10 +543,17 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
oneOf(eventBus).broadcast(with(new PredicateMatcher<>(
|
||||
PendingContactStateChangedEvent.class, e ->
|
||||
e.getPendingContactState() == OFFLINE)));
|
||||
// Capture the poll task
|
||||
oneOf(scheduler).scheduleWithFixedDelay(with(any(Runnable.class)),
|
||||
with(any(Executor.class)), with(POLLING_INTERVAL_MS),
|
||||
with(POLLING_INTERVAL_MS), with(MILLISECONDS));
|
||||
will(new CaptureArgumentAction<>(capturePollTask, Runnable.class,
|
||||
0));
|
||||
}});
|
||||
|
||||
expectDeriveRendezvousKey();
|
||||
return expectSchedulePolling();
|
||||
|
||||
return capturePollTask;
|
||||
}
|
||||
|
||||
private void expectPendingContactExpires(long now) {
|
||||
|
||||
@@ -64,7 +64,7 @@ public class SimplexOutgoingSessionTest extends BrambleMockTestCase {
|
||||
oneOf(db).transactionWithNullableResult(with(false),
|
||||
withNullableDbCallable(noMsgTxn));
|
||||
oneOf(db).generateBatch(with(noMsgTxn), with(contactId),
|
||||
with(any(int.class)), with(MAX_LATENCY), with(true));
|
||||
with(any(int.class)), with(MAX_LATENCY));
|
||||
will(returnValue(null));
|
||||
// Send the end of stream marker
|
||||
oneOf(streamWriter).sendEndOfStream();
|
||||
@@ -101,7 +101,7 @@ public class SimplexOutgoingSessionTest extends BrambleMockTestCase {
|
||||
oneOf(db).transactionWithNullableResult(with(false),
|
||||
withNullableDbCallable(msgTxn));
|
||||
oneOf(db).generateBatch(with(msgTxn), with(contactId),
|
||||
with(any(int.class)), with(MAX_LATENCY), with(true));
|
||||
with(any(int.class)), with(MAX_LATENCY));
|
||||
will(returnValue(singletonList(message)));
|
||||
oneOf(recordWriter).writeMessage(message);
|
||||
// No more acks
|
||||
@@ -113,7 +113,7 @@ public class SimplexOutgoingSessionTest extends BrambleMockTestCase {
|
||||
oneOf(db).transactionWithNullableResult(with(false),
|
||||
withNullableDbCallable(noMsgTxn));
|
||||
oneOf(db).generateBatch(with(noMsgTxn), with(contactId),
|
||||
with(any(int.class)), with(MAX_LATENCY), with(true));
|
||||
with(any(int.class)), with(MAX_LATENCY));
|
||||
will(returnValue(null));
|
||||
// Send the end of stream marker
|
||||
oneOf(streamWriter).sendEndOfStream();
|
||||
|
||||
@@ -99,7 +99,7 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
|
||||
context.checking(new DbExpectations() {{
|
||||
// Load the first raw message and group
|
||||
oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
|
||||
oneOf(db).getSmallMessage(txn, messageId);
|
||||
oneOf(db).getMessage(txn, messageId);
|
||||
will(returnValue(message));
|
||||
oneOf(db).getGroup(txn, groupId);
|
||||
will(returnValue(group));
|
||||
@@ -118,7 +118,7 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
|
||||
will(returnValue(emptyMap()));
|
||||
// Load the second raw message and group
|
||||
oneOf(db).transactionWithResult(with(true), withDbCallable(txn2));
|
||||
oneOf(db).getSmallMessage(txn2, messageId1);
|
||||
oneOf(db).getMessage(txn2, messageId1);
|
||||
will(returnValue(message1));
|
||||
oneOf(db).getGroup(txn2, groupId);
|
||||
will(returnValue(group));
|
||||
@@ -159,7 +159,7 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
|
||||
oneOf(db).getMessageDependencies(txn, messageId);
|
||||
will(returnValue(singletonMap(messageId1, DELIVERED)));
|
||||
// Get the message and its metadata to deliver
|
||||
oneOf(db).getSmallMessage(txn, messageId);
|
||||
oneOf(db).getMessage(txn, messageId);
|
||||
will(returnValue(message));
|
||||
oneOf(db).getGroup(txn, groupId);
|
||||
will(returnValue(group));
|
||||
@@ -179,7 +179,7 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
|
||||
oneOf(db).getMessageDependencies(txn1, messageId2);
|
||||
will(returnValue(singletonMap(messageId1, DELIVERED)));
|
||||
// Get the dependent and its metadata to deliver
|
||||
oneOf(db).getSmallMessage(txn1, messageId2);
|
||||
oneOf(db).getMessage(txn1, messageId2);
|
||||
will(returnValue(message2));
|
||||
oneOf(db).getGroup(txn1, groupId);
|
||||
will(returnValue(group));
|
||||
@@ -276,11 +276,11 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
|
||||
context.checking(new DbExpectations() {{
|
||||
// Load the first raw message - *gasp* it's gone!
|
||||
oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
|
||||
oneOf(db).getSmallMessage(txn, messageId);
|
||||
oneOf(db).getMessage(txn, messageId);
|
||||
will(throwException(new NoSuchMessageException()));
|
||||
// Load the second raw message and group
|
||||
oneOf(db).transactionWithResult(with(true), withDbCallable(txn1));
|
||||
oneOf(db).getSmallMessage(txn1, messageId1);
|
||||
oneOf(db).getMessage(txn1, messageId1);
|
||||
will(returnValue(message1));
|
||||
oneOf(db).getGroup(txn1, groupId);
|
||||
will(returnValue(group));
|
||||
@@ -317,14 +317,14 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
|
||||
context.checking(new DbExpectations() {{
|
||||
// Load the first raw message
|
||||
oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
|
||||
oneOf(db).getSmallMessage(txn, messageId);
|
||||
oneOf(db).getMessage(txn, messageId);
|
||||
will(returnValue(message));
|
||||
// Load the group - *gasp* it's gone!
|
||||
oneOf(db).getGroup(txn, groupId);
|
||||
will(throwException(new NoSuchGroupException()));
|
||||
// Load the second raw message and group
|
||||
oneOf(db).transactionWithResult(with(true), withDbCallable(txn1));
|
||||
oneOf(db).getSmallMessage(txn1, messageId1);
|
||||
oneOf(db).getMessage(txn1, messageId1);
|
||||
will(returnValue(message1));
|
||||
oneOf(db).getGroup(txn1, groupId);
|
||||
will(returnValue(group));
|
||||
@@ -614,7 +614,7 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
|
||||
oneOf(db).getMessageDependencies(txn2, messageId1);
|
||||
will(returnValue(singletonMap(messageId, DELIVERED)));
|
||||
// Get message 1 and its metadata
|
||||
oneOf(db).getSmallMessage(txn2, messageId1);
|
||||
oneOf(db).getMessage(txn2, messageId1);
|
||||
will(returnValue(message1));
|
||||
oneOf(db).getGroup(txn2, groupId);
|
||||
will(returnValue(group));
|
||||
@@ -634,7 +634,7 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
|
||||
oneOf(db).getMessageDependencies(txn3, messageId2);
|
||||
will(returnValue(singletonMap(messageId, DELIVERED)));
|
||||
// Get message 2 and its metadata
|
||||
oneOf(db).getSmallMessage(txn3, messageId2);
|
||||
oneOf(db).getMessage(txn3, messageId2);
|
||||
will(returnValue(message2));
|
||||
oneOf(db).getGroup(txn3, groupId);
|
||||
will(returnValue(group));
|
||||
@@ -654,7 +654,7 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
|
||||
oneOf(db).getMessageDependencies(txn4, messageId3);
|
||||
will(returnValue(twoDependencies));
|
||||
// Get message 3 and its metadata
|
||||
oneOf(db).getSmallMessage(txn4, messageId3);
|
||||
oneOf(db).getMessage(txn4, messageId3);
|
||||
will(returnValue(message3));
|
||||
oneOf(db).getGroup(txn4, groupId);
|
||||
will(returnValue(group));
|
||||
@@ -677,7 +677,7 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
|
||||
oneOf(db).getMessageDependencies(txn6, messageId4);
|
||||
will(returnValue(singletonMap(messageId3, DELIVERED)));
|
||||
// Get message 4 and its metadata
|
||||
oneOf(db).getSmallMessage(txn6, messageId4);
|
||||
oneOf(db).getMessage(txn6, messageId4);
|
||||
will(returnValue(message4));
|
||||
oneOf(db).getGroup(txn6, groupId);
|
||||
will(returnValue(group));
|
||||
|
||||
@@ -184,7 +184,7 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
|
||||
contactGroup.getId());
|
||||
will(returnValue(singletonMap(localUpdateId, localUpdateMeta)));
|
||||
// Load the latest local update
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, localUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, localUpdateId);
|
||||
will(returnValue(localUpdateBody));
|
||||
// Latest local update is up-to-date, no visibilities have changed
|
||||
}});
|
||||
@@ -206,7 +206,7 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
|
||||
// Load the old client versions
|
||||
oneOf(db).getMessageIds(txn, localGroup.getId());
|
||||
will(returnValue(singletonList(localVersionsId)));
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, localVersionsId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, localVersionsId);
|
||||
will(returnValue(localVersionsBody));
|
||||
// Client versions are up-to-date
|
||||
}});
|
||||
@@ -248,7 +248,7 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
|
||||
// Load the old client versions
|
||||
oneOf(db).getMessageIds(txn, localGroup.getId());
|
||||
will(returnValue(singletonList(oldLocalVersionsId)));
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, oldLocalVersionsId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, oldLocalVersionsId);
|
||||
will(returnValue(oldLocalVersionsBody));
|
||||
// Delete the old client versions
|
||||
oneOf(db).removeMessage(txn, oldLocalVersionsId);
|
||||
@@ -272,7 +272,7 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
|
||||
will(returnValue(singletonMap(oldLocalUpdateId,
|
||||
oldLocalUpdateMeta)));
|
||||
// Load the latest local update
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, oldLocalUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, oldLocalUpdateId);
|
||||
will(returnValue(oldLocalUpdateBody));
|
||||
// Delete the latest local update
|
||||
oneOf(db).deleteMessage(txn, oldLocalUpdateId);
|
||||
@@ -344,7 +344,7 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
|
||||
// Load the old client versions
|
||||
oneOf(db).getMessageIds(txn, localGroup.getId());
|
||||
will(returnValue(singletonList(oldLocalVersionsId)));
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, oldLocalVersionsId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, oldLocalVersionsId);
|
||||
will(returnValue(oldLocalVersionsBody));
|
||||
// Delete the old client versions
|
||||
oneOf(db).removeMessage(txn, oldLocalVersionsId);
|
||||
@@ -367,10 +367,10 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
|
||||
contactGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
// Load the latest local update
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, oldLocalUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, oldLocalUpdateId);
|
||||
will(returnValue(oldLocalUpdateBody));
|
||||
// Load the latest remote update
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, oldRemoteUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, oldRemoteUpdateId);
|
||||
will(returnValue(oldRemoteUpdateBody));
|
||||
// Delete the latest local update
|
||||
oneOf(db).deleteMessage(txn, oldLocalUpdateId);
|
||||
@@ -451,10 +451,10 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
|
||||
contactGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
// Load the latest local update
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, oldLocalUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, oldLocalUpdateId);
|
||||
will(returnValue(oldLocalUpdateBody));
|
||||
// Load the latest remote update
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, oldRemoteUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, oldRemoteUpdateId);
|
||||
will(returnValue(oldRemoteUpdateBody));
|
||||
// Delete the old remote update
|
||||
oneOf(db).deleteMessage(txn, oldRemoteUpdateId);
|
||||
@@ -490,7 +490,7 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
|
||||
will(returnValue(singletonMap(oldLocalUpdateId,
|
||||
oldLocalUpdateMeta)));
|
||||
// Load the latest local update
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, oldLocalUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, oldLocalUpdateId);
|
||||
will(returnValue(oldLocalUpdateBody));
|
||||
// Get client ID
|
||||
oneOf(clientHelper).getGroupMetadataAsDictionary(txn,
|
||||
@@ -557,10 +557,10 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
|
||||
contactGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
// Load the latest local update
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, oldLocalUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, oldLocalUpdateId);
|
||||
will(returnValue(oldLocalUpdateBody));
|
||||
// Load the latest remote update
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, oldRemoteUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, oldRemoteUpdateId);
|
||||
will(returnValue(oldRemoteUpdateBody));
|
||||
// Delete the old remote update
|
||||
oneOf(db).deleteMessage(txn, oldRemoteUpdateId);
|
||||
@@ -630,10 +630,10 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
|
||||
contactGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
// Load the latest local update
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, oldLocalUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, oldLocalUpdateId);
|
||||
will(returnValue(oldLocalUpdateBody));
|
||||
// Load the latest remote update
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, oldRemoteUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, oldRemoteUpdateId);
|
||||
will(returnValue(oldRemoteUpdateBody));
|
||||
// Delete the old remote update
|
||||
oneOf(db).deleteMessage(txn, oldRemoteUpdateId);
|
||||
@@ -734,9 +734,9 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
|
||||
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||
contactGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, localUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, localUpdateId);
|
||||
will(returnValue(localUpdateBody));
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, remoteUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, remoteUpdateId);
|
||||
will(returnValue(remoteUpdateBody));
|
||||
}});
|
||||
|
||||
@@ -769,9 +769,9 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
|
||||
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||
contactGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, localUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, localUpdateId);
|
||||
will(returnValue(localUpdateBody));
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, remoteUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, remoteUpdateId);
|
||||
will(returnValue(remoteUpdateBody));
|
||||
}});
|
||||
|
||||
@@ -804,9 +804,9 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
|
||||
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||
contactGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, localUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, localUpdateId);
|
||||
will(returnValue(localUpdateBody));
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, remoteUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, remoteUpdateId);
|
||||
will(returnValue(remoteUpdateBody));
|
||||
}});
|
||||
|
||||
@@ -839,9 +839,9 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
|
||||
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||
contactGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, localUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, localUpdateId);
|
||||
will(returnValue(localUpdateBody));
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, remoteUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, remoteUpdateId);
|
||||
will(returnValue(remoteUpdateBody));
|
||||
}});
|
||||
|
||||
@@ -901,7 +901,7 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
|
||||
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||
contactGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, remoteUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, remoteUpdateId);
|
||||
will(returnValue(remoteUpdateBody));
|
||||
}});
|
||||
|
||||
@@ -933,7 +933,7 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
|
||||
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||
contactGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, remoteUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, remoteUpdateId);
|
||||
will(returnValue(remoteUpdateBody));
|
||||
}});
|
||||
|
||||
@@ -965,7 +965,7 @@ public class ClientVersioningManagerImplTest extends BrambleMockTestCase {
|
||||
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||
contactGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
oneOf(clientHelper).getSmallMessageAsList(txn, remoteUpdateId);
|
||||
oneOf(clientHelper).getMessageAsList(txn, remoteUpdateId);
|
||||
will(returnValue(remoteUpdateBody));
|
||||
}});
|
||||
|
||||
|
||||
@@ -62,6 +62,22 @@ class JavaBluetoothPlugin
|
||||
return localDevice != null && LocalDevice.isPowerOn();
|
||||
}
|
||||
|
||||
@Override
|
||||
void enableAdapter() {
|
||||
// Nothing we can do on this platform
|
||||
LOG.info("Could not enable Bluetooth");
|
||||
}
|
||||
|
||||
@Override
|
||||
void disableAdapterIfEnabledByUs() {
|
||||
// We didn't enable it so we don't need to disable it
|
||||
}
|
||||
|
||||
@Override
|
||||
void setEnabledByUs() {
|
||||
// Irrelevant on this platform
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
String getBluetoothAddress() {
|
||||
|
||||
@@ -16,14 +16,14 @@ def getStdout = { command, defaultValue ->
|
||||
}
|
||||
|
||||
android {
|
||||
compileSdkVersion rootProject.ext.compileSdkVersion
|
||||
buildToolsVersion rootProject.ext.buildToolsVersion
|
||||
compileSdkVersion 29
|
||||
buildToolsVersion '29.0.2'
|
||||
|
||||
defaultConfig {
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
versionCode rootProject.ext.versionCode
|
||||
versionName rootProject.ext.versionName
|
||||
minSdkVersion 16
|
||||
targetSdkVersion 28
|
||||
versionCode 10209
|
||||
versionName "1.2.9"
|
||||
applicationId "org.briarproject.briar.android"
|
||||
buildConfigField "String", "GitHash",
|
||||
"\"${getStdout(['git', 'rev-parse', '--short=7', 'HEAD'], 'No commit hash')}\""
|
||||
|
||||
@@ -13,9 +13,8 @@ import java.util.Random;
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4;
|
||||
|
||||
import static androidx.test.InstrumentationRegistry.getContext;
|
||||
import static org.briarproject.briar.android.attachment.AttachmentItem.State.AVAILABLE;
|
||||
import static org.briarproject.briar.android.attachment.AttachmentItem.State.ERROR;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@RunWith(AndroidJUnit4.class)
|
||||
@@ -28,7 +27,7 @@ public class AttachmentRetrieverIntegrationTest {
|
||||
|
||||
private final ImageHelper imageHelper = new ImageHelperImpl();
|
||||
private final AttachmentRetriever retriever =
|
||||
new AttachmentRetrieverImpl(null, null, dimensions, imageHelper,
|
||||
new AttachmentRetrieverImpl(null, dimensions, imageHelper,
|
||||
new ImageSizeCalculator(imageHelper));
|
||||
|
||||
@Test
|
||||
@@ -36,7 +35,7 @@ public class AttachmentRetrieverIntegrationTest {
|
||||
AttachmentHeader h = new AttachmentHeader(msgId, "image/jpeg");
|
||||
InputStream is = getAssetInputStream("kitten_small.jpg");
|
||||
Attachment a = new Attachment(h, is);
|
||||
AttachmentItem item = retriever.createAttachmentItem(a, true);
|
||||
AttachmentItem item = retriever.getAttachmentItem(a, true);
|
||||
assertEquals(msgId, item.getMessageId());
|
||||
assertEquals(160, item.getWidth());
|
||||
assertEquals(240, item.getHeight());
|
||||
@@ -44,7 +43,7 @@ public class AttachmentRetrieverIntegrationTest {
|
||||
assertEquals(240, item.getThumbnailHeight());
|
||||
assertEquals("image/jpeg", item.getMimeType());
|
||||
assertJpgOrJpeg(item.getExtension());
|
||||
assertEquals(AVAILABLE, item.getState());
|
||||
assertFalse(item.hasError());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -52,7 +51,7 @@ public class AttachmentRetrieverIntegrationTest {
|
||||
AttachmentHeader h = new AttachmentHeader(msgId, "image/jpeg");
|
||||
InputStream is = getAssetInputStream("kitten_original.jpg");
|
||||
Attachment a = new Attachment(h, is);
|
||||
AttachmentItem item = retriever.createAttachmentItem(a, true);
|
||||
AttachmentItem item = retriever.getAttachmentItem(a, true);
|
||||
assertEquals(msgId, item.getMessageId());
|
||||
assertEquals(1728, item.getWidth());
|
||||
assertEquals(2592, item.getHeight());
|
||||
@@ -60,7 +59,7 @@ public class AttachmentRetrieverIntegrationTest {
|
||||
assertEquals(dimensions.maxHeight, item.getThumbnailHeight());
|
||||
assertEquals("image/jpeg", item.getMimeType());
|
||||
assertJpgOrJpeg(item.getExtension());
|
||||
assertEquals(AVAILABLE, item.getState());
|
||||
assertFalse(item.hasError());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -68,7 +67,7 @@ public class AttachmentRetrieverIntegrationTest {
|
||||
AttachmentHeader h = new AttachmentHeader(msgId, "image/png");
|
||||
InputStream is = getAssetInputStream("kitten.png");
|
||||
Attachment a = new Attachment(h, is);
|
||||
AttachmentItem item = retriever.createAttachmentItem(a, true);
|
||||
AttachmentItem item = retriever.getAttachmentItem(a, true);
|
||||
assertEquals(msgId, item.getMessageId());
|
||||
assertEquals(737, item.getWidth());
|
||||
assertEquals(510, item.getHeight());
|
||||
@@ -76,7 +75,7 @@ public class AttachmentRetrieverIntegrationTest {
|
||||
assertEquals(138, item.getThumbnailHeight());
|
||||
assertEquals("image/png", item.getMimeType());
|
||||
assertEquals("png", item.getExtension());
|
||||
assertEquals(AVAILABLE, item.getState());
|
||||
assertFalse(item.hasError());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -84,14 +83,14 @@ public class AttachmentRetrieverIntegrationTest {
|
||||
AttachmentHeader h = new AttachmentHeader(msgId, "image/gif");
|
||||
InputStream is = getAssetInputStream("uber.gif");
|
||||
Attachment a = new Attachment(h, is);
|
||||
AttachmentItem item = retriever.createAttachmentItem(a, true);
|
||||
AttachmentItem item = retriever.getAttachmentItem(a, true);
|
||||
assertEquals(1, item.getWidth());
|
||||
assertEquals(1, item.getHeight());
|
||||
assertEquals(dimensions.minHeight, item.getThumbnailWidth());
|
||||
assertEquals(dimensions.minHeight, item.getThumbnailHeight());
|
||||
assertEquals("image/gif", item.getMimeType());
|
||||
assertEquals("gif", item.getExtension());
|
||||
assertEquals(AVAILABLE, item.getState());
|
||||
assertFalse(item.hasError());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -99,14 +98,14 @@ public class AttachmentRetrieverIntegrationTest {
|
||||
AttachmentHeader h = new AttachmentHeader(msgId, "image/jpeg");
|
||||
InputStream is = getAssetInputStream("lottapixel.jpg");
|
||||
Attachment a = new Attachment(h, is);
|
||||
AttachmentItem item = retriever.createAttachmentItem(a, true);
|
||||
AttachmentItem item = retriever.getAttachmentItem(a, true);
|
||||
assertEquals(64250, item.getWidth());
|
||||
assertEquals(64250, item.getHeight());
|
||||
assertEquals(dimensions.maxWidth, item.getThumbnailWidth());
|
||||
assertEquals(dimensions.maxWidth, item.getThumbnailHeight());
|
||||
assertEquals("image/jpeg", item.getMimeType());
|
||||
assertJpgOrJpeg(item.getExtension());
|
||||
assertEquals(AVAILABLE, item.getState());
|
||||
assertFalse(item.hasError());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -114,14 +113,14 @@ public class AttachmentRetrieverIntegrationTest {
|
||||
AttachmentHeader h = new AttachmentHeader(msgId, "image/png");
|
||||
InputStream is = getAssetInputStream("image_io_crash.png");
|
||||
Attachment a = new Attachment(h, is);
|
||||
AttachmentItem item = retriever.createAttachmentItem(a, true);
|
||||
AttachmentItem item = retriever.getAttachmentItem(a, true);
|
||||
assertEquals(1184, item.getWidth());
|
||||
assertEquals(448, item.getHeight());
|
||||
assertEquals(dimensions.maxWidth, item.getThumbnailWidth());
|
||||
assertEquals(dimensions.minHeight, item.getThumbnailHeight());
|
||||
assertEquals("image/png", item.getMimeType());
|
||||
assertEquals("png", item.getExtension());
|
||||
assertEquals(AVAILABLE, item.getState());
|
||||
assertFalse(item.hasError());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -129,14 +128,14 @@ public class AttachmentRetrieverIntegrationTest {
|
||||
AttachmentHeader h = new AttachmentHeader(msgId, "image/gif");
|
||||
InputStream is = getAssetInputStream("gimp_crash.gif");
|
||||
Attachment a = new Attachment(h, is);
|
||||
AttachmentItem item = retriever.createAttachmentItem(a, true);
|
||||
AttachmentItem item = retriever.getAttachmentItem(a, true);
|
||||
assertEquals(1, item.getWidth());
|
||||
assertEquals(1, item.getHeight());
|
||||
assertEquals(dimensions.minHeight, item.getThumbnailWidth());
|
||||
assertEquals(dimensions.minHeight, item.getThumbnailHeight());
|
||||
assertEquals("image/gif", item.getMimeType());
|
||||
assertEquals("gif", item.getExtension());
|
||||
assertEquals(AVAILABLE, item.getState());
|
||||
assertFalse(item.hasError());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -144,14 +143,14 @@ public class AttachmentRetrieverIntegrationTest {
|
||||
AttachmentHeader h = new AttachmentHeader(msgId, "image/gif");
|
||||
InputStream is = getAssetInputStream("opti_png_afl.gif");
|
||||
Attachment a = new Attachment(h, is);
|
||||
AttachmentItem item = retriever.createAttachmentItem(a, true);
|
||||
AttachmentItem item = retriever.getAttachmentItem(a, true);
|
||||
assertEquals(32, item.getWidth());
|
||||
assertEquals(32, item.getHeight());
|
||||
assertEquals(dimensions.minHeight, item.getThumbnailWidth());
|
||||
assertEquals(dimensions.minHeight, item.getThumbnailHeight());
|
||||
assertEquals("image/gif", item.getMimeType());
|
||||
assertEquals("gif", item.getExtension());
|
||||
assertEquals(AVAILABLE, item.getState());
|
||||
assertFalse(item.hasError());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -159,8 +158,8 @@ public class AttachmentRetrieverIntegrationTest {
|
||||
AttachmentHeader h = new AttachmentHeader(msgId, "image/jpeg");
|
||||
InputStream is = getAssetInputStream("libraw_error.jpg");
|
||||
Attachment a = new Attachment(h, is);
|
||||
AttachmentItem item = retriever.createAttachmentItem(a, true);
|
||||
assertEquals(ERROR, item.getState());
|
||||
AttachmentItem item = retriever.getAttachmentItem(a, true);
|
||||
assertTrue(item.hasError());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -168,14 +167,14 @@ public class AttachmentRetrieverIntegrationTest {
|
||||
AttachmentHeader h = new AttachmentHeader(msgId, "image/gif");
|
||||
InputStream is = getAssetInputStream("animated.gif");
|
||||
Attachment a = new Attachment(h, is);
|
||||
AttachmentItem item = retriever.createAttachmentItem(a, true);
|
||||
AttachmentItem item = retriever.getAttachmentItem(a, true);
|
||||
assertEquals(65535, item.getWidth());
|
||||
assertEquals(65535, item.getHeight());
|
||||
assertEquals(dimensions.maxWidth, item.getThumbnailWidth());
|
||||
assertEquals(dimensions.maxWidth, item.getThumbnailHeight());
|
||||
assertEquals("image/gif", item.getMimeType());
|
||||
assertEquals("gif", item.getExtension());
|
||||
assertEquals(AVAILABLE, item.getState());
|
||||
assertFalse(item.hasError());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -183,14 +182,14 @@ public class AttachmentRetrieverIntegrationTest {
|
||||
AttachmentHeader h = new AttachmentHeader(msgId, "image/gif");
|
||||
InputStream is = getAssetInputStream("animated2.gif");
|
||||
Attachment a = new Attachment(h, is);
|
||||
AttachmentItem item = retriever.createAttachmentItem(a, true);
|
||||
AttachmentItem item = retriever.getAttachmentItem(a, true);
|
||||
assertEquals(10000, item.getWidth());
|
||||
assertEquals(10000, item.getHeight());
|
||||
assertEquals(dimensions.maxWidth, item.getThumbnailWidth());
|
||||
assertEquals(dimensions.maxWidth, item.getThumbnailHeight());
|
||||
assertEquals("image/gif", item.getMimeType());
|
||||
assertEquals("gif", item.getExtension());
|
||||
assertEquals(AVAILABLE, item.getState());
|
||||
assertFalse(item.hasError());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -198,14 +197,14 @@ public class AttachmentRetrieverIntegrationTest {
|
||||
AttachmentHeader h = new AttachmentHeader(msgId, "image/gif");
|
||||
InputStream is = getAssetInputStream("error_large.gif");
|
||||
Attachment a = new Attachment(h, is);
|
||||
AttachmentItem item = retriever.createAttachmentItem(a, true);
|
||||
AttachmentItem item = retriever.getAttachmentItem(a, true);
|
||||
assertEquals(16384, item.getWidth());
|
||||
assertEquals(16384, item.getHeight());
|
||||
assertEquals(dimensions.maxWidth, item.getThumbnailWidth());
|
||||
assertEquals(dimensions.maxWidth, item.getThumbnailHeight());
|
||||
assertEquals("image/gif", item.getMimeType());
|
||||
assertEquals("gif", item.getExtension());
|
||||
assertEquals(AVAILABLE, item.getState());
|
||||
assertFalse(item.hasError());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -213,14 +212,14 @@ public class AttachmentRetrieverIntegrationTest {
|
||||
AttachmentHeader h = new AttachmentHeader(msgId, "image/jpeg");
|
||||
InputStream is = getAssetInputStream("error_high.jpg");
|
||||
Attachment a = new Attachment(h, is);
|
||||
AttachmentItem item = retriever.createAttachmentItem(a, true);
|
||||
AttachmentItem item = retriever.getAttachmentItem(a, true);
|
||||
assertEquals(1, item.getWidth());
|
||||
assertEquals(10000, item.getHeight());
|
||||
assertEquals(dimensions.minWidth, item.getThumbnailWidth());
|
||||
assertEquals(dimensions.maxHeight, item.getThumbnailHeight());
|
||||
assertEquals("image/jpeg", item.getMimeType());
|
||||
assertJpgOrJpeg(item.getExtension());
|
||||
assertEquals(AVAILABLE, item.getState());
|
||||
assertFalse(item.hasError());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -228,14 +227,14 @@ public class AttachmentRetrieverIntegrationTest {
|
||||
AttachmentHeader h = new AttachmentHeader(msgId, "image/jpeg");
|
||||
InputStream is = getAssetInputStream("error_wide.jpg");
|
||||
Attachment a = new Attachment(h, is);
|
||||
AttachmentItem item = retriever.createAttachmentItem(a, true);
|
||||
AttachmentItem item = retriever.getAttachmentItem(a, true);
|
||||
assertEquals(1920, item.getWidth());
|
||||
assertEquals(1, item.getHeight());
|
||||
assertEquals(dimensions.maxWidth, item.getThumbnailWidth());
|
||||
assertEquals(dimensions.minHeight, item.getThumbnailHeight());
|
||||
assertEquals("image/jpeg", item.getMimeType());
|
||||
assertJpgOrJpeg(item.getExtension());
|
||||
assertEquals(AVAILABLE, item.getState());
|
||||
assertFalse(item.hasError());
|
||||
}
|
||||
|
||||
private InputStream getAssetInputStream(String name) throws Exception {
|
||||
|
||||
@@ -1,46 +1,46 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
package="org.briarproject.briar">
|
||||
<manifest
|
||||
package="org.briarproject.briar"
|
||||
xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<uses-feature
|
||||
android:name="android.hardware.bluetooth"
|
||||
android:required="false" />
|
||||
android:required="false"/>
|
||||
<uses-feature
|
||||
android:name="android.hardware.camera"
|
||||
android:required="false" />
|
||||
android:required="false"/>
|
||||
<uses-feature
|
||||
android:name="android.hardware.touchscreen"
|
||||
android:required="false" />
|
||||
<uses-feature
|
||||
android:name="android.software.leanback"
|
||||
android:required="false" />
|
||||
android:required="false"/>
|
||||
<uses-feature android:name="android.software.leanback"
|
||||
android:required="false" />
|
||||
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
|
||||
<uses-permission android:name="android.permission.BLUETOOTH"/>
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
|
||||
<uses-permission android:name="android.permission.CAMERA"/>
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
|
||||
<!--suppress DeprecatedClassUsageInspection -->
|
||||
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
|
||||
<uses-permission android:name="android.permission.VIBRATE"/>
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK"/>
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
|
||||
|
||||
<uses-permission-sdk-23 android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
<uses-permission-sdk-23 android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
|
||||
<uses-permission-sdk-23 android:name="android.permission.USE_BIOMETRIC" />
|
||||
<uses-permission-sdk-23 android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission-sdk-23 android:name="android.permission.ACCESS_FINE_LOCATION"/>
|
||||
<uses-permission-sdk-23 android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
|
||||
<uses-permission-sdk-23 android:name="android.permission.USE_BIOMETRIC"/>
|
||||
<uses-permission-sdk-23 android:name="android.permission.FOREGROUND_SERVICE"/>
|
||||
|
||||
<application
|
||||
android:name="org.briarproject.briar.android.BriarApplicationImpl"
|
||||
android:allowBackup="false"
|
||||
android:banner="@mipmap/tv_banner"
|
||||
android:icon="@mipmap/ic_launcher_round"
|
||||
android:label="@string/app_name"
|
||||
android:logo="@mipmap/ic_launcher_round"
|
||||
android:banner="@mipmap/tv_banner"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/BriarTheme"
|
||||
tools:ignore="GoogleAppIndexingWarning,UnusedAttribute"
|
||||
@@ -50,8 +50,8 @@
|
||||
android:name="org.briarproject.briar.android.login.SignInReminderReceiver"
|
||||
android:exported="false">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED"/>
|
||||
<action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
@@ -59,13 +59,14 @@
|
||||
android:name="org.briarproject.briar.android.BriarService"
|
||||
android:exported="false">
|
||||
<intent-filter>
|
||||
<action android:name="org.briarproject.briar.android.BriarService" />
|
||||
<action android:name="org.briarproject.briar.android.BriarService"/>
|
||||
</intent-filter>
|
||||
</service>
|
||||
|
||||
<service
|
||||
android:name="org.briarproject.briar.android.NotificationCleanupService"
|
||||
android:exported="false"></service>
|
||||
android:exported="false">
|
||||
</service>
|
||||
|
||||
<activity
|
||||
android:name="org.briarproject.briar.android.reporting.DevReportActivity"
|
||||
@@ -75,29 +76,32 @@
|
||||
android:label="@string/crash_report_title"
|
||||
android:launchMode="singleInstance"
|
||||
android:theme="@style/BriarTheme.NoActionBar"
|
||||
android:windowSoftInputMode="adjustResize|stateHidden"></activity>
|
||||
android:windowSoftInputMode="adjustResize|stateHidden">
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name="org.briarproject.briar.android.splash.ExpiredActivity"
|
||||
android:label="@string/app_name"></activity>
|
||||
android:label="@string/app_name">
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name="org.briarproject.briar.android.login.StartupActivity"
|
||||
android:label="@string/app_name"></activity>
|
||||
android:label="@string/app_name">
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name="org.briarproject.briar.android.account.SetupActivity"
|
||||
android:label="@string/setup_title"
|
||||
android:windowSoftInputMode="adjustResize|stateAlwaysVisible"></activity>
|
||||
android:windowSoftInputMode="adjustResize|stateAlwaysVisible">
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name="org.briarproject.briar.android.splash.SplashScreenActivity"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/BriarTheme.NoActionBar">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
<action android:name="android.intent.action.MAIN"/>
|
||||
<category android:name="android.intent.category.LAUNCHER"/>
|
||||
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
@@ -107,17 +111,17 @@
|
||||
android:launchMode="singleTask"
|
||||
android:theme="@style/BriarTheme.NoActionBar">
|
||||
<intent-filter android:label="@string/add_contact_remotely_title_case">
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<action android:name="android.intent.action.VIEW"/>
|
||||
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<category android:name="android.intent.category.DEFAULT"/>
|
||||
<category android:name="android.intent.category.BROWSABLE"/>
|
||||
|
||||
<data android:scheme="briar" />
|
||||
<data android:scheme="briar"/>
|
||||
</intent-filter>
|
||||
<intent-filter android:label="@string/add_contact_remotely_title_case">
|
||||
<action android:name="android.intent.action.SEND" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<data android:mimeType="text/plain" />
|
||||
<action android:name="android.intent.action.SEND"/>
|
||||
<category android:name="android.intent.category.DEFAULT"/>
|
||||
<data android:mimeType="text/plain"/>
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
@@ -129,7 +133,7 @@
|
||||
android:windowSoftInputMode="adjustResize|stateUnchanged">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity" />
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -138,7 +142,7 @@
|
||||
android:theme="@style/BriarTheme.ActionBarOverlay">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.conversation.ConversationActivity" />
|
||||
android:value="org.briarproject.briar.android.conversation.ConversationActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -148,7 +152,7 @@
|
||||
android:windowSoftInputMode="adjustResize|stateAlwaysVisible">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity" />
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -159,7 +163,7 @@
|
||||
android:windowSoftInputMode="adjustResize|stateHidden">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity" />
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -168,7 +172,7 @@
|
||||
android:parentActivityName="org.briarproject.briar.android.navdrawer.NavDrawerActivity">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity" />
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -177,7 +181,7 @@
|
||||
android:parentActivityName="org.briarproject.briar.android.privategroup.conversation.GroupActivity">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.privategroup.conversation.GroupActivity" />
|
||||
android:value="org.briarproject.briar.android.privategroup.conversation.GroupActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -186,7 +190,7 @@
|
||||
android:parentActivityName="org.briarproject.briar.android.privategroup.conversation.GroupActivity">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.privategroup.conversation.GroupActivity" />
|
||||
android:value="org.briarproject.briar.android.privategroup.conversation.GroupActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -196,7 +200,7 @@
|
||||
android:windowSoftInputMode="adjustResize|stateHidden">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.privategroup.conversation.GroupActivity" />
|
||||
android:value="org.briarproject.briar.android.privategroup.conversation.GroupActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -205,7 +209,7 @@
|
||||
android:parentActivityName="org.briarproject.briar.android.navdrawer.NavDrawerActivity">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity" />
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -214,7 +218,7 @@
|
||||
android:parentActivityName="org.briarproject.briar.android.conversation.ConversationActivity">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.conversation.ConversationActivity" />
|
||||
android:value="org.briarproject.briar.android.conversation.ConversationActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -224,7 +228,7 @@
|
||||
android:windowSoftInputMode="adjustResize|stateAlwaysVisible">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity" />
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -235,7 +239,7 @@
|
||||
android:windowSoftInputMode="adjustResize|stateHidden">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity" />
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -245,7 +249,7 @@
|
||||
android:windowSoftInputMode="adjustResize|stateHidden">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.forum.ForumActivity" />
|
||||
android:value="org.briarproject.briar.android.forum.ForumActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -255,7 +259,7 @@
|
||||
android:windowSoftInputMode="adjustResize|stateHidden">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.blog.BlogActivity" />
|
||||
android:value="org.briarproject.briar.android.blog.BlogActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -264,7 +268,8 @@
|
||||
android:parentActivityName="org.briarproject.briar.android.forum.ForumActivity">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.forum.ForumActivity" />
|
||||
android:value="org.briarproject.briar.android.forum.ForumActivity"
|
||||
/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -273,7 +278,7 @@
|
||||
android:parentActivityName="org.briarproject.briar.android.blog.BlogActivity">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.blog.BlogActivity" />
|
||||
android:value="org.briarproject.briar.android.blog.BlogActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -282,7 +287,7 @@
|
||||
android:theme="@style/BriarTheme.NoActionBar">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity" />
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -292,7 +297,7 @@
|
||||
android:windowSoftInputMode="adjustResize|stateAlwaysVisible">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.blog.BlogActivity" />
|
||||
android:value="org.briarproject.briar.android.blog.BlogActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -302,7 +307,7 @@
|
||||
android:windowSoftInputMode="adjustResize|stateHidden">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.blog.BlogActivity" />
|
||||
android:value="org.briarproject.briar.android.blog.BlogActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -312,7 +317,7 @@
|
||||
android:windowSoftInputMode="adjustResize|stateAlwaysVisible">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity" />
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -321,7 +326,7 @@
|
||||
android:parentActivityName="org.briarproject.briar.android.navdrawer.NavDrawerActivity">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity" />
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -331,7 +336,7 @@
|
||||
android:theme="@style/BriarTheme.NoActionBar">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity" />
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -341,12 +346,13 @@
|
||||
android:windowSoftInputMode="adjustResize|stateHidden">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.conversation.ConversationActivity" />
|
||||
android:value="org.briarproject.briar.android.conversation.ConversationActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name="org.briarproject.briar.android.StartupFailureActivity"
|
||||
android:label="@string/startup_failed_activity_title"></activity>
|
||||
android:label="@string/startup_failed_activity_title">
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name="org.briarproject.briar.android.settings.SettingsActivity"
|
||||
@@ -355,22 +361,13 @@
|
||||
android:permission="android.permission.READ_NETWORK_USAGE_HISTORY">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity" />
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity"/>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MANAGE_NETWORK_USAGE" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<action android:name="android.intent.action.MANAGE_NETWORK_USAGE"/>
|
||||
<category android:name="android.intent.category.DEFAULT"/>
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name="org.briarproject.briar.android.navdrawer.TransportsActivity"
|
||||
android:label="@string/network_settings_title"
|
||||
android:parentActivityName="org.briarproject.briar.android.navdrawer.NavDrawerActivity">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.navdrawer.NavDrawerActivity" />
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name="org.briarproject.briar.android.login.ChangePasswordActivity"
|
||||
android:label="@string/change_password"
|
||||
@@ -378,7 +375,7 @@
|
||||
android:windowSoftInputMode="adjustResize|stateAlwaysVisible">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.settings.SettingsActivity" />
|
||||
android:value="org.briarproject.briar.android.settings.SettingsActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -387,7 +384,7 @@
|
||||
android:parentActivityName="org.briarproject.briar.android.settings.SettingsActivity">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.settings.SettingsActivity" />
|
||||
android:value="org.briarproject.briar.android.settings.SettingsActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -396,7 +393,7 @@
|
||||
android:parentActivityName="org.briarproject.briar.android.settings.SettingsActivity">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value="org.briarproject.briar.android.settings.SettingsActivity" />
|
||||
android:value="org.briarproject.briar.android.settings.SettingsActivity"/>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -405,35 +402,37 @@
|
||||
android:theme="@style/TranslucentTheme">
|
||||
<!-- this can never have launchMode singleTask or singleInstance! -->
|
||||
<intent-filter>
|
||||
<action android:name="info.guardianproject.panic.action.TRIGGER" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<action android:name="info.guardianproject.panic.action.TRIGGER"/>
|
||||
<category android:name="android.intent.category.DEFAULT"/>
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name="org.briarproject.briar.android.logout.ExitActivity"
|
||||
android:theme="@android:style/Theme.NoDisplay"></activity>
|
||||
android:theme="@android:style/Theme.NoDisplay">
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".android.logout.HideUiActivity"
|
||||
android:theme="@android:style/Theme.NoDisplay"></activity>
|
||||
android:theme="@android:style/Theme.NoDisplay">
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".android.account.UnlockActivity"
|
||||
android:label="@string/lock_unlock"
|
||||
android:launchMode="singleTask"
|
||||
android:theme="@style/BriarTheme.NoActionBar" />
|
||||
android:theme="@style/BriarTheme.NoActionBar"/>
|
||||
|
||||
<activity
|
||||
android:name=".android.contact.add.remote.AddContactActivity"
|
||||
android:label="@string/add_contact_remotely_title_case"
|
||||
android:theme="@style/BriarTheme"
|
||||
android:windowSoftInputMode="adjustResize|stateHidden" />
|
||||
android:windowSoftInputMode="adjustResize|stateHidden"/>
|
||||
|
||||
<activity
|
||||
android:name=".android.contact.add.remote.PendingContactListActivity"
|
||||
android:label="@string/pending_contact_requests"
|
||||
android:theme="@style/BriarTheme" />
|
||||
android:theme="@style/BriarTheme"/>
|
||||
|
||||
</application>
|
||||
</manifest>
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 9.9 KiB |
@@ -0,0 +1,93 @@
|
||||
package org.briarproject.briar.android.account;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.widget.Toast;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
|
||||
import static android.os.Environment.DIRECTORY_DOWNLOADS;
|
||||
import static android.os.Environment.getExternalStoragePublicDirectory;
|
||||
import static android.widget.Toast.LENGTH_LONG;
|
||||
import static java.util.logging.Level.WARNING;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
import static org.briarproject.bramble.util.IoUtils.copyAndClose;
|
||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||
import static org.briarproject.briar.android.BriarApplication.ENTRY_ACTIVITY;
|
||||
import static org.briarproject.briar.android.navdrawer.NavDrawerActivity.SIGN_OUT_URI;
|
||||
|
||||
public class AccountUtils {
|
||||
|
||||
private static final Logger LOG = getLogger(AccountUtils.class.getName());
|
||||
|
||||
private static final String[] BACKUP_DIRS =
|
||||
{"app_db", "app_key", "shared_prefs"};
|
||||
|
||||
public static void exportAccount(Context ctx) {
|
||||
try {
|
||||
File dataDir = getDataDir(ctx);
|
||||
File backupDir = getBackupDir(ctx);
|
||||
for (String name : BACKUP_DIRS) {
|
||||
copyRecursively(new File(dataDir, name),
|
||||
new File(backupDir, name));
|
||||
}
|
||||
Toast.makeText(ctx, "Account exported to "
|
||||
+ backupDir.getCanonicalPath(), LENGTH_LONG).show();
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
Toast.makeText(ctx, "Export failed", LENGTH_LONG).show();
|
||||
}
|
||||
}
|
||||
|
||||
public static void importAccount(Context ctx) {
|
||||
try {
|
||||
File dataDir = getDataDir(ctx);
|
||||
File backupDir = getBackupDir(ctx);
|
||||
for (String name : BACKUP_DIRS) {
|
||||
copyRecursively(new File(backupDir, name),
|
||||
new File(dataDir, name));
|
||||
}
|
||||
Toast.makeText(ctx, "Account imported from "
|
||||
+ backupDir.getCanonicalPath(), LENGTH_LONG).show();
|
||||
Intent intent = new Intent(ctx, ENTRY_ACTIVITY);
|
||||
intent.setFlags(FLAG_ACTIVITY_CLEAR_TOP);
|
||||
intent.setData(SIGN_OUT_URI);
|
||||
ctx.startActivity(intent);
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
Toast.makeText(ctx, "Import failed", LENGTH_LONG).show();
|
||||
}
|
||||
}
|
||||
|
||||
private static File getDataDir(Context ctx) {
|
||||
return new File(ctx.getApplicationInfo().dataDir);
|
||||
}
|
||||
|
||||
private static File getBackupDir(Context ctx) {
|
||||
File downloads = getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS);
|
||||
return new File(downloads, ctx.getPackageName());
|
||||
}
|
||||
|
||||
private static void copyRecursively(File src, File dest)
|
||||
throws IOException {
|
||||
if (src.isDirectory()) {
|
||||
if (!dest.isDirectory() && !dest.mkdirs()) throw new IOException();
|
||||
File[] children = src.listFiles();
|
||||
if (children == null) throw new IOException();
|
||||
for (File child : children) {
|
||||
copyRecursively(child, new File(dest, child.getName()));
|
||||
}
|
||||
} else if (src.isFile()) {
|
||||
InputStream in = new FileInputStream(src);
|
||||
OutputStream out = new FileOutputStream(dest);
|
||||
copyAndClose(in, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -117,24 +117,14 @@ public class UnlockActivity extends BaseActivity {
|
||||
|
||||
@RequiresApi(api = 28)
|
||||
private void requestFingerprintUnlock() {
|
||||
BiometricPrompt biometricPrompt;
|
||||
if (SDK_INT >= 29) {
|
||||
biometricPrompt = new Builder(this)
|
||||
.setTitle(getString(R.string.lock_unlock))
|
||||
.setDescription(getString(
|
||||
R.string.lock_unlock_fingerprint_description))
|
||||
.setDeviceCredentialAllowed(true)
|
||||
.build();
|
||||
} else {
|
||||
biometricPrompt = new Builder(this)
|
||||
.setTitle(getString(R.string.lock_unlock))
|
||||
.setDescription(getString(
|
||||
R.string.lock_unlock_fingerprint_description))
|
||||
.setNegativeButton(getString(R.string.lock_unlock_password),
|
||||
getMainExecutor(),
|
||||
(dialog, which) -> requestKeyguardUnlock())
|
||||
.build();
|
||||
}
|
||||
BiometricPrompt biometricPrompt = new Builder(this)
|
||||
.setTitle(getString(R.string.lock_unlock))
|
||||
.setDescription(
|
||||
getString(R.string.lock_unlock_fingerprint_description))
|
||||
.setNegativeButton(getString(R.string.lock_unlock_password),
|
||||
getMainExecutor(),
|
||||
(dialog, which) -> requestKeyguardUnlock())
|
||||
.build();
|
||||
CancellationSignal signal = new CancellationSignal();
|
||||
AuthenticationCallback callback = new AuthenticationCallback() {
|
||||
@Override
|
||||
|
||||
@@ -47,7 +47,6 @@ import org.briarproject.briar.android.login.OpenDatabaseFragment;
|
||||
import org.briarproject.briar.android.login.PasswordFragment;
|
||||
import org.briarproject.briar.android.login.StartupActivity;
|
||||
import org.briarproject.briar.android.navdrawer.NavDrawerActivity;
|
||||
import org.briarproject.briar.android.navdrawer.TransportsActivity;
|
||||
import org.briarproject.briar.android.panic.PanicPreferencesActivity;
|
||||
import org.briarproject.briar.android.panic.PanicResponderActivity;
|
||||
import org.briarproject.briar.android.privategroup.conversation.GroupActivity;
|
||||
@@ -164,8 +163,6 @@ public interface ActivityComponent {
|
||||
|
||||
void inject(SettingsActivity activity);
|
||||
|
||||
void inject(TransportsActivity activity);
|
||||
|
||||
void inject(TestDataActivity activity);
|
||||
|
||||
void inject(ChangePasswordActivity activity);
|
||||
|
||||
@@ -34,7 +34,6 @@ 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;
|
||||
import static org.briarproject.briar.android.attachment.AttachmentItem.State.ERROR;
|
||||
import static org.briarproject.briar.android.util.UiUtils.observeForeverOnce;
|
||||
import static org.briarproject.briar.api.messaging.MessagingConstants.MAX_IMAGE_SIZE;
|
||||
|
||||
@@ -76,12 +75,8 @@ class AttachmentCreatorImpl implements AttachmentCreator {
|
||||
@UiThread
|
||||
public LiveData<AttachmentResult> storeAttachments(
|
||||
LiveData<GroupId> groupId, Collection<Uri> newUris) {
|
||||
if (task != null || result != null || !uris.isEmpty()) {
|
||||
if (task != null) LOG.warning("Task already exists!");
|
||||
if (result != null) LOG.warning("Result already exists!");
|
||||
if (!uris.isEmpty()) LOG.warning("Uris available: " + uris);
|
||||
if (task != null || result != null || !uris.isEmpty())
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
MutableLiveData<AttachmentResult> result = new MutableLiveData<>();
|
||||
this.result = result;
|
||||
uris.addAll(newUris);
|
||||
@@ -100,12 +95,8 @@ class AttachmentCreatorImpl implements AttachmentCreator {
|
||||
@UiThread
|
||||
public LiveData<AttachmentResult> getLiveAttachments() {
|
||||
MutableLiveData<AttachmentResult> result = this.result;
|
||||
if (task == null || result == null || uris.isEmpty()) {
|
||||
if (task == null) LOG.warning("No Task!");
|
||||
if (result == null) LOG.warning("No Result!");
|
||||
if (uris.isEmpty()) LOG.warning("Uris empty!");
|
||||
if (task == null || result == null || uris.isEmpty())
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
// A task is already running. It will update the result LiveData.
|
||||
// So nothing more to do here.
|
||||
return result;
|
||||
@@ -118,8 +109,8 @@ class AttachmentCreatorImpl implements AttachmentCreator {
|
||||
// get and cache AttachmentItem for ImagePreview
|
||||
try {
|
||||
Attachment a = retriever.getMessageAttachment(h);
|
||||
AttachmentItem item = retriever.createAttachmentItem(a, needsSize);
|
||||
if (item.getState() == ERROR) throw new IOException();
|
||||
AttachmentItem item = retriever.getAttachmentItem(a, needsSize);
|
||||
if (item.hasError()) throw new IOException();
|
||||
AttachmentItemResult itemResult =
|
||||
new AttachmentItemResult(uri, item);
|
||||
itemResults.add(itemResult);
|
||||
@@ -176,13 +167,21 @@ class AttachmentCreatorImpl implements AttachmentCreator {
|
||||
@Override
|
||||
@UiThread
|
||||
public void onAttachmentsSent(MessageId id) {
|
||||
List<AttachmentItem> items = new ArrayList<>(itemResults.size());
|
||||
for (AttachmentItemResult itemResult : itemResults) {
|
||||
// check if we are trying to send attachment items with errors
|
||||
if (itemResult.getItem() == null) throw new IllegalStateException();
|
||||
items.add(itemResult.getItem());
|
||||
}
|
||||
retriever.cachePut(id, items);
|
||||
resetState();
|
||||
}
|
||||
|
||||
@Override
|
||||
@UiThread
|
||||
public void cancel() {
|
||||
if (task != null) task.cancel();
|
||||
if (task == null) throw new AssertionError();
|
||||
task.cancel();
|
||||
deleteUnsentAttachments();
|
||||
resetState();
|
||||
}
|
||||
|
||||
@@ -7,33 +7,24 @@ import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.sync.MessageId;
|
||||
import org.briarproject.briar.api.messaging.AttachmentHeader;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import static java.lang.System.arraycopy;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
import static org.briarproject.bramble.util.StringUtils.toHexString;
|
||||
import static org.briarproject.briar.android.attachment.AttachmentItem.State.LOADING;
|
||||
import static org.briarproject.briar.android.attachment.AttachmentItem.State.MISSING;
|
||||
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
public class AttachmentItem implements Parcelable {
|
||||
|
||||
public enum State {
|
||||
LOADING, MISSING, AVAILABLE, ERROR;
|
||||
|
||||
public boolean isFinal() {
|
||||
return this == AVAILABLE || this == ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private final AttachmentHeader header;
|
||||
private final int width, height;
|
||||
private final String extension;
|
||||
private final int thumbnailWidth, thumbnailHeight;
|
||||
private final State state;
|
||||
private final boolean hasError;
|
||||
private final long instanceId;
|
||||
|
||||
public static final Creator<AttachmentItem> CREATOR =
|
||||
new Creator<AttachmentItem>() {
|
||||
@@ -48,33 +39,19 @@ public class AttachmentItem implements Parcelable {
|
||||
}
|
||||
};
|
||||
|
||||
private static final AtomicLong NEXT_INSTANCE_ID = new AtomicLong(0);
|
||||
|
||||
AttachmentItem(AttachmentHeader header, int width, int height,
|
||||
String extension, int thumbnailWidth, int thumbnailHeight,
|
||||
State state) {
|
||||
boolean hasError) {
|
||||
this.header = header;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.extension = extension;
|
||||
this.thumbnailWidth = thumbnailWidth;
|
||||
this.thumbnailHeight = thumbnailHeight;
|
||||
this.state = state;
|
||||
}
|
||||
|
||||
/**
|
||||
* Use only for {@link State MISSING} or {@link State LOADING} items.
|
||||
*/
|
||||
AttachmentItem(AttachmentHeader header, int width, int height,
|
||||
State state) {
|
||||
this(header, width, height, "", width, height, state);
|
||||
if (state != MISSING && state != LOADING)
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
/**
|
||||
* Use when the item does not need a size.
|
||||
*/
|
||||
AttachmentItem(AttachmentHeader header, String extension, State state) {
|
||||
this(header, 0, 0, extension, 0, 0, state);
|
||||
this.hasError = hasError;
|
||||
instanceId = NEXT_INSTANCE_ID.getAndIncrement();
|
||||
}
|
||||
|
||||
protected AttachmentItem(Parcel in) {
|
||||
@@ -87,7 +64,8 @@ public class AttachmentItem implements Parcelable {
|
||||
extension = requireNonNull(in.readString());
|
||||
thumbnailWidth = in.readInt();
|
||||
thumbnailHeight = in.readInt();
|
||||
state = State.valueOf(requireNonNull(in.readString()));
|
||||
hasError = in.readByte() != 0;
|
||||
instanceId = in.readLong();
|
||||
header = new AttachmentHeader(messageId, mimeType);
|
||||
}
|
||||
|
||||
@@ -123,16 +101,12 @@ public class AttachmentItem implements Parcelable {
|
||||
return thumbnailHeight;
|
||||
}
|
||||
|
||||
public State getState() {
|
||||
return state;
|
||||
public boolean hasError() {
|
||||
return hasError;
|
||||
}
|
||||
|
||||
public String getTransitionName(MessageId conversationItemId) {
|
||||
int len = MessageId.LENGTH;
|
||||
byte[] instanceId = new byte[len * 2];
|
||||
arraycopy(header.getMessageId().getBytes(), 0, instanceId, 0, len);
|
||||
arraycopy(conversationItemId.getBytes(), 0, instanceId, len, len);
|
||||
return toHexString(instanceId);
|
||||
public String getTransitionName() {
|
||||
return String.valueOf(instanceId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -149,23 +123,14 @@ public class AttachmentItem implements Parcelable {
|
||||
dest.writeString(extension);
|
||||
dest.writeInt(thumbnailWidth);
|
||||
dest.writeInt(thumbnailHeight);
|
||||
dest.writeString(state.name());
|
||||
dest.writeByte((byte) (hasError ? 1 : 0));
|
||||
dest.writeLong(instanceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* This is used to identity if two items are the same,
|
||||
* irrespective of their state or size.
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(@Nullable Object o) {
|
||||
return o instanceof AttachmentItem &&
|
||||
header.getMessageId().equals(
|
||||
((AttachmentItem) o).header.getMessageId()
|
||||
);
|
||||
instanceId == ((AttachmentItem) o).instanceId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return header.getMessageId().hashCode();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,63 +1,29 @@
|
||||
package org.briarproject.briar.android.attachment;
|
||||
|
||||
import org.briarproject.bramble.api.db.DatabaseExecutor;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.sync.MessageId;
|
||||
import org.briarproject.briar.api.messaging.Attachment;
|
||||
import org.briarproject.briar.api.messaging.AttachmentHeader;
|
||||
import org.briarproject.briar.api.messaging.PrivateMessageHeader;
|
||||
import org.briarproject.briar.api.messaging.event.AttachmentReceivedEvent;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
|
||||
import androidx.lifecycle.LiveData;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
@NotNullByDefault
|
||||
public interface AttachmentRetriever {
|
||||
|
||||
@DatabaseExecutor
|
||||
void cachePut(MessageId messageId, List<AttachmentItem> attachments);
|
||||
|
||||
@Nullable
|
||||
List<AttachmentItem> cacheGet(MessageId messageId);
|
||||
|
||||
Attachment getMessageAttachment(AttachmentHeader h) throws DbException;
|
||||
|
||||
/**
|
||||
* Returns a list of observable {@link LiveData}
|
||||
* that get updated as the state of their {@link AttachmentItem}s changes.
|
||||
*/
|
||||
List<LiveData<AttachmentItem>> getAttachmentItems(
|
||||
PrivateMessageHeader messageHeader);
|
||||
|
||||
/**
|
||||
* Retrieves item size and adds the item to the cache, if available.
|
||||
* <p>
|
||||
* Use this to eagerly load the attachment size before it gets displayed.
|
||||
* This is needed for messages containing a single attachment.
|
||||
* Messages with more than one attachment use a standard size.
|
||||
*/
|
||||
@DatabaseExecutor
|
||||
void cacheAttachmentItemWithSize(MessageId conversationMessageId,
|
||||
AttachmentHeader h) throws DbException;
|
||||
|
||||
/**
|
||||
* Creates an {@link AttachmentItem} from the {@link Attachment}'s
|
||||
* {@link InputStream} which will be closed when this method returns.
|
||||
*/
|
||||
AttachmentItem createAttachmentItem(Attachment a, boolean needsSize);
|
||||
|
||||
/**
|
||||
* Loads an {@link AttachmentItem}
|
||||
* that arrived via an {@link AttachmentReceivedEvent}
|
||||
* and notifies the associated {@link LiveData}.
|
||||
*
|
||||
* Note that you need to call {@link #getAttachmentItems(PrivateMessageHeader)}
|
||||
* first to get the LiveData.
|
||||
*
|
||||
* It is possible that no LiveData is available,
|
||||
* because the message of the AttachmentItem did not arrive, yet.
|
||||
* In this case, the load wil be deferred until the message arrives.
|
||||
*/
|
||||
@DatabaseExecutor
|
||||
void loadAttachmentItem(MessageId attachmentId);
|
||||
|
||||
AttachmentItem getAttachmentItem(Attachment a, boolean needsSize);
|
||||
}
|
||||
|
||||
@@ -1,39 +1,25 @@
|
||||
package org.briarproject.briar.android.attachment;
|
||||
|
||||
import org.briarproject.bramble.api.db.DatabaseExecutor;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
import org.briarproject.bramble.api.db.NoSuchMessageException;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.sync.MessageId;
|
||||
import org.briarproject.briar.android.attachment.AttachmentItem.State;
|
||||
import org.briarproject.briar.api.messaging.Attachment;
|
||||
import org.briarproject.briar.api.messaging.AttachmentHeader;
|
||||
import org.briarproject.briar.api.messaging.MessagingManager;
|
||||
import org.briarproject.briar.api.messaging.PrivateMessageHeader;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
import static java.util.logging.Level.WARNING;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
import static org.briarproject.bramble.util.IoUtils.tryToClose;
|
||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||
import static org.briarproject.briar.android.attachment.AttachmentItem.State.AVAILABLE;
|
||||
import static org.briarproject.briar.android.attachment.AttachmentItem.State.ERROR;
|
||||
import static org.briarproject.briar.android.attachment.AttachmentItem.State.LOADING;
|
||||
import static org.briarproject.briar.android.attachment.AttachmentItem.State.MISSING;
|
||||
|
||||
@NotNullByDefault
|
||||
class AttachmentRetrieverImpl implements AttachmentRetriever {
|
||||
@@ -41,8 +27,6 @@ class AttachmentRetrieverImpl implements AttachmentRetriever {
|
||||
private static final Logger LOG =
|
||||
getLogger(AttachmentRetrieverImpl.class.getName());
|
||||
|
||||
@DatabaseExecutor
|
||||
private final Executor dbExecutor;
|
||||
private final MessagingManager messagingManager;
|
||||
private final ImageHelper imageHelper;
|
||||
private final ImageSizeCalculator imageSizeCalculator;
|
||||
@@ -50,17 +34,13 @@ class AttachmentRetrieverImpl implements AttachmentRetriever {
|
||||
private final int minWidth, maxWidth;
|
||||
private final int minHeight, maxHeight;
|
||||
|
||||
private final ConcurrentMap<MessageId, MutableLiveData<AttachmentItem>>
|
||||
itemsWithSize = new ConcurrentHashMap<>();
|
||||
private final ConcurrentMap<MessageId, MutableLiveData<AttachmentItem>>
|
||||
itemsWithoutSize = new ConcurrentHashMap<>();
|
||||
private final Map<MessageId, List<AttachmentItem>> attachmentCache =
|
||||
new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
AttachmentRetrieverImpl(@DatabaseExecutor Executor dbExecutor,
|
||||
MessagingManager messagingManager,
|
||||
AttachmentRetrieverImpl(MessagingManager messagingManager,
|
||||
AttachmentDimensions dimensions, ImageHelper imageHelper,
|
||||
ImageSizeCalculator imageSizeCalculator) {
|
||||
this.dbExecutor = dbExecutor;
|
||||
this.messagingManager = messagingManager;
|
||||
this.imageHelper = imageHelper;
|
||||
this.imageSizeCalculator = imageSizeCalculator;
|
||||
@@ -72,143 +52,40 @@ class AttachmentRetrieverImpl implements AttachmentRetriever {
|
||||
}
|
||||
|
||||
@Override
|
||||
@DatabaseExecutor
|
||||
public void cachePut(MessageId messageId,
|
||||
List<AttachmentItem> attachments) {
|
||||
attachmentCache.put(messageId, attachments);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public List<AttachmentItem> cacheGet(MessageId messageId) {
|
||||
return attachmentCache.get(messageId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Attachment getMessageAttachment(AttachmentHeader h)
|
||||
throws DbException {
|
||||
return messagingManager.getAttachment(h);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<LiveData<AttachmentItem>> getAttachmentItems(
|
||||
PrivateMessageHeader messageHeader) {
|
||||
List<AttachmentHeader> headers = messageHeader.getAttachmentHeaders();
|
||||
List<LiveData<AttachmentItem>> items = new ArrayList<>(headers.size());
|
||||
boolean needsSize = headers.size() == 1;
|
||||
for (AttachmentHeader h : headers) {
|
||||
// try cache for existing item live data
|
||||
MutableLiveData<AttachmentItem> liveData;
|
||||
if (needsSize) liveData = itemsWithSize.get(h.getMessageId());
|
||||
else {
|
||||
// try items with size first, as they work as well
|
||||
liveData = itemsWithSize.get(h.getMessageId());
|
||||
if (liveData == null)
|
||||
liveData = itemsWithoutSize.get(h.getMessageId());
|
||||
}
|
||||
|
||||
// create new live data with LOADING item if cache miss
|
||||
if (liveData == null) {
|
||||
AttachmentItem item = new AttachmentItem(h,
|
||||
defaultSize, defaultSize, LOADING);
|
||||
liveData = new MutableLiveData<>(item);
|
||||
// add new LiveData to cache, checking for concurrent updates
|
||||
MutableLiveData<AttachmentItem> oldLiveData;
|
||||
if (needsSize) {
|
||||
oldLiveData = itemsWithSize.putIfAbsent(h.getMessageId(),
|
||||
liveData);
|
||||
} else {
|
||||
oldLiveData = itemsWithoutSize.putIfAbsent(h.getMessageId(),
|
||||
liveData);
|
||||
}
|
||||
if (oldLiveData == null) {
|
||||
// kick-off loading of attachment, will post to live data
|
||||
MutableLiveData<AttachmentItem> finalLiveData = liveData;
|
||||
dbExecutor.execute(() ->
|
||||
loadAttachmentItem(h, needsSize, finalLiveData));
|
||||
} else {
|
||||
// Concurrent cache update - use the existing live data
|
||||
liveData = oldLiveData;
|
||||
}
|
||||
}
|
||||
items.add(liveData);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
@Override
|
||||
@DatabaseExecutor
|
||||
public void cacheAttachmentItemWithSize(MessageId conversationMessageId,
|
||||
AttachmentHeader h) throws DbException {
|
||||
// If a live data is already cached we don't need to do anything
|
||||
if (itemsWithSize.containsKey(h.getMessageId())) return;
|
||||
try {
|
||||
Attachment a = messagingManager.getAttachment(h);
|
||||
AttachmentItem item = createAttachmentItem(a, true);
|
||||
MutableLiveData<AttachmentItem> liveData =
|
||||
new MutableLiveData<>(item);
|
||||
// If a live data was concurrently cached, don't replace it
|
||||
itemsWithSize.putIfAbsent(h.getMessageId(), liveData);
|
||||
} catch (NoSuchMessageException e) {
|
||||
LOG.info("Attachment not received yet");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@DatabaseExecutor
|
||||
public void loadAttachmentItem(MessageId attachmentId) {
|
||||
// try to find LiveData for attachment in both caches
|
||||
MutableLiveData<AttachmentItem> liveData;
|
||||
boolean needsSize = true;
|
||||
liveData = itemsWithSize.get(attachmentId);
|
||||
if (liveData == null) {
|
||||
needsSize = false;
|
||||
liveData = itemsWithoutSize.get(attachmentId);
|
||||
}
|
||||
|
||||
// If no LiveData for the attachment exists,
|
||||
// its message did not yet arrive and we can ignore it for now.
|
||||
if (liveData == null) return;
|
||||
|
||||
// actually load the attachment item
|
||||
AttachmentHeader h = requireNonNull(liveData.getValue()).getHeader();
|
||||
loadAttachmentItem(h, needsSize, liveData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads an {@link AttachmentItem} from the database
|
||||
* and notifies the given {@link LiveData}.
|
||||
*/
|
||||
@DatabaseExecutor
|
||||
private void loadAttachmentItem(AttachmentHeader h, boolean needsSize,
|
||||
MutableLiveData<AttachmentItem> liveData) {
|
||||
Attachment a;
|
||||
AttachmentItem item;
|
||||
try {
|
||||
a = messagingManager.getAttachment(h);
|
||||
item = createAttachmentItem(a, needsSize);
|
||||
} catch (NoSuchMessageException e) {
|
||||
LOG.info("Attachment not received yet");
|
||||
item = new AttachmentItem(h, defaultSize, defaultSize, MISSING);
|
||||
} catch (DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
item = new AttachmentItem(h, "", ERROR);
|
||||
}
|
||||
liveData.postValue(item);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttachmentItem createAttachmentItem(Attachment a,
|
||||
boolean needsSize) {
|
||||
AttachmentItem item;
|
||||
public AttachmentItem getAttachmentItem(Attachment a, boolean needsSize) {
|
||||
AttachmentHeader h = a.getHeader();
|
||||
if (needsSize) {
|
||||
InputStream is = new BufferedInputStream(a.getStream());
|
||||
Size size = imageSizeCalculator.getSize(is, h.getContentType());
|
||||
tryToClose(is, LOG, WARNING);
|
||||
item = createAttachmentItem(h, size);
|
||||
} else {
|
||||
if (!needsSize) {
|
||||
String extension =
|
||||
imageHelper.getExtensionFromMimeType(h.getContentType());
|
||||
State state = AVAILABLE;
|
||||
boolean hasError = false;
|
||||
if (extension == null) {
|
||||
extension = "";
|
||||
state = ERROR;
|
||||
hasError = true;
|
||||
}
|
||||
item = new AttachmentItem(h, extension, state);
|
||||
return new AttachmentItem(h, 0, 0, extension, 0, 0, hasError);
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
private AttachmentItem createAttachmentItem(AttachmentHeader h, Size size) {
|
||||
InputStream is = new BufferedInputStream(a.getStream());
|
||||
Size size = imageSizeCalculator.getSize(is, h.getContentType());
|
||||
|
||||
// calculate thumbnail size
|
||||
Size thumbnailSize = new Size(defaultSize, defaultSize, size.mimeType);
|
||||
if (!size.error) {
|
||||
@@ -227,9 +104,8 @@ class AttachmentRetrieverImpl implements AttachmentRetriever {
|
||||
hasError = true;
|
||||
}
|
||||
if (extension == null) extension = "";
|
||||
State state = hasError ? ERROR : AVAILABLE;
|
||||
return new AttachmentItem(h, size.width, size.height,
|
||||
extension, thumbnailSize.width, thumbnailSize.height, state);
|
||||
return new AttachmentItem(h, size.width, size.height, extension,
|
||||
thumbnailSize.width, thumbnailSize.height, hasError);
|
||||
}
|
||||
|
||||
private Size getThumbnailSize(int width, int height, String mimeType) {
|
||||
|
||||
@@ -28,6 +28,7 @@ import org.briarproject.bramble.api.contact.event.ContactRemovedEvent;
|
||||
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.db.NoSuchMessageException;
|
||||
import org.briarproject.bramble.api.event.Event;
|
||||
import org.briarproject.bramble.api.event.EventBus;
|
||||
import org.briarproject.bramble.api.event.EventListener;
|
||||
@@ -64,16 +65,17 @@ import org.briarproject.briar.api.client.ProtocolStateException;
|
||||
import org.briarproject.briar.api.client.SessionId;
|
||||
import org.briarproject.briar.api.conversation.ConversationManager;
|
||||
import org.briarproject.briar.api.conversation.ConversationMessageHeader;
|
||||
import org.briarproject.briar.api.conversation.ConversationMessageVisitor;
|
||||
import org.briarproject.briar.api.conversation.ConversationRequest;
|
||||
import org.briarproject.briar.api.conversation.ConversationResponse;
|
||||
import org.briarproject.briar.api.conversation.DeletionResult;
|
||||
import org.briarproject.briar.api.conversation.event.ConversationMessageReceivedEvent;
|
||||
import org.briarproject.briar.api.forum.ForumSharingManager;
|
||||
import org.briarproject.briar.api.introduction.IntroductionManager;
|
||||
import org.briarproject.briar.api.messaging.Attachment;
|
||||
import org.briarproject.briar.api.messaging.AttachmentHeader;
|
||||
import org.briarproject.briar.api.messaging.MessagingManager;
|
||||
import org.briarproject.briar.api.messaging.PrivateMessageHeader;
|
||||
import org.briarproject.briar.api.messaging.event.AttachmentReceivedEvent;
|
||||
import org.briarproject.briar.api.privategroup.invitation.GroupInvitationManager;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@@ -95,7 +97,6 @@ import androidx.appcompat.widget.Toolbar;
|
||||
import androidx.core.app.ActivityCompat;
|
||||
import androidx.core.app.ActivityOptionsCompat;
|
||||
import androidx.core.content.ContextCompat;
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.lifecycle.Observer;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
import androidx.lifecycle.ViewModelProviders;
|
||||
@@ -117,6 +118,8 @@ import static androidx.core.app.ActivityOptionsCompat.makeSceneTransitionAnimati
|
||||
import static androidx.core.view.ViewCompat.setTransitionName;
|
||||
import static androidx.lifecycle.Lifecycle.State.STARTED;
|
||||
import static androidx.recyclerview.widget.SortedList.INVALID_POSITION;
|
||||
import static java.util.Collections.emptyList;
|
||||
import static java.util.Collections.singletonList;
|
||||
import static java.util.Collections.sort;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
import static java.util.logging.Level.INFO;
|
||||
@@ -133,7 +136,6 @@ import static org.briarproject.briar.android.activity.RequestCodes.REQUEST_INTRO
|
||||
import static org.briarproject.briar.android.conversation.ImageActivity.ATTACHMENTS;
|
||||
import static org.briarproject.briar.android.conversation.ImageActivity.ATTACHMENT_POSITION;
|
||||
import static org.briarproject.briar.android.conversation.ImageActivity.DATE;
|
||||
import static org.briarproject.briar.android.conversation.ImageActivity.ITEM_ID;
|
||||
import static org.briarproject.briar.android.conversation.ImageActivity.NAME;
|
||||
import static org.briarproject.briar.android.util.UiUtils.getAvatarTransitionName;
|
||||
import static org.briarproject.briar.android.util.UiUtils.getBulbTransitionName;
|
||||
@@ -183,6 +185,8 @@ public class ConversationActivity extends BriarActivity
|
||||
volatile GroupInvitationManager groupInvitationManager;
|
||||
|
||||
private final Map<MessageId, String> textCache = new ConcurrentHashMap<>();
|
||||
private final Map<MessageId, PrivateMessageHeader> missingAttachments =
|
||||
new ConcurrentHashMap<>();
|
||||
private final Observer<String> contactNameObserver = name -> {
|
||||
requireNonNull(name);
|
||||
loadMessages();
|
||||
@@ -536,7 +540,6 @@ public class ConversationActivity extends BriarActivity
|
||||
});
|
||||
}
|
||||
|
||||
@DatabaseExecutor
|
||||
private void eagerlyLoadMessageSize(PrivateMessageHeader h) {
|
||||
try {
|
||||
MessageId id = h.getId();
|
||||
@@ -553,11 +556,21 @@ public class ConversationActivity extends BriarActivity
|
||||
// images we use a grid so the size is fixed
|
||||
List<AttachmentHeader> headers = h.getAttachmentHeaders();
|
||||
if (headers.size() == 1) {
|
||||
LOG.info("Eagerly loading image size for latest message");
|
||||
AttachmentHeader header = headers.get(0);
|
||||
// get the item to retrieve its size
|
||||
attachmentRetriever
|
||||
.cacheAttachmentItemWithSize(h.getId(), header);
|
||||
List<AttachmentItem> items = attachmentRetriever.cacheGet(id);
|
||||
if (items == null) {
|
||||
LOG.info("Eagerly loading image size for latest message");
|
||||
AttachmentHeader header = headers.get(0);
|
||||
try {
|
||||
Attachment a = attachmentRetriever
|
||||
.getMessageAttachment(header);
|
||||
AttachmentItem item =
|
||||
attachmentRetriever.getAttachmentItem(a, true);
|
||||
attachmentRetriever.cachePut(id, singletonList(item));
|
||||
} catch (NoSuchMessageException e) {
|
||||
LOG.info("Attachment not received yet");
|
||||
missingAttachments.put(header.getMessageId(), h);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
@@ -638,18 +651,59 @@ public class ConversationActivity extends BriarActivity
|
||||
&& adapter.isScrolledToBottom(layoutManager);
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void updateMessageAttachment(MessageId m, AttachmentItem item) {
|
||||
Pair<Integer, ConversationMessageItem> pair = adapter.getMessageItem(m);
|
||||
if (pair != null && pair.getSecond().updateAttachments(item)) {
|
||||
boolean scroll = shouldScrollWhenUpdatingMessage();
|
||||
adapter.notifyItemChanged(pair.getFirst());
|
||||
if (scroll) scrollToBottom();
|
||||
}
|
||||
private void loadMessageAttachments(PrivateMessageHeader h) {
|
||||
// TODO: Use placeholders for missing/invalid attachments
|
||||
runOnDbThread(() -> {
|
||||
try {
|
||||
// TODO move getting the items off to IoExecutor, if size == 1
|
||||
List<AttachmentHeader> headers = h.getAttachmentHeaders();
|
||||
boolean needsSize = headers.size() == 1;
|
||||
List<AttachmentItem> items = new ArrayList<>(headers.size());
|
||||
for (AttachmentHeader header : headers) {
|
||||
try {
|
||||
Attachment a = attachmentRetriever
|
||||
.getMessageAttachment(header);
|
||||
AttachmentItem item = attachmentRetriever
|
||||
.getAttachmentItem(a, needsSize);
|
||||
items.add(item);
|
||||
} catch (NoSuchMessageException e) {
|
||||
LOG.info("Attachment not received yet");
|
||||
missingAttachments.put(header.getMessageId(), h);
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Don't cache items unless all are present and valid
|
||||
attachmentRetriever.cachePut(h.getId(), items);
|
||||
displayMessageAttachments(h.getId(), items);
|
||||
} catch (DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void displayMessageAttachments(MessageId m,
|
||||
List<AttachmentItem> items) {
|
||||
runOnUiThreadUnlessDestroyed(() -> {
|
||||
Pair<Integer, ConversationMessageItem> pair =
|
||||
adapter.getMessageItem(m);
|
||||
if (pair != null) {
|
||||
boolean scroll = shouldScrollWhenUpdatingMessage();
|
||||
pair.getSecond().setAttachments(items);
|
||||
adapter.notifyItemChanged(pair.getFirst());
|
||||
if (scroll) scrollToBottom();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void eventOccurred(Event e) {
|
||||
if (e instanceof AttachmentReceivedEvent) {
|
||||
AttachmentReceivedEvent a = (AttachmentReceivedEvent) e;
|
||||
if (a.getContactId().equals(contactId)) {
|
||||
LOG.info("Attachment received");
|
||||
onAttachmentReceived(a.getMessageId());
|
||||
}
|
||||
}
|
||||
if (e instanceof ContactRemovedEvent) {
|
||||
ContactRemovedEvent c = (ContactRemovedEvent) e;
|
||||
if (c.getContactId().equals(contactId)) {
|
||||
@@ -709,6 +763,15 @@ public class ConversationActivity extends BriarActivity
|
||||
scrollToBottom();
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void onAttachmentReceived(MessageId attachmentId) {
|
||||
PrivateMessageHeader h = missingAttachments.remove(attachmentId);
|
||||
if (h != null) {
|
||||
LOG.info("Missing attachment received");
|
||||
loadMessageAttachments(h);
|
||||
}
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void onNewConversationMessage(ConversationMessageHeader h) {
|
||||
if (h instanceof ConversationRequest ||
|
||||
@@ -717,7 +780,7 @@ public class ConversationActivity extends BriarActivity
|
||||
observeOnce(viewModel.getContactDisplayName(), this,
|
||||
name -> addConversationItem(h.accept(visitor)));
|
||||
} else {
|
||||
// visitor also loads message text and attachments (if existing)
|
||||
// visitor also loads message text (if existing)
|
||||
addConversationItem(h.accept(visitor));
|
||||
}
|
||||
}
|
||||
@@ -1044,9 +1107,8 @@ public class ConversationActivity extends BriarActivity
|
||||
i.putExtra(ATTACHMENT_POSITION, attachments.indexOf(item));
|
||||
i.putExtra(NAME, name);
|
||||
i.putExtra(DATE, messageItem.getTime());
|
||||
i.putExtra(ITEM_ID, messageItem.getId().getBytes());
|
||||
// restoring list position should not trigger android bug #224270
|
||||
String transitionName = item.getTransitionName(messageItem.getId());
|
||||
String transitionName = item.getTransitionName();
|
||||
ActivityOptionsCompat options =
|
||||
makeSceneTransitionAnimation(this, view, transitionName);
|
||||
ActivityCompat.startActivity(this, i, options.toBundle());
|
||||
@@ -1085,41 +1147,15 @@ public class ConversationActivity extends BriarActivity
|
||||
return text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by {@link PrivateMessageHeader#accept(ConversationMessageVisitor)}
|
||||
*/
|
||||
@Override
|
||||
public List<AttachmentItem> getAttachmentItems(PrivateMessageHeader h) {
|
||||
List<LiveData<AttachmentItem>> liveDataList =
|
||||
attachmentRetriever.getAttachmentItems(h);
|
||||
List<AttachmentItem> items = new ArrayList<>(liveDataList.size());
|
||||
for (LiveData<AttachmentItem> liveData : liveDataList) {
|
||||
// first remove all our observers to avoid having more than one
|
||||
// in case we reload the conversation, e.g. after deleting messages
|
||||
liveData.removeObservers(this);
|
||||
// add a new observer
|
||||
liveData.observe(this, new AttachmentObserver(h.getId(), liveData));
|
||||
items.add(requireNonNull(liveData.getValue()));
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
private class AttachmentObserver implements Observer<AttachmentItem> {
|
||||
private final MessageId conversationMessageId;
|
||||
private final LiveData<AttachmentItem> liveData;
|
||||
|
||||
private AttachmentObserver(MessageId conversationMessageId,
|
||||
LiveData<AttachmentItem> liveData) {
|
||||
this.conversationMessageId = conversationMessageId;
|
||||
this.liveData = liveData;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onChanged(AttachmentItem attachmentItem) {
|
||||
updateMessageAttachment(conversationMessageId, attachmentItem);
|
||||
if (attachmentItem.getState().isFinal())
|
||||
liveData.removeObserver(this);
|
||||
List<AttachmentItem> attachments =
|
||||
attachmentRetriever.cacheGet(h.getId());
|
||||
if (attachments == null) {
|
||||
loadMessageAttachments(h);
|
||||
return emptyList();
|
||||
}
|
||||
return attachments;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -9,13 +9,12 @@ import java.util.List;
|
||||
import javax.annotation.concurrent.NotThreadSafe;
|
||||
|
||||
import androidx.annotation.LayoutRes;
|
||||
import androidx.annotation.UiThread;
|
||||
|
||||
@NotThreadSafe
|
||||
@NotNullByDefault
|
||||
class ConversationMessageItem extends ConversationItem {
|
||||
|
||||
private final List<AttachmentItem> attachments;
|
||||
private List<AttachmentItem> attachments;
|
||||
|
||||
ConversationMessageItem(@LayoutRes int layoutRes, PrivateMessageHeader h,
|
||||
List<AttachmentItem> attachments) {
|
||||
@@ -27,14 +26,8 @@ class ConversationMessageItem extends ConversationItem {
|
||||
return attachments;
|
||||
}
|
||||
|
||||
@UiThread
|
||||
boolean updateAttachments(AttachmentItem item) {
|
||||
int pos = attachments.indexOf(item);
|
||||
if (pos != -1 && attachments.get(pos).getState() != item.getState()) {
|
||||
attachments.set(pos, item);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
void setAttachments(List<AttachmentItem> attachments) {
|
||||
this.attachments = attachments;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -11,9 +11,6 @@ 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.db.TransactionManager;
|
||||
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.identity.AuthorId;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.settings.Settings;
|
||||
@@ -33,7 +30,6 @@ import org.briarproject.briar.api.messaging.MessagingManager;
|
||||
import org.briarproject.briar.api.messaging.PrivateMessage;
|
||||
import org.briarproject.briar.api.messaging.PrivateMessageFactory;
|
||||
import org.briarproject.briar.api.messaging.PrivateMessageHeader;
|
||||
import org.briarproject.briar.api.messaging.event.AttachmentReceivedEvent;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
@@ -60,7 +56,7 @@ import static org.briarproject.briar.android.util.UiUtils.observeForeverOnce;
|
||||
|
||||
@NotNullByDefault
|
||||
public class ConversationViewModel extends AndroidViewModel
|
||||
implements EventListener, AttachmentManager {
|
||||
implements AttachmentManager {
|
||||
|
||||
private static Logger LOG =
|
||||
getLogger(ConversationViewModel.class.getName());
|
||||
@@ -73,7 +69,6 @@ public class ConversationViewModel extends AndroidViewModel
|
||||
@DatabaseExecutor
|
||||
private final Executor dbExecutor;
|
||||
private final TransactionManager db;
|
||||
private final EventBus eventBus;
|
||||
private final MessagingManager messagingManager;
|
||||
private final ContactManager contactManager;
|
||||
private final SettingsManager settingsManager;
|
||||
@@ -106,7 +101,6 @@ public class ConversationViewModel extends AndroidViewModel
|
||||
ConversationViewModel(Application application,
|
||||
@DatabaseExecutor Executor dbExecutor,
|
||||
TransactionManager db,
|
||||
EventBus eventBus,
|
||||
MessagingManager messagingManager,
|
||||
ContactManager contactManager,
|
||||
SettingsManager settingsManager,
|
||||
@@ -116,7 +110,6 @@ public class ConversationViewModel extends AndroidViewModel
|
||||
super(application);
|
||||
this.dbExecutor = dbExecutor;
|
||||
this.db = db;
|
||||
this.eventBus = eventBus;
|
||||
this.messagingManager = messagingManager;
|
||||
this.contactManager = contactManager;
|
||||
this.settingsManager = settingsManager;
|
||||
@@ -126,27 +119,12 @@ public class ConversationViewModel extends AndroidViewModel
|
||||
messagingGroupId = Transformations
|
||||
.map(contact, c -> messagingManager.getContactGroup(c).getId());
|
||||
contactDeleted.setValue(false);
|
||||
|
||||
eventBus.addListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCleared() {
|
||||
super.onCleared();
|
||||
attachmentCreator.cancel(); // also deletes unsent attachments
|
||||
eventBus.removeListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void eventOccurred(Event e) {
|
||||
if (e instanceof AttachmentReceivedEvent) {
|
||||
AttachmentReceivedEvent a = (AttachmentReceivedEvent) e;
|
||||
if (a.getContactId().equals(contactId)) {
|
||||
LOG.info("Attachment received");
|
||||
dbExecutor.execute(() -> attachmentRetriever
|
||||
.loadAttachmentItem(a.getMessageId()));
|
||||
}
|
||||
}
|
||||
attachmentCreator.deleteUnsentAttachments();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -274,7 +252,6 @@ public class ConversationViewModel extends AndroidViewModel
|
||||
settingsManager.mergeSettings(settings, SETTINGS_NAMESPACE);
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void createMessage(GroupId groupId, @Nullable String text,
|
||||
List<AttachmentHeader> headers, long timestamp,
|
||||
boolean hasImageSupport) {
|
||||
@@ -293,7 +270,6 @@ public class ConversationViewModel extends AndroidViewModel
|
||||
}
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void storeMessage(PrivateMessage m) {
|
||||
attachmentCreator.onAttachmentsSent(m.getMessage().getId());
|
||||
dbExecutor.execute(() -> {
|
||||
|
||||
@@ -16,7 +16,6 @@ import com.google.android.material.appbar.AppBarLayout;
|
||||
|
||||
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
|
||||
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
|
||||
import org.briarproject.bramble.api.sync.MessageId;
|
||||
import org.briarproject.briar.R;
|
||||
import org.briarproject.briar.android.activity.ActivityComponent;
|
||||
import org.briarproject.briar.android.activity.BriarActivity;
|
||||
@@ -68,7 +67,6 @@ public class ImageActivity extends BriarActivity
|
||||
final static String ATTACHMENT_POSITION = "position";
|
||||
final static String NAME = "name";
|
||||
final static String DATE = "date";
|
||||
final static String ITEM_ID = "itemId";
|
||||
|
||||
@RequiresApi(api = 16)
|
||||
private final static int UI_FLAGS_DEFAULT =
|
||||
@@ -82,7 +80,6 @@ public class ImageActivity extends BriarActivity
|
||||
private AppBarLayout appBarLayout;
|
||||
private ViewPager viewPager;
|
||||
private List<AttachmentItem> attachments;
|
||||
private MessageId conversationMessageId;
|
||||
|
||||
@Override
|
||||
public void injectActivity(ActivityComponent component) {
|
||||
@@ -101,20 +98,9 @@ public class ImageActivity extends BriarActivity
|
||||
setSceneTransitionAnimation(transition, null, transition);
|
||||
}
|
||||
|
||||
// Intent Extras
|
||||
Intent i = getIntent();
|
||||
attachments =
|
||||
requireNonNull(i.getParcelableArrayListExtra(ATTACHMENTS));
|
||||
int position = i.getIntExtra(ATTACHMENT_POSITION, -1);
|
||||
if (position == -1) throw new IllegalStateException();
|
||||
String name = i.getStringExtra(NAME);
|
||||
long time = i.getLongExtra(DATE, 0);
|
||||
byte[] messageIdBytes = requireNonNull(i.getByteArrayExtra(ITEM_ID));
|
||||
|
||||
// get View Model
|
||||
viewModel = ViewModelProviders.of(this, viewModelFactory)
|
||||
.get(ImageViewModel.class);
|
||||
viewModel.expectAttachments(attachments);
|
||||
viewModel.getSaveState().observeEvent(this,
|
||||
this::onImageSaveStateChanged);
|
||||
|
||||
@@ -138,11 +124,16 @@ public class ImageActivity extends BriarActivity
|
||||
TextView contactName = toolbar.findViewById(R.id.contactName);
|
||||
TextView dateView = toolbar.findViewById(R.id.dateView);
|
||||
|
||||
// Set contact name and message time
|
||||
// Intent Extras
|
||||
Intent i = getIntent();
|
||||
attachments = i.getParcelableArrayListExtra(ATTACHMENTS);
|
||||
int position = i.getIntExtra(ATTACHMENT_POSITION, -1);
|
||||
if (position == -1) throw new IllegalStateException();
|
||||
String name = i.getStringExtra(NAME);
|
||||
long time = i.getLongExtra(DATE, 0);
|
||||
String date = formatDateAbsolute(this, time);
|
||||
contactName.setText(name);
|
||||
dateView.setText(date);
|
||||
conversationMessageId = new MessageId(messageIdBytes);
|
||||
|
||||
// Set up image ViewPager
|
||||
viewPager = findViewById(R.id.viewPager);
|
||||
@@ -329,8 +320,8 @@ public class ImageActivity extends BriarActivity
|
||||
|
||||
@Override
|
||||
public Fragment getItem(int position) {
|
||||
Fragment f = ImageFragment.newInstance(
|
||||
attachments.get(position), conversationMessageId, isFirst);
|
||||
Fragment f = ImageFragment
|
||||
.newInstance(attachments.get(position), isFirst);
|
||||
isFirst = false;
|
||||
return f;
|
||||
}
|
||||
|
||||
@@ -49,8 +49,7 @@ class ImageAdapter extends Adapter<ImageViewHolder> {
|
||||
public ImageViewHolder onCreateViewHolder(ViewGroup viewGroup, int type) {
|
||||
View v = LayoutInflater.from(viewGroup.getContext()).inflate(
|
||||
R.layout.list_item_image, viewGroup, false);
|
||||
requireNonNull(conversationItem);
|
||||
return new ImageViewHolder(v, imageSize, conversationItem.getId());
|
||||
return new ImageViewHolder(v, imageSize);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -15,7 +15,6 @@ import com.bumptech.glide.request.target.Target;
|
||||
import com.github.chrisbanes.photoview.PhotoView;
|
||||
|
||||
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
|
||||
import org.briarproject.bramble.api.sync.MessageId;
|
||||
import org.briarproject.briar.R;
|
||||
import org.briarproject.briar.android.activity.BaseActivity;
|
||||
import org.briarproject.briar.android.attachment.AttachmentItem;
|
||||
@@ -24,7 +23,6 @@ import org.briarproject.briar.android.conversation.glide.GlideApp;
|
||||
import javax.annotation.ParametersAreNonnullByDefault;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import androidx.annotation.DrawableRes;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.fragment.app.Fragment;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
@@ -34,36 +32,27 @@ import static android.os.Build.VERSION.SDK_INT;
|
||||
import static android.widget.ImageView.ScaleType.FIT_START;
|
||||
import static com.bumptech.glide.load.engine.DiskCacheStrategy.NONE;
|
||||
import static org.briarproject.bramble.api.nullsafety.NullSafety.requireNonNull;
|
||||
import static org.briarproject.briar.android.attachment.AttachmentItem.State.AVAILABLE;
|
||||
import static org.briarproject.briar.android.attachment.AttachmentItem.State.ERROR;
|
||||
import static org.briarproject.briar.android.conversation.ImageActivity.ATTACHMENT_POSITION;
|
||||
import static org.briarproject.briar.android.conversation.ImageActivity.ITEM_ID;
|
||||
|
||||
@MethodsNotNullByDefault
|
||||
@ParametersAreNonnullByDefault
|
||||
public class ImageFragment extends Fragment
|
||||
implements RequestListener<Drawable> {
|
||||
public class ImageFragment extends Fragment {
|
||||
|
||||
private final static String IS_FIRST = "isFirst";
|
||||
@DrawableRes
|
||||
private static final int ERROR_RES = R.drawable.ic_image_broken;
|
||||
|
||||
@Inject
|
||||
ViewModelProvider.Factory viewModelFactory;
|
||||
|
||||
private AttachmentItem attachment;
|
||||
private boolean isFirst;
|
||||
private MessageId conversationItemId;
|
||||
private ImageViewModel viewModel;
|
||||
private PhotoView photoView;
|
||||
|
||||
static ImageFragment newInstance(AttachmentItem a,
|
||||
MessageId conversationMessageId, boolean isFirst) {
|
||||
static ImageFragment newInstance(AttachmentItem a, boolean isFirst) {
|
||||
ImageFragment f = new ImageFragment();
|
||||
Bundle args = new Bundle();
|
||||
args.putParcelable(ATTACHMENT_POSITION, a);
|
||||
args.putBoolean(IS_FIRST, isFirst);
|
||||
args.putByteArray(ITEM_ID, conversationMessageId.getBytes());
|
||||
f.setArguments(args);
|
||||
return f;
|
||||
}
|
||||
@@ -81,8 +70,6 @@ public class ImageFragment extends Fragment
|
||||
Bundle args = requireNonNull(getArguments());
|
||||
attachment = requireNonNull(args.getParcelable(ATTACHMENT_POSITION));
|
||||
isFirst = args.getBoolean(IS_FIRST);
|
||||
conversationItemId =
|
||||
new MessageId(requireNonNull(args.getByteArray(ITEM_ID)));
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@@ -100,68 +87,50 @@ public class ImageFragment extends Fragment
|
||||
photoView.setScaleLevels(1, 2, 4);
|
||||
photoView.setOnClickListener(view -> viewModel.clickImage());
|
||||
|
||||
if (attachment.getState() == AVAILABLE) {
|
||||
loadImage();
|
||||
// postponed transition will be started when Image was loaded
|
||||
} else if (attachment.getState() == ERROR) {
|
||||
photoView.setImageResource(ERROR_RES);
|
||||
startPostponedTransition();
|
||||
} else {
|
||||
photoView.setImageResource(R.drawable.ic_image_missing);
|
||||
startPostponedTransition();
|
||||
// state is not final, so observe state changes
|
||||
viewModel.getOnAttachmentReceived(attachment.getMessageId())
|
||||
.observeEvent(this, this::onAttachmentReceived);
|
||||
}
|
||||
// Request Listener
|
||||
RequestListener<Drawable> listener = new RequestListener<Drawable>() {
|
||||
|
||||
@Override
|
||||
public boolean onLoadFailed(@Nullable GlideException e,
|
||||
Object model, Target<Drawable> target,
|
||||
boolean isFirstResource) {
|
||||
if (getActivity() != null && isFirst)
|
||||
getActivity().supportStartPostponedEnterTransition();
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onResourceReady(Drawable resource, Object model,
|
||||
Target<Drawable> target, DataSource dataSource,
|
||||
boolean isFirstResource) {
|
||||
if (SDK_INT >= 21 && !(resource instanceof Animatable)) {
|
||||
// set transition name only when not animatable,
|
||||
// because the animation won't start otherwise
|
||||
photoView.setTransitionName(
|
||||
attachment.getTransitionName());
|
||||
}
|
||||
// Move image to the top if overlapping toolbar
|
||||
if (viewModel.isOverlappingToolbar(photoView, resource)) {
|
||||
photoView.setScaleType(FIT_START);
|
||||
}
|
||||
if (getActivity() != null && isFirst) {
|
||||
getActivity().supportStartPostponedEnterTransition();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Load Image
|
||||
GlideApp.with(this)
|
||||
.load(attachment)
|
||||
// TODO allow if size < maxTextureSize ?
|
||||
// .override(SIZE_ORIGINAL)
|
||||
.diskCacheStrategy(NONE)
|
||||
.error(R.drawable.ic_image_broken)
|
||||
.addListener(listener)
|
||||
.into(photoView);
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
private void loadImage() {
|
||||
GlideApp.with(this)
|
||||
.load(attachment)
|
||||
// TODO allow if size < maxTextureSize ?
|
||||
// .override(SIZE_ORIGINAL)
|
||||
.diskCacheStrategy(NONE)
|
||||
.error(ERROR_RES)
|
||||
.addListener(this)
|
||||
.into(photoView);
|
||||
}
|
||||
|
||||
private void onAttachmentReceived(Boolean received) {
|
||||
if (received) loadImage();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onLoadFailed(@Nullable GlideException e,
|
||||
Object model, Target<Drawable> target,
|
||||
boolean isFirstResource) {
|
||||
startPostponedTransition();
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onResourceReady(Drawable resource, Object model,
|
||||
Target<Drawable> target, DataSource dataSource,
|
||||
boolean isFirstResource) {
|
||||
if (SDK_INT >= 21 && !(resource instanceof Animatable)) {
|
||||
// set transition name only when not animatable,
|
||||
// because the animation won't start otherwise
|
||||
photoView.setTransitionName(
|
||||
attachment.getTransitionName(conversationItemId));
|
||||
}
|
||||
// Move image to the top if overlapping toolbar
|
||||
if (viewModel.isOverlappingToolbar(photoView, resource)) {
|
||||
photoView.setScaleType(FIT_START);
|
||||
}
|
||||
startPostponedTransition();
|
||||
return false;
|
||||
}
|
||||
|
||||
private void startPostponedTransition() {
|
||||
if (getActivity() != null && isFirst) {
|
||||
getActivity().supportStartPostponedEnterTransition();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ import android.widget.ImageView;
|
||||
import com.bumptech.glide.load.Transformation;
|
||||
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.sync.MessageId;
|
||||
import org.briarproject.briar.R;
|
||||
import org.briarproject.briar.android.attachment.AttachmentItem;
|
||||
import org.briarproject.briar.android.conversation.glide.BriarImageTransformation;
|
||||
@@ -19,12 +18,8 @@ import androidx.recyclerview.widget.RecyclerView.ViewHolder;
|
||||
import androidx.recyclerview.widget.StaggeredGridLayoutManager.LayoutParams;
|
||||
|
||||
import static android.os.Build.VERSION.SDK_INT;
|
||||
import static android.widget.ImageView.ScaleType.CENTER_CROP;
|
||||
import static android.widget.ImageView.ScaleType.FIT_CENTER;
|
||||
import static com.bumptech.glide.load.engine.DiskCacheStrategy.NONE;
|
||||
import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade;
|
||||
import static org.briarproject.briar.android.attachment.AttachmentItem.State.AVAILABLE;
|
||||
import static org.briarproject.briar.android.attachment.AttachmentItem.State.ERROR;
|
||||
|
||||
@NotNullByDefault
|
||||
class ImageViewHolder extends ViewHolder {
|
||||
@@ -34,33 +29,25 @@ class ImageViewHolder extends ViewHolder {
|
||||
|
||||
protected final ImageView imageView;
|
||||
private final int imageSize;
|
||||
private final MessageId conversationItemId;
|
||||
|
||||
ImageViewHolder(View v, int imageSize, MessageId conversationItemId) {
|
||||
ImageViewHolder(View v, int imageSize) {
|
||||
super(v);
|
||||
imageView = v.findViewById(R.id.imageView);
|
||||
this.imageSize = imageSize;
|
||||
this.conversationItemId = conversationItemId;
|
||||
}
|
||||
|
||||
void bind(AttachmentItem attachment, Radii r, boolean single,
|
||||
boolean needsStretch) {
|
||||
setImageViewDimensions(attachment, single, needsStretch);
|
||||
if (attachment.getState() != AVAILABLE) {
|
||||
GlideApp.with(imageView).clear(imageView);
|
||||
if (attachment.getState() == ERROR) {
|
||||
imageView.setImageResource(ERROR_RES);
|
||||
} else {
|
||||
imageView.setImageResource(R.drawable.ic_image_missing);
|
||||
}
|
||||
imageView.setScaleType(FIT_CENTER);
|
||||
if (attachment.hasError()) {
|
||||
GlideApp.with(imageView)
|
||||
.clear(imageView);
|
||||
imageView.setImageResource(ERROR_RES);
|
||||
} else {
|
||||
setImageViewDimensions(attachment, single, needsStretch);
|
||||
loadImage(attachment, r);
|
||||
imageView.setScaleType(CENTER_CROP);
|
||||
}
|
||||
if (SDK_INT >= 21) {
|
||||
imageView.setTransitionName(
|
||||
attachment.getTransitionName(conversationItemId));
|
||||
if (SDK_INT >= 21) {
|
||||
imageView.setTransitionName(attachment.getTransitionName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,18 +7,13 @@ import android.view.View;
|
||||
|
||||
import org.briarproject.bramble.api.db.DatabaseExecutor;
|
||||
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.lifecycle.IoExecutor;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.sync.MessageId;
|
||||
import org.briarproject.briar.android.attachment.AttachmentItem;
|
||||
import org.briarproject.briar.android.viewmodel.LiveEvent;
|
||||
import org.briarproject.briar.android.viewmodel.MutableLiveEvent;
|
||||
import org.briarproject.briar.api.messaging.Attachment;
|
||||
import org.briarproject.briar.api.messaging.MessagingManager;
|
||||
import org.briarproject.briar.api.messaging.event.AttachmentReceivedEvent;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
@@ -27,8 +22,6 @@ import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.logging.Logger;
|
||||
@@ -42,28 +35,22 @@ import androidx.lifecycle.AndroidViewModel;
|
||||
import static android.media.MediaScannerConnection.scanFile;
|
||||
import static android.os.Environment.DIRECTORY_PICTURES;
|
||||
import static android.os.Environment.getExternalStoragePublicDirectory;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
import static java.util.logging.Level.WARNING;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
import static org.briarproject.bramble.util.IoUtils.copyAndClose;
|
||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||
|
||||
@NotNullByDefault
|
||||
public class ImageViewModel extends AndroidViewModel implements EventListener {
|
||||
public class ImageViewModel extends AndroidViewModel {
|
||||
|
||||
private static Logger LOG = getLogger(ImageViewModel.class.getName());
|
||||
|
||||
private final MessagingManager messagingManager;
|
||||
private final EventBus eventBus;
|
||||
@DatabaseExecutor
|
||||
private final Executor dbExecutor;
|
||||
@IoExecutor
|
||||
private final Executor ioExecutor;
|
||||
|
||||
private boolean receivedAttachmentsInitialized = false;
|
||||
private HashMap<MessageId, MutableLiveEvent<Boolean>> receivedAttachments =
|
||||
new HashMap<>();
|
||||
|
||||
/**
|
||||
* true means there was an error saving the image, false if image was saved.
|
||||
*/
|
||||
@@ -75,60 +62,13 @@ public class ImageViewModel extends AndroidViewModel implements EventListener {
|
||||
|
||||
@Inject
|
||||
ImageViewModel(Application application,
|
||||
MessagingManager messagingManager, EventBus eventBus,
|
||||
MessagingManager messagingManager,
|
||||
@DatabaseExecutor Executor dbExecutor,
|
||||
@IoExecutor Executor ioExecutor) {
|
||||
super(application);
|
||||
this.messagingManager = messagingManager;
|
||||
this.eventBus = eventBus;
|
||||
this.dbExecutor = dbExecutor;
|
||||
this.ioExecutor = ioExecutor;
|
||||
|
||||
eventBus.addListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCleared() {
|
||||
super.onCleared();
|
||||
eventBus.removeListener(this);
|
||||
}
|
||||
|
||||
@UiThread
|
||||
@Override
|
||||
public void eventOccurred(Event e) {
|
||||
if (e instanceof AttachmentReceivedEvent) {
|
||||
MessageId id = ((AttachmentReceivedEvent) e).getMessageId();
|
||||
MutableLiveEvent<Boolean> oldEvent;
|
||||
if (receivedAttachmentsInitialized) {
|
||||
oldEvent = receivedAttachments.get(id);
|
||||
if (oldEvent != null) oldEvent.postEvent(true);
|
||||
} else {
|
||||
receivedAttachments.put(id, new MutableLiveEvent<>(true));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@UiThread
|
||||
public void expectAttachments(List<AttachmentItem> attachments) {
|
||||
for (AttachmentItem item : attachments) {
|
||||
// no need to track items that are in a final state already
|
||||
if (item.getState().isFinal()) continue;
|
||||
// add new live events, if not already added by eventOccurred()
|
||||
MessageId id = item.getMessageId();
|
||||
if (!receivedAttachments.containsKey(id)) {
|
||||
receivedAttachments.put(id, new MutableLiveEvent<>());
|
||||
}
|
||||
}
|
||||
receivedAttachmentsInitialized = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a LiveData for attachments in a non-final state.
|
||||
* Note that you need to call {@link #expectAttachments(List)} first.
|
||||
*/
|
||||
@UiThread
|
||||
LiveEvent<Boolean> getOnAttachmentReceived(MessageId messageId) {
|
||||
return requireNonNull(receivedAttachments.get(messageId));
|
||||
}
|
||||
|
||||
void clickImage() {
|
||||
|
||||
@@ -9,6 +9,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.activity.ActivityComponent;
|
||||
import org.briarproject.briar.android.fragment.BaseFragment;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import javax.inject.Inject;
|
||||
@@ -113,7 +114,9 @@ public class ContactExchangeActivity extends KeyAgreementActivity {
|
||||
return getString(R.string.exchanging_contact_details);
|
||||
}
|
||||
|
||||
private void showErrorFragment() {
|
||||
showNextFragment(new ContactExchangeErrorFragment());
|
||||
protected void showErrorFragment() {
|
||||
String errorMsg = getString(R.string.connection_error_explanation);
|
||||
BaseFragment f = ContactExchangeErrorFragment.newInstance(errorMsg);
|
||||
showNextFragment(f);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package org.briarproject.briar.android.keyagreement;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
@@ -19,10 +18,7 @@ import org.briarproject.briar.android.util.UiUtils;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.fragment.app.FragmentActivity;
|
||||
|
||||
import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
|
||||
import static android.view.View.GONE;
|
||||
import static org.briarproject.briar.android.util.UiUtils.onSingleLinkClick;
|
||||
|
||||
@MethodsNotNullByDefault
|
||||
@@ -62,12 +58,13 @@ public class ContactExchangeErrorFragment extends BaseFragment {
|
||||
View v = inflater.inflate(R.layout.fragment_error_contact_exchange,
|
||||
container, false);
|
||||
|
||||
// set optional error message
|
||||
// set humanized error message
|
||||
TextView explanation = v.findViewById(R.id.errorMessage);
|
||||
Bundle args = getArguments();
|
||||
String errorMessage = args == null ? null : args.getString(ERROR_MSG);
|
||||
if (errorMessage == null) explanation.setVisibility(GONE);
|
||||
else explanation.setText(args.getString(ERROR_MSG));
|
||||
if (args == null) {
|
||||
throw new IllegalArgumentException("Use newInstance()");
|
||||
}
|
||||
explanation.setText(args.getString(ERROR_MSG));
|
||||
|
||||
// make feedback link clickable
|
||||
TextView sendFeedback = v.findViewById(R.id.sendFeedback);
|
||||
@@ -76,11 +73,7 @@ public class ContactExchangeErrorFragment extends BaseFragment {
|
||||
// buttons
|
||||
Button tryAgain = v.findViewById(R.id.tryAgainButton);
|
||||
tryAgain.setOnClickListener(view -> {
|
||||
// Recreate the activity so we return to the intro fragment
|
||||
FragmentActivity activity = requireActivity();
|
||||
Intent i = new Intent(activity, ContactExchangeActivity.class);
|
||||
i.setFlags(FLAG_ACTIVITY_CLEAR_TOP);
|
||||
activity.startActivity(i);
|
||||
if (getActivity() != null) getActivity().onBackPressed();
|
||||
});
|
||||
Button cancel = v.findViewById(R.id.cancelButton);
|
||||
cancel.setOnClickListener(view -> finish());
|
||||
|
||||
@@ -18,6 +18,7 @@ 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.BluetoothEnabledEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportStateEvent;
|
||||
import org.briarproject.briar.R;
|
||||
import org.briarproject.briar.android.activity.ActivityComponent;
|
||||
@@ -26,6 +27,7 @@ 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 org.briarproject.briar.android.util.UiUtils;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@@ -45,7 +47,6 @@ 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;
|
||||
@@ -55,7 +56,6 @@ 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
|
||||
@@ -118,6 +118,13 @@ public abstract class KeyAgreementActivity extends BriarActivity implements
|
||||
*/
|
||||
private boolean continueClicked = false;
|
||||
|
||||
/**
|
||||
* Records whether the Bluetooth adapter was already enabled before we
|
||||
* asked for Bluetooth discoverability, so we know whether to broadcast a
|
||||
* {@link BluetoothEnabledEvent}.
|
||||
*/
|
||||
private boolean wasAdapterEnabled = false;
|
||||
|
||||
/**
|
||||
* Records whether we've enabled the wifi plugin so we don't enable it more
|
||||
* than once.
|
||||
@@ -134,8 +141,6 @@ public abstract class KeyAgreementActivity extends BriarActivity implements
|
||||
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) {
|
||||
@@ -155,9 +160,6 @@ public abstract class KeyAgreementActivity extends BriarActivity implements
|
||||
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
|
||||
@@ -193,7 +195,6 @@ public abstract class KeyAgreementActivity extends BriarActivity implements
|
||||
showQrCodeFragmentIfAllowed();
|
||||
}
|
||||
|
||||
@SuppressWarnings("StatementWithEmptyBody")
|
||||
private void showQrCodeFragmentIfAllowed() {
|
||||
if (isResumed && continueClicked && areEssentialPermissionsGranted()) {
|
||||
if (isWifiReady() && isBluetoothReady()) {
|
||||
@@ -207,8 +208,6 @@ public abstract class KeyAgreementActivity extends BriarActivity implements
|
||||
}
|
||||
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;
|
||||
@@ -219,50 +218,55 @@ public abstract class KeyAgreementActivity extends BriarActivity implements
|
||||
}
|
||||
|
||||
private boolean areEssentialPermissionsGranted() {
|
||||
// If the camera permission has been granted, and the location
|
||||
// permission has been granted or permanently denied, we can continue
|
||||
return cameraPermission == Permission.GRANTED &&
|
||||
(SDK_INT < 23 || locationPermission == Permission.GRANTED ||
|
||||
!isBluetoothSupported());
|
||||
}
|
||||
|
||||
private boolean isBluetoothSupported() {
|
||||
return bt != null && bluetoothPlugin != null;
|
||||
(locationPermission == Permission.GRANTED ||
|
||||
locationPermission == Permission.PERMANENTLY_DENIED);
|
||||
}
|
||||
|
||||
private boolean isWifiReady() {
|
||||
if (wifiPlugin == null) return true; // Continue without wifi
|
||||
State state = wifiPlugin.getState();
|
||||
Plugin p = pluginManager.getPlugin(LanTcpConstants.ID);
|
||||
if (p == null) return true; // Continue without wifi
|
||||
State state = p.getState();
|
||||
// Wait for plugin to become enabled
|
||||
return state == ACTIVE || state == INACTIVE;
|
||||
}
|
||||
|
||||
private boolean isBluetoothReady() {
|
||||
if (!isBluetoothSupported()) {
|
||||
if (bluetoothDecision == BluetoothDecision.UNKNOWN ||
|
||||
bluetoothDecision == BluetoothDecision.WAITING) {
|
||||
// Wait for decision
|
||||
return false;
|
||||
}
|
||||
if (bluetoothDecision == BluetoothDecision.NO_ADAPTER
|
||||
|| bluetoothDecision == BluetoothDecision.REFUSED) {
|
||||
// Continue without Bluetooth
|
||||
return true;
|
||||
}
|
||||
if (bluetoothDecision == BluetoothDecision.UNKNOWN ||
|
||||
bluetoothDecision == BluetoothDecision.WAITING ||
|
||||
bluetoothDecision == BluetoothDecision.REFUSED) {
|
||||
// Wait for user to accept
|
||||
return false;
|
||||
}
|
||||
BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter();
|
||||
if (bt == null) return true; // Continue without Bluetooth
|
||||
if (bt.getScanMode() != SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
|
||||
// Wait for adapter to become discoverable
|
||||
return false;
|
||||
}
|
||||
Plugin p = pluginManager.getPlugin(BluetoothConstants.ID);
|
||||
if (p == null) return true; // Continue without Bluetooth
|
||||
// Wait for plugin to become active
|
||||
return bluetoothPlugin.getState() == ACTIVE;
|
||||
return p.getState() == ACTIVE;
|
||||
}
|
||||
|
||||
private boolean shouldEnableWifi() {
|
||||
if (hasEnabledWifi) return false;
|
||||
if (wifiPlugin == null) return false;
|
||||
State state = wifiPlugin.getState();
|
||||
Plugin p = pluginManager.getPlugin(LanTcpConstants.ID);
|
||||
if (p == null) return false;
|
||||
State state = p.getState();
|
||||
return state == STARTING_STOPPING || state == DISABLED;
|
||||
}
|
||||
|
||||
private void requestBluetoothDiscoverable() {
|
||||
if (!isBluetoothSupported()) {
|
||||
BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter();
|
||||
if (bt == null) {
|
||||
bluetoothDecision = BluetoothDecision.NO_ADAPTER;
|
||||
showQrCodeFragmentIfAllowed();
|
||||
} else {
|
||||
@@ -270,6 +274,7 @@ public abstract class KeyAgreementActivity extends BriarActivity implements
|
||||
if (i.resolveActivity(getPackageManager()) != null) {
|
||||
LOG.info("Asking for Bluetooth discoverability");
|
||||
bluetoothDecision = BluetoothDecision.WAITING;
|
||||
wasAdapterEnabled = bt.isEnabled();
|
||||
startActivityForResult(i, REQUEST_BLUETOOTH_DISCOVERABLE);
|
||||
} else {
|
||||
bluetoothDecision = BluetoothDecision.NO_ADAPTER;
|
||||
@@ -281,8 +286,9 @@ public abstract class KeyAgreementActivity extends BriarActivity implements
|
||||
private boolean shouldEnableBluetooth() {
|
||||
if (bluetoothDecision != BluetoothDecision.ACCEPTED) return false;
|
||||
if (hasEnabledBluetooth) return false;
|
||||
if (!isBluetoothSupported()) return false;
|
||||
State state = bluetoothPlugin.getState();
|
||||
Plugin p = pluginManager.getPlugin(BluetoothConstants.ID);
|
||||
if (p == null) return false;
|
||||
State state = p.getState();
|
||||
return state == STARTING_STOPPING || state == DISABLED;
|
||||
}
|
||||
|
||||
@@ -301,9 +307,6 @@ public abstract class KeyAgreementActivity extends BriarActivity implements
|
||||
@Override
|
||||
public void showNextScreen() {
|
||||
continueClicked = true;
|
||||
if (bluetoothDecision == BluetoothDecision.REFUSED) {
|
||||
bluetoothDecision = BluetoothDecision.UNKNOWN; // Ask again
|
||||
}
|
||||
if (checkPermissions()) showQrCodeFragmentIfAllowed();
|
||||
}
|
||||
|
||||
@@ -317,6 +320,11 @@ public abstract class KeyAgreementActivity extends BriarActivity implements
|
||||
} else {
|
||||
LOG.info("Bluetooth discoverability was accepted");
|
||||
bluetoothDecision = BluetoothDecision.ACCEPTED;
|
||||
if (!wasAdapterEnabled) {
|
||||
LOG.info("Bluetooth adapter was enabled by us");
|
||||
eventBus.broadcast(new BluetoothEnabledEvent());
|
||||
wasAdapterEnabled = true;
|
||||
}
|
||||
}
|
||||
showQrCodeFragmentIfAllowed();
|
||||
} else super.onActivityResult(request, result, data);
|
||||
@@ -347,17 +355,17 @@ public abstract class KeyAgreementActivity extends BriarActivity implements
|
||||
|
||||
private boolean checkPermissions() {
|
||||
if (areEssentialPermissionsGranted()) return true;
|
||||
// If an essential permission has been permanently denied, ask the
|
||||
// If the camera 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);
|
||||
Builder builder = new Builder(this, R.style.BriarDialogTheme);
|
||||
builder.setTitle(R.string.permission_camera_title);
|
||||
builder.setMessage(R.string.permission_camera_denied_body);
|
||||
builder.setPositiveButton(R.string.ok,
|
||||
UiUtils.getGoToSettingsListener(this));
|
||||
builder.setNegativeButton(R.string.cancel,
|
||||
(dialog, which) -> supportFinishAfterTransition());
|
||||
builder.show();
|
||||
return false;
|
||||
}
|
||||
// Should we show the rationale for one or both permissions?
|
||||
@@ -377,16 +385,6 @@ public abstract class KeyAgreementActivity extends BriarActivity implements
|
||||
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);
|
||||
@@ -397,13 +395,8 @@ public abstract class KeyAgreementActivity extends BriarActivity implements
|
||||
}
|
||||
|
||||
private void requestPermissions() {
|
||||
String[] permissions;
|
||||
if (isBluetoothSupported()) {
|
||||
permissions = new String[] {CAMERA, ACCESS_FINE_LOCATION};
|
||||
} else {
|
||||
permissions = new String[] {CAMERA};
|
||||
}
|
||||
ActivityCompat.requestPermissions(this, permissions,
|
||||
ActivityCompat.requestPermissions(this,
|
||||
new String[] {CAMERA, ACCESS_FINE_LOCATION},
|
||||
REQUEST_PERMISSION_CAMERA_LOCATION);
|
||||
}
|
||||
|
||||
@@ -420,15 +413,12 @@ public abstract class KeyAgreementActivity extends BriarActivity implements
|
||||
} 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 (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
|
||||
|
||||
@@ -11,7 +11,6 @@ import android.view.ViewGroup;
|
||||
import android.widget.BaseAdapter;
|
||||
import android.widget.GridView;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.google.android.material.navigation.NavigationView;
|
||||
@@ -57,10 +56,8 @@ import androidx.core.content.ContextCompat;
|
||||
import androidx.drawerlayout.widget.DrawerLayout;
|
||||
import androidx.fragment.app.FragmentManager;
|
||||
import androidx.fragment.app.FragmentTransaction;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
import androidx.lifecycle.ViewModelProviders;
|
||||
import uk.co.samuelwall.materialtaptargetprompt.MaterialTapTargetPrompt;
|
||||
|
||||
import static android.view.View.GONE;
|
||||
import static android.view.View.VISIBLE;
|
||||
@@ -78,8 +75,6 @@ import static org.briarproject.briar.android.TestingConstants.IS_DEBUG_BUILD;
|
||||
import static org.briarproject.briar.android.activity.RequestCodes.REQUEST_PASSWORD;
|
||||
import static org.briarproject.briar.android.navdrawer.IntentRouter.handleExternalIntent;
|
||||
import static org.briarproject.briar.android.util.UiUtils.getDaysUntilExpiry;
|
||||
import static org.briarproject.briar.android.util.UiUtils.observeOnce;
|
||||
import static org.briarproject.briar.android.util.UiUtils.resolveColorAttribute;
|
||||
|
||||
@MethodsNotNullByDefault
|
||||
@ParametersNotNullByDefault
|
||||
@@ -102,9 +97,6 @@ public class NavDrawerActivity extends BriarActivity implements
|
||||
public static Uri SIGN_OUT_URI =
|
||||
Uri.parse("briar-content://org.briarproject.briar/sign-out");
|
||||
|
||||
private final List<Transport> transports = new ArrayList<>(3);
|
||||
private final MutableLiveData<ImageView> torIcon = new MutableLiveData<>();
|
||||
|
||||
private NavDrawerViewModel navDrawerViewModel;
|
||||
private PluginViewModel pluginViewModel;
|
||||
private ActionBarDrawerToggle drawerToggle;
|
||||
@@ -118,6 +110,7 @@ public class NavDrawerActivity extends BriarActivity implements
|
||||
private DrawerLayout drawerLayout;
|
||||
private NavigationView navigation;
|
||||
|
||||
private List<Transport> transports;
|
||||
private BaseAdapter transportsAdapter;
|
||||
|
||||
@Override
|
||||
@@ -148,11 +141,6 @@ public class NavDrawerActivity extends BriarActivity implements
|
||||
drawerLayout = findViewById(R.id.drawer_layout);
|
||||
navigation = findViewById(R.id.navigation);
|
||||
GridView transportsView = findViewById(R.id.transportsView);
|
||||
LinearLayout transportsLayout = findViewById(R.id.transports);
|
||||
transportsLayout.setOnClickListener(v -> {
|
||||
LOG.info("Starting transports activity");
|
||||
startActivity(new Intent(this, TransportsActivity.class));
|
||||
});
|
||||
|
||||
setSupportActionBar(toolbar);
|
||||
ActionBar actionBar = requireNonNull(getSupportActionBar());
|
||||
@@ -161,23 +149,13 @@ public class NavDrawerActivity extends BriarActivity implements
|
||||
|
||||
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
|
||||
R.string.nav_drawer_open_description,
|
||||
R.string.nav_drawer_close_description) {
|
||||
@Override
|
||||
public void onDrawerOpened(View drawerView) {
|
||||
super.onDrawerOpened(drawerView);
|
||||
navDrawerViewModel.checkTransportsOnboarding();
|
||||
}
|
||||
};
|
||||
R.string.nav_drawer_close_description);
|
||||
drawerLayout.addDrawerListener(drawerToggle);
|
||||
navigation.setNavigationItemSelectedListener(this);
|
||||
|
||||
initializeTransports();
|
||||
transportsView.setAdapter(transportsAdapter);
|
||||
|
||||
observeOnce(navDrawerViewModel.showTransportsOnboarding(), this, show ->
|
||||
observeOnce(torIcon, this, imageView ->
|
||||
showTransportsOnboarding(show, imageView)));
|
||||
|
||||
lockManager.isLockable().observe(this, this::setLockVisible);
|
||||
|
||||
if (lifecycleManager.getLifecycleState().isAfter(RUNNING)) {
|
||||
@@ -402,6 +380,8 @@ public class NavDrawerActivity extends BriarActivity implements
|
||||
}
|
||||
|
||||
private void initializeTransports() {
|
||||
transports = new ArrayList<>(3);
|
||||
|
||||
transportsAdapter = new BaseAdapter() {
|
||||
|
||||
@Override
|
||||
@@ -442,8 +422,6 @@ public class NavDrawerActivity extends BriarActivity implements
|
||||
TextView text = view.findViewById(R.id.textView);
|
||||
text.setText(getString(t.label));
|
||||
|
||||
if (t.id.equals(TorConstants.ID)) torIcon.setValue(icon);
|
||||
|
||||
return view;
|
||||
}
|
||||
};
|
||||
@@ -466,7 +444,7 @@ public class NavDrawerActivity extends BriarActivity implements
|
||||
private Transport createTransport(TransportId id,
|
||||
@DrawableRes int iconDrawable, @StringRes int label) {
|
||||
int iconColor = getIconColor(STARTING_STOPPING);
|
||||
Transport transport = new Transport(id, iconDrawable, label, iconColor);
|
||||
Transport transport = new Transport(iconDrawable, label, iconColor);
|
||||
pluginViewModel.getPluginState(id).observe(this, state -> {
|
||||
transport.iconColor = getIconColor(state);
|
||||
transportsAdapter.notifyDataSetChanged();
|
||||
@@ -474,25 +452,8 @@ public class NavDrawerActivity extends BriarActivity implements
|
||||
return transport;
|
||||
}
|
||||
|
||||
private void showTransportsOnboarding(boolean show, ImageView imageView) {
|
||||
if (show) {
|
||||
int color = resolveColorAttribute(this, R.attr.colorControlNormal);
|
||||
new MaterialTapTargetPrompt.Builder(NavDrawerActivity.this,
|
||||
R.style.OnboardingDialogTheme).setTarget(imageView)
|
||||
.setPrimaryText(R.string.network_settings_title)
|
||||
.setSecondaryText(R.string.transports_onboarding_text)
|
||||
.setIcon(R.drawable.transport_tor)
|
||||
.setIconDrawableColourFilter(color)
|
||||
.setBackgroundColour(
|
||||
ContextCompat.getColor(this, R.color.briar_primary))
|
||||
.show();
|
||||
navDrawerViewModel.transportsOnboardingShown();
|
||||
}
|
||||
}
|
||||
|
||||
private static class Transport {
|
||||
|
||||
private final TransportId id;
|
||||
@DrawableRes
|
||||
private final int iconDrawable;
|
||||
@StringRes
|
||||
@@ -501,9 +462,8 @@ public class NavDrawerActivity extends BriarActivity implements
|
||||
@ColorRes
|
||||
private int iconColor;
|
||||
|
||||
private Transport(TransportId id, @DrawableRes int iconDrawable,
|
||||
@StringRes int label, @ColorRes int iconColor) {
|
||||
this.id = id;
|
||||
private Transport(@DrawableRes int iconDrawable, @StringRes int label,
|
||||
@ColorRes int iconColor) {
|
||||
this.iconDrawable = iconDrawable;
|
||||
this.label = label;
|
||||
this.iconColor = iconColor;
|
||||
|
||||
@@ -34,8 +34,6 @@ public class NavDrawerViewModel extends AndroidViewModel {
|
||||
getLogger(NavDrawerViewModel.class.getName());
|
||||
|
||||
private static final String EXPIRY_DATE_WARNING = "expiryDateWarning";
|
||||
private static final String SHOW_TRANSPORTS_ONBOARDING =
|
||||
"showTransportsOnboarding";
|
||||
|
||||
@DatabaseExecutor
|
||||
private final Executor dbExecutor;
|
||||
@@ -45,8 +43,6 @@ public class NavDrawerViewModel extends AndroidViewModel {
|
||||
new MutableLiveData<>();
|
||||
private final MutableLiveData<Boolean> shouldAskForDozeWhitelisting =
|
||||
new MutableLiveData<>();
|
||||
private final MutableLiveData<Boolean> showTransportsOnboarding =
|
||||
new MutableLiveData<>();
|
||||
|
||||
@Inject
|
||||
NavDrawerViewModel(Application app, @DatabaseExecutor Executor dbExecutor,
|
||||
@@ -132,39 +128,4 @@ public class NavDrawerViewModel extends AndroidViewModel {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@UiThread
|
||||
LiveData<Boolean> showTransportsOnboarding() {
|
||||
return showTransportsOnboarding;
|
||||
}
|
||||
|
||||
@UiThread
|
||||
void checkTransportsOnboarding() {
|
||||
if (showTransportsOnboarding.getValue() != null) return;
|
||||
dbExecutor.execute(() -> {
|
||||
try {
|
||||
Settings settings =
|
||||
settingsManager.getSettings(SETTINGS_NAMESPACE);
|
||||
boolean show =
|
||||
settings.getBoolean(SHOW_TRANSPORTS_ONBOARDING, true);
|
||||
showTransportsOnboarding.postValue(show);
|
||||
} catch (DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@UiThread
|
||||
void transportsOnboardingShown() {
|
||||
showTransportsOnboarding.setValue(false);
|
||||
dbExecutor.execute(() -> {
|
||||
try {
|
||||
Settings settings = new Settings();
|
||||
settings.putBoolean(SHOW_TRANSPORTS_ONBOARDING, false);
|
||||
settingsManager.mergeSettings(settings, SETTINGS_NAMESPACE);
|
||||
} catch (DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +1,8 @@
|
||||
package org.briarproject.briar.android.navdrawer;
|
||||
|
||||
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 org.briarproject.bramble.api.db.DatabaseExecutor;
|
||||
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.network.NetworkManager;
|
||||
import org.briarproject.bramble.api.network.NetworkStatus;
|
||||
import org.briarproject.bramble.api.network.event.NetworkStatusEvent;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.BluetoothConstants;
|
||||
import org.briarproject.bramble.api.plugin.LanTcpConstants;
|
||||
@@ -24,44 +12,28 @@ import org.briarproject.bramble.api.plugin.PluginManager;
|
||||
import org.briarproject.bramble.api.plugin.TorConstants;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportStateEvent;
|
||||
import org.briarproject.bramble.api.settings.Settings;
|
||||
import org.briarproject.bramble.api.settings.SettingsManager;
|
||||
import org.briarproject.bramble.api.settings.event.SettingsUpdatedEvent;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.lifecycle.AndroidViewModel;
|
||||
import androidx.lifecycle.LiveData;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
import androidx.lifecycle.ViewModel;
|
||||
|
||||
import static android.bluetooth.BluetoothAdapter.ACTION_STATE_CHANGED;
|
||||
import static android.bluetooth.BluetoothAdapter.EXTRA_STATE;
|
||||
import static android.bluetooth.BluetoothAdapter.STATE_ON;
|
||||
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.PREF_PLUGIN_ENABLE;
|
||||
import static org.briarproject.bramble.api.plugin.Plugin.State.STARTING_STOPPING;
|
||||
import static org.briarproject.bramble.util.LogUtils.logDuration;
|
||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||
import static org.briarproject.bramble.util.LogUtils.now;
|
||||
|
||||
@NotNullByDefault
|
||||
public class PluginViewModel extends AndroidViewModel implements EventListener {
|
||||
public class PluginViewModel extends ViewModel implements EventListener {
|
||||
|
||||
private static final Logger LOG =
|
||||
getLogger(PluginViewModel.class.getName());
|
||||
|
||||
private final Application app;
|
||||
private final Executor dbExecutor;
|
||||
private final SettingsManager settingsManager;
|
||||
private final PluginManager pluginManager;
|
||||
private final EventBus eventBus;
|
||||
private final BroadcastReceiver receiver;
|
||||
|
||||
private final MutableLiveData<State> torPluginState =
|
||||
new MutableLiveData<>();
|
||||
@@ -70,68 +42,24 @@ public class PluginViewModel extends AndroidViewModel implements EventListener {
|
||||
private final MutableLiveData<State> btPluginState =
|
||||
new MutableLiveData<>();
|
||||
|
||||
private final MutableLiveData<Boolean> torEnabledSetting =
|
||||
new MutableLiveData<>(false);
|
||||
private final MutableLiveData<Boolean> wifiEnabledSetting =
|
||||
new MutableLiveData<>(false);
|
||||
private final MutableLiveData<Boolean> btEnabledSetting =
|
||||
new MutableLiveData<>(false);
|
||||
|
||||
private final MutableLiveData<NetworkStatus> networkStatus =
|
||||
new MutableLiveData<>();
|
||||
|
||||
private final MutableLiveData<Boolean> bluetoothTurnedOn =
|
||||
new MutableLiveData<>(false);
|
||||
|
||||
@Inject
|
||||
PluginViewModel(Application app, @DatabaseExecutor Executor dbExecutor,
|
||||
SettingsManager settingsManager, PluginManager pluginManager,
|
||||
EventBus eventBus, NetworkManager networkManager) {
|
||||
super(app);
|
||||
this.app = app;
|
||||
this.dbExecutor = dbExecutor;
|
||||
this.settingsManager = settingsManager;
|
||||
PluginViewModel(PluginManager pluginManager, EventBus eventBus) {
|
||||
this.pluginManager = pluginManager;
|
||||
this.eventBus = eventBus;
|
||||
eventBus.addListener(this);
|
||||
receiver = new BluetoothStateReceiver();
|
||||
app.registerReceiver(receiver, new IntentFilter(ACTION_STATE_CHANGED));
|
||||
networkStatus.setValue(networkManager.getNetworkStatus());
|
||||
torPluginState.setValue(getTransportState(TorConstants.ID));
|
||||
wifiPluginState.setValue(getTransportState(LanTcpConstants.ID));
|
||||
btPluginState.setValue(getTransportState(BluetoothConstants.ID));
|
||||
initialiseBluetoothState();
|
||||
loadSettings();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCleared() {
|
||||
eventBus.removeListener(this);
|
||||
app.unregisterReceiver(receiver);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void eventOccurred(Event e) {
|
||||
if (e instanceof NetworkStatusEvent) {
|
||||
networkStatus.setValue(((NetworkStatusEvent) e).getStatus());
|
||||
} else if (e instanceof SettingsUpdatedEvent) {
|
||||
SettingsUpdatedEvent s = (SettingsUpdatedEvent) e;
|
||||
if (s.getNamespace().equals(TorConstants.ID.getString())) {
|
||||
boolean enable = s.getSettings().getBoolean(PREF_PLUGIN_ENABLE,
|
||||
TorConstants.DEFAULT_PREF_PLUGIN_ENABLE);
|
||||
torEnabledSetting.setValue(enable);
|
||||
} else if (s.getNamespace().equals(
|
||||
LanTcpConstants.ID.getString())) {
|
||||
boolean enable = s.getSettings().getBoolean(PREF_PLUGIN_ENABLE,
|
||||
LanTcpConstants.DEFAULT_PREF_PLUGIN_ENABLE);
|
||||
wifiEnabledSetting.setValue(enable);
|
||||
} else if (s.getNamespace().equals(
|
||||
BluetoothConstants.ID.getString())) {
|
||||
boolean enable = s.getSettings().getBoolean(PREF_PLUGIN_ENABLE,
|
||||
BluetoothConstants.DEFAULT_PREF_PLUGIN_ENABLE);
|
||||
btEnabledSetting.setValue(enable);
|
||||
}
|
||||
} else if (e instanceof TransportStateEvent) {
|
||||
if (e instanceof TransportStateEvent) {
|
||||
TransportStateEvent t = (TransportStateEvent) e;
|
||||
TransportId id = t.getTransportId();
|
||||
State state = t.getState();
|
||||
@@ -149,62 +77,6 @@ public class PluginViewModel extends AndroidViewModel implements EventListener {
|
||||
return liveData;
|
||||
}
|
||||
|
||||
LiveData<Boolean> getPluginEnabledSetting(TransportId id) {
|
||||
if (id.equals(TorConstants.ID)) return torEnabledSetting;
|
||||
else if (id.equals(LanTcpConstants.ID)) return wifiEnabledSetting;
|
||||
else if (id.equals(BluetoothConstants.ID)) return btEnabledSetting;
|
||||
else throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
LiveData<NetworkStatus> getNetworkStatus() {
|
||||
return networkStatus;
|
||||
}
|
||||
|
||||
LiveData<Boolean> getBluetoothTurnedOn() {
|
||||
return bluetoothTurnedOn;
|
||||
}
|
||||
|
||||
int getReasonsTorDisabled() {
|
||||
Plugin plugin = pluginManager.getPlugin(TorConstants.ID);
|
||||
return plugin == null ? 0 : plugin.getReasonsDisabled();
|
||||
}
|
||||
|
||||
void enableTransport(TransportId id, boolean enable) {
|
||||
Settings s = new Settings();
|
||||
s.putBoolean(PREF_PLUGIN_ENABLE, enable);
|
||||
mergeSettings(s, id.getString());
|
||||
}
|
||||
|
||||
private void initialiseBluetoothState() {
|
||||
BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter();
|
||||
if (bt == null) bluetoothTurnedOn.setValue(false);
|
||||
else bluetoothTurnedOn.setValue(bt.getState() == STATE_ON);
|
||||
}
|
||||
|
||||
private void loadSettings() {
|
||||
dbExecutor.execute(() -> {
|
||||
try {
|
||||
boolean tor = isPluginEnabled(TorConstants.ID,
|
||||
TorConstants.DEFAULT_PREF_PLUGIN_ENABLE);
|
||||
torEnabledSetting.postValue(tor);
|
||||
boolean wifi = isPluginEnabled(LanTcpConstants.ID,
|
||||
LanTcpConstants.DEFAULT_PREF_PLUGIN_ENABLE);
|
||||
wifiEnabledSetting.postValue(wifi);
|
||||
boolean bt = isPluginEnabled(BluetoothConstants.ID,
|
||||
BluetoothConstants.DEFAULT_PREF_PLUGIN_ENABLE);
|
||||
btEnabledSetting.postValue(bt);
|
||||
} catch (DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private boolean isPluginEnabled(TransportId id, boolean defaultValue)
|
||||
throws DbException {
|
||||
Settings s = settingsManager.getSettings(id.getString());
|
||||
return s.getBoolean(PREF_PLUGIN_ENABLE, defaultValue);
|
||||
}
|
||||
|
||||
private State getTransportState(TransportId id) {
|
||||
Plugin plugin = pluginManager.getPlugin(id);
|
||||
return plugin == null ? STARTING_STOPPING : plugin.getState();
|
||||
@@ -217,26 +89,4 @@ public class PluginViewModel extends AndroidViewModel implements EventListener {
|
||||
else if (id.equals(BluetoothConstants.ID)) return btPluginState;
|
||||
else return null;
|
||||
}
|
||||
|
||||
private void mergeSettings(Settings s, String namespace) {
|
||||
dbExecutor.execute(() -> {
|
||||
try {
|
||||
long start = now();
|
||||
settingsManager.mergeSettings(s, namespace);
|
||||
logDuration(LOG, "Merging settings", start);
|
||||
} catch (DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private class BluetoothStateReceiver extends BroadcastReceiver {
|
||||
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
int state = intent.getIntExtra(EXTRA_STATE, 0);
|
||||
if (state == STATE_ON) bluetoothTurnedOn.postValue(true);
|
||||
else bluetoothTurnedOn.postValue(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,360 +0,0 @@
|
||||
package org.briarproject.briar.android.navdrawer;
|
||||
|
||||
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.BaseAdapter;
|
||||
import android.widget.GridView;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.TextView;
|
||||
|
||||
import org.briarproject.bramble.api.network.NetworkStatus;
|
||||
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.State;
|
||||
import org.briarproject.bramble.api.plugin.TorConstants;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
import org.briarproject.briar.R;
|
||||
import org.briarproject.briar.android.activity.ActivityComponent;
|
||||
import org.briarproject.briar.android.activity.BriarActivity;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
||||
import androidx.annotation.ColorRes;
|
||||
import androidx.annotation.DrawableRes;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.annotation.StringRes;
|
||||
import androidx.appcompat.app.ActionBar;
|
||||
import androidx.appcompat.widget.SwitchCompat;
|
||||
import androidx.core.content.ContextCompat;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
import androidx.lifecycle.ViewModelProviders;
|
||||
|
||||
import static android.view.View.GONE;
|
||||
import static android.view.View.VISIBLE;
|
||||
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.ENABLING;
|
||||
import static org.briarproject.bramble.api.plugin.Plugin.State.STARTING_STOPPING;
|
||||
import static org.briarproject.bramble.api.plugin.TorConstants.REASON_BATTERY;
|
||||
import static org.briarproject.bramble.api.plugin.TorConstants.REASON_COUNTRY_BLOCKED;
|
||||
import static org.briarproject.bramble.api.plugin.TorConstants.REASON_MOBILE_DATA;
|
||||
import static org.briarproject.briar.android.util.UiUtils.showOnboardingDialog;
|
||||
|
||||
@MethodsNotNullByDefault
|
||||
@ParametersNotNullByDefault
|
||||
public class TransportsActivity extends BriarActivity {
|
||||
|
||||
@Inject
|
||||
ViewModelProvider.Factory viewModelFactory;
|
||||
|
||||
private final List<Transport> transports = new ArrayList<>(3);
|
||||
|
||||
private PluginViewModel viewModel;
|
||||
private BaseAdapter transportsAdapter;
|
||||
|
||||
@Override
|
||||
public void onCreate(@Nullable Bundle state) {
|
||||
super.onCreate(state);
|
||||
|
||||
ActionBar actionBar = getSupportActionBar();
|
||||
if (actionBar != null) {
|
||||
actionBar.setHomeButtonEnabled(true);
|
||||
actionBar.setDisplayHomeAsUpEnabled(true);
|
||||
}
|
||||
|
||||
setContentView(R.layout.activity_transports);
|
||||
|
||||
ViewModelProvider provider =
|
||||
ViewModelProviders.of(this, viewModelFactory);
|
||||
viewModel = provider.get(PluginViewModel.class);
|
||||
|
||||
GridView grid = findViewById(R.id.grid);
|
||||
initializeCards();
|
||||
grid.setAdapter(transportsAdapter);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void injectActivity(ActivityComponent component) {
|
||||
component.inject(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(MenuItem item) {
|
||||
if (item.getItemId() == android.R.id.home) {
|
||||
onBackPressed();
|
||||
return true;
|
||||
} else if (item.getItemId() == R.id.action_help) {
|
||||
String text = getString(R.string.transports_help_text);
|
||||
showOnboardingDialog(this, text);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCreateOptionsMenu(Menu menu) {
|
||||
MenuInflater inflater = getMenuInflater();
|
||||
inflater.inflate(R.menu.help_action, menu);
|
||||
return super.onCreateOptionsMenu(menu);
|
||||
}
|
||||
|
||||
private void initializeCards() {
|
||||
transportsAdapter = new BaseAdapter() {
|
||||
|
||||
@Override
|
||||
public int getCount() {
|
||||
return transports.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Transport getItem(int position) {
|
||||
return transports.get(position);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getItemId(int position) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public View getView(int position, View convertView,
|
||||
ViewGroup parent) {
|
||||
View view;
|
||||
if (convertView != null) {
|
||||
view = convertView;
|
||||
} else {
|
||||
LayoutInflater inflater = getLayoutInflater();
|
||||
view = inflater.inflate(R.layout.list_item_transport_card,
|
||||
parent, false);
|
||||
}
|
||||
|
||||
Transport t = getItem(position);
|
||||
|
||||
ImageView icon = view.findViewById(R.id.icon);
|
||||
icon.setImageDrawable(ContextCompat.getDrawable(
|
||||
TransportsActivity.this, t.iconDrawable));
|
||||
icon.setColorFilter(ContextCompat.getColor(
|
||||
TransportsActivity.this, t.iconColor));
|
||||
|
||||
TextView title = view.findViewById(R.id.title);
|
||||
title.setText(getString(t.title));
|
||||
|
||||
SwitchCompat switchCompat =
|
||||
view.findViewById(R.id.switchCompat);
|
||||
switchCompat.setText(getString(t.switchLabel));
|
||||
switchCompat.setOnClickListener(v ->
|
||||
viewModel.enableTransport(t.id,
|
||||
switchCompat.isChecked()));
|
||||
switchCompat.setChecked(t.isSwitchChecked);
|
||||
|
||||
TextView summary = view.findViewById(R.id.summary);
|
||||
if (t.summary == 0) {
|
||||
summary.setVisibility(GONE);
|
||||
} else {
|
||||
summary.setText(t.summary);
|
||||
summary.setVisibility(VISIBLE);
|
||||
}
|
||||
|
||||
TextView deviceStatus = view.findViewById(R.id.deviceStatus);
|
||||
deviceStatus.setText(getBulletString(t.deviceStatus));
|
||||
|
||||
TextView pluginStatus = view.findViewById(R.id.appStatus);
|
||||
pluginStatus.setText(getBulletString(t.pluginStatus));
|
||||
pluginStatus.setVisibility(t.showPluginStatus ? VISIBLE : GONE);
|
||||
|
||||
return view;
|
||||
}
|
||||
};
|
||||
|
||||
Transport tor = createTransport(TorConstants.ID,
|
||||
R.drawable.transport_tor, R.string.transport_tor,
|
||||
R.string.tor_enable_title, R.string.tor_enable_summary,
|
||||
R.string.tor_device_status_offline,
|
||||
R.string.tor_plugin_status_inactive);
|
||||
transports.add(tor);
|
||||
|
||||
Transport wifi = createTransport(LanTcpConstants.ID,
|
||||
R.drawable.transport_lan, R.string.transport_lan_long,
|
||||
R.string.wifi_setting, 0, R.string.lan_device_status_off,
|
||||
R.string.lan_plugin_status_inactive);
|
||||
transports.add(wifi);
|
||||
|
||||
Transport bt = createTransport(BluetoothConstants.ID,
|
||||
R.drawable.transport_bt, R.string.transport_bt,
|
||||
R.string.bluetooth_setting, 0, R.string.bt_device_status_off,
|
||||
R.string.bt_plugin_status_inactive);
|
||||
transports.add(bt);
|
||||
|
||||
viewModel.getNetworkStatus().observe(this, status -> {
|
||||
updateTorResources(tor, status);
|
||||
updateWifiResources(wifi, status);
|
||||
transportsAdapter.notifyDataSetChanged();
|
||||
});
|
||||
|
||||
viewModel.getBluetoothTurnedOn().observe(this, on -> {
|
||||
updateBtResources(bt, on);
|
||||
transportsAdapter.notifyDataSetChanged();
|
||||
});
|
||||
}
|
||||
|
||||
private String getBulletString(@StringRes int resId) {
|
||||
return "\u2022 " + getString(resId);
|
||||
}
|
||||
|
||||
@ColorRes
|
||||
private int getIconColor(State state) {
|
||||
if (state == ACTIVE) return R.color.briar_lime_400;
|
||||
else if (state == ENABLING) return R.color.briar_orange_500;
|
||||
else return android.R.color.tertiary_text_light;
|
||||
}
|
||||
|
||||
private void updateTorResources(Transport tor, NetworkStatus status) {
|
||||
if (status.isConnected()) {
|
||||
if (status.isWifi()) {
|
||||
tor.deviceStatus = R.string.tor_device_status_online_wifi;
|
||||
} else {
|
||||
tor.deviceStatus = R.string.tor_device_status_online_mobile;
|
||||
}
|
||||
tor.showPluginStatus = true;
|
||||
} else {
|
||||
tor.deviceStatus = R.string.tor_device_status_offline;
|
||||
tor.showPluginStatus = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void updateWifiResources(Transport wifi, NetworkStatus status) {
|
||||
if (status.isWifi()) {
|
||||
wifi.deviceStatus = R.string.lan_device_status_on;
|
||||
wifi.showPluginStatus = true;
|
||||
} else {
|
||||
wifi.deviceStatus = R.string.lan_device_status_off;
|
||||
wifi.showPluginStatus = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void updateBtResources(Transport bt, boolean on) {
|
||||
if (on) {
|
||||
bt.deviceStatus = R.string.bt_device_status_on;
|
||||
bt.showPluginStatus = true;
|
||||
} else {
|
||||
bt.deviceStatus = R.string.bt_device_status_off;
|
||||
bt.showPluginStatus = false;
|
||||
}
|
||||
}
|
||||
|
||||
@StringRes
|
||||
private int getPluginStatus(TransportId id, State state) {
|
||||
if (id.equals(TorConstants.ID)) {
|
||||
return getTorPluginStatus(state);
|
||||
} else if (id.equals(LanTcpConstants.ID)) {
|
||||
return getWifiPluginStatus(state);
|
||||
} else if (id.equals(BluetoothConstants.ID)) {
|
||||
return getBtPluginStatus(state);
|
||||
} else throw new AssertionError();
|
||||
}
|
||||
|
||||
@StringRes
|
||||
private int getTorPluginStatus(State state) {
|
||||
if (state == ENABLING) {
|
||||
return R.string.tor_plugin_status_enabling;
|
||||
} else if (state == ACTIVE) {
|
||||
return R.string.tor_plugin_status_active;
|
||||
} else if (state == DISABLED) {
|
||||
int reasons = viewModel.getReasonsTorDisabled();
|
||||
if ((reasons & REASON_MOBILE_DATA) != 0) {
|
||||
return R.string.tor_plugin_status_disabled_mobile_data;
|
||||
} else if ((reasons & REASON_BATTERY) != 0) {
|
||||
return R.string.tor_plugin_status_disabled_battery;
|
||||
} else if ((reasons & REASON_COUNTRY_BLOCKED) != 0) {
|
||||
return R.string.tor_plugin_status_disabled_country_blocked;
|
||||
} else {
|
||||
return R.string.tor_plugin_status_disabled;
|
||||
}
|
||||
} else {
|
||||
return R.string.tor_plugin_status_inactive;
|
||||
}
|
||||
}
|
||||
|
||||
@StringRes
|
||||
private int getWifiPluginStatus(State state) {
|
||||
if (state == ENABLING) return R.string.lan_plugin_status_enabling;
|
||||
else if (state == ACTIVE) return R.string.lan_plugin_status_active;
|
||||
else if (state == DISABLED) return R.string.lan_plugin_status_disabled;
|
||||
else return R.string.lan_plugin_status_inactive;
|
||||
}
|
||||
|
||||
@StringRes
|
||||
private int getBtPluginStatus(State state) {
|
||||
if (state == ENABLING) return R.string.bt_plugin_status_enabling;
|
||||
else if (state == ACTIVE) return R.string.bt_plugin_status_active;
|
||||
else if (state == DISABLED) return R.string.bt_plugin_status_disabled;
|
||||
else return R.string.bt_plugin_status_inactive;
|
||||
}
|
||||
|
||||
private Transport createTransport(TransportId id,
|
||||
@DrawableRes int iconDrawable, @StringRes int title,
|
||||
@StringRes int switchLabel, @StringRes int summary,
|
||||
@StringRes int deviceStatus, @StringRes int pluginStatus) {
|
||||
int iconColor = getIconColor(STARTING_STOPPING);
|
||||
Transport transport = new Transport(id, iconDrawable, iconColor, title,
|
||||
switchLabel, false, summary, deviceStatus, pluginStatus, false);
|
||||
viewModel.getPluginState(id).observe(this, state -> {
|
||||
transport.iconColor = getIconColor(state);
|
||||
transport.pluginStatus = getPluginStatus(transport.id, state);
|
||||
transportsAdapter.notifyDataSetChanged();
|
||||
});
|
||||
viewModel.getPluginEnabledSetting(id).observe(this, enabled -> {
|
||||
transport.isSwitchChecked = enabled;
|
||||
transportsAdapter.notifyDataSetChanged();
|
||||
});
|
||||
return transport;
|
||||
}
|
||||
|
||||
private static class Transport {
|
||||
|
||||
private final TransportId id;
|
||||
|
||||
@DrawableRes
|
||||
private final int iconDrawable;
|
||||
@StringRes
|
||||
private final int title, switchLabel, summary;
|
||||
|
||||
@ColorRes
|
||||
private int iconColor;
|
||||
@StringRes
|
||||
private int deviceStatus, pluginStatus;
|
||||
private boolean isSwitchChecked, showPluginStatus;
|
||||
|
||||
private Transport(TransportId id,
|
||||
@DrawableRes int iconDrawable,
|
||||
@ColorRes int iconColor,
|
||||
@StringRes int title,
|
||||
@StringRes int switchLabel,
|
||||
boolean isSwitchChecked,
|
||||
@StringRes int summary,
|
||||
@StringRes int deviceStatus,
|
||||
@StringRes int pluginStatus,
|
||||
boolean showPluginStatus) {
|
||||
this.id = id;
|
||||
this.iconDrawable = iconDrawable;
|
||||
this.iconColor = iconColor;
|
||||
this.title = title;
|
||||
this.switchLabel = switchLabel;
|
||||
this.isSwitchChecked = isSwitchChecked;
|
||||
this.summary = summary;
|
||||
this.deviceStatus = deviceStatus;
|
||||
this.pluginStatus = pluginStatus;
|
||||
this.showPluginStatus = showPluginStatus;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,7 @@ import org.briarproject.bramble.plugin.tor.CircumventionProvider;
|
||||
import org.briarproject.bramble.util.StringUtils;
|
||||
import org.briarproject.briar.R;
|
||||
import org.briarproject.briar.android.Localizer;
|
||||
import org.briarproject.briar.android.account.AccountUtils;
|
||||
import org.briarproject.briar.android.util.UiUtils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@@ -251,9 +252,23 @@ public class SettingsFragment extends PreferenceFragmentCompat
|
||||
throw new RuntimeException("Boom!");
|
||||
}
|
||||
);
|
||||
findPreference("pref_key_export").setOnPreferenceClickListener(
|
||||
preference -> {
|
||||
AccountUtils.exportAccount(requireContext());
|
||||
return true;
|
||||
}
|
||||
);
|
||||
findPreference("pref_key_import").setOnPreferenceClickListener(
|
||||
preference -> {
|
||||
AccountUtils.importAccount(requireContext());
|
||||
return true;
|
||||
}
|
||||
);
|
||||
} else {
|
||||
findPreference("pref_key_explode").setVisible(false);
|
||||
findPreference("pref_key_test_data").setVisible(false);
|
||||
findPreference("pref_key_export").setVisible(false);
|
||||
findPreference("pref_key_import").setVisible(false);
|
||||
PreferenceGroup testing =
|
||||
findPreference("pref_key_explode").getParent();
|
||||
if (testing == null) throw new AssertionError();
|
||||
|
||||
@@ -79,7 +79,7 @@ public class ImagePreview extends ConstraintLayout {
|
||||
((ImagePreviewAdapter) imageList.getAdapter());
|
||||
int pos = requireNonNull(adapter).loadItemPreview(result);
|
||||
if (pos != NO_POSITION) {
|
||||
imageList.scrollToPosition(pos);
|
||||
imageList.smoothScrollToPosition(pos);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,22 +12,6 @@ import androidx.lifecycle.Observer;
|
||||
@NotNullByDefault
|
||||
public class LiveEvent<T> extends LiveData<LiveEvent.ConsumableEvent<T>> {
|
||||
|
||||
/**
|
||||
* Creates a LiveEvent initialized with the given {@code value}.
|
||||
*
|
||||
* @param value initial value
|
||||
*/
|
||||
public LiveEvent(T value) {
|
||||
super(new ConsumableEvent<>(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a LiveEvent with no value assigned to it.
|
||||
*/
|
||||
public LiveEvent() {
|
||||
super();
|
||||
}
|
||||
|
||||
public void observeEvent(LifecycleOwner owner,
|
||||
LiveEventHandler<T> handler) {
|
||||
LiveEventObserver<T> observer = new LiveEventObserver<>(handler);
|
||||
|
||||
@@ -5,22 +5,6 @@ import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
@NotNullByDefault
|
||||
public class MutableLiveEvent<T> extends LiveEvent<T> {
|
||||
|
||||
/**
|
||||
* Creates a MutableLiveEvent initialized with the given {@code value}.
|
||||
*
|
||||
* @param value initial value
|
||||
*/
|
||||
public MutableLiveEvent(T value) {
|
||||
super(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a MutableLiveEvent with no value assigned to it.
|
||||
*/
|
||||
public MutableLiveEvent() {
|
||||
super();
|
||||
}
|
||||
|
||||
public void postEvent(T value) {
|
||||
super.postValue(new ConsumableEvent<>(value));
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user