diff --git a/src/main/AndroidManifest.xml b/src/main/AndroidManifest.xml index c5c4ce362..36c36b98e 100644 --- a/src/main/AndroidManifest.xml +++ b/src/main/AndroidManifest.xml @@ -1,28 +1,53 @@ - - - - - - - - - - + + + + + + + + + - + - + - + - + @@ -38,470 +63,530 @@ - + - + - + - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + android:largeHeap="true" + tools:ignore="GoogleAppIndexingWarning" + android:requestLegacyExternalStorage="true" + tools:targetApi="TIRAMISU" + android:hasFragileUserData="true"> - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - + - + + + + + + + + + + + - - + + + + + + + - + + + + + + + + + + + + - - - - - - + - - - - - + - - - - - - - + - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/org/thoughtcrime/securesms/ApplicationContext.java b/src/main/java/org/thoughtcrime/securesms/ApplicationContext.java index 84dfc246c..83508d97a 100644 --- a/src/main/java/org/thoughtcrime/securesms/ApplicationContext.java +++ b/src/main/java/org/thoughtcrime/securesms/ApplicationContext.java @@ -9,7 +9,6 @@ import android.net.LinkProperties; import android.net.NetworkCapabilities; import android.os.Build; import android.util.Log; - import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatDelegate; import androidx.core.app.NotificationManagerCompat; @@ -19,14 +18,16 @@ import androidx.work.ExistingPeriodicWorkPolicy; import androidx.work.NetworkType; import androidx.work.PeriodicWorkRequest; import androidx.work.WorkManager; - +import chat.delta.rpc.Rpc; +import chat.delta.rpc.RpcException; import com.b44t.messenger.DcAccounts; import com.b44t.messenger.DcContext; import com.b44t.messenger.DcEvent; import com.b44t.messenger.DcEventChannel; import com.b44t.messenger.DcEventEmitter; import com.b44t.messenger.FFITransport; - +import java.io.File; +import java.util.concurrent.TimeUnit; import org.thoughtcrime.securesms.calls.CallCoordinator; import org.thoughtcrime.securesms.connect.AccountManager; import org.thoughtcrime.securesms.connect.DcEventCenter; @@ -49,33 +50,27 @@ import org.thoughtcrime.securesms.util.SignalProtocolLoggerProvider; import org.thoughtcrime.securesms.util.Util; import org.thoughtcrime.securesms.webxdc.WebxdcGarbageCollectionWorker; -import java.io.File; -import java.util.concurrent.TimeUnit; - -import chat.delta.rpc.Rpc; -import chat.delta.rpc.RpcException; - public class ApplicationContext extends MultiDexApplication { private static final String TAG = ApplicationContext.class.getSimpleName(); private static final Object initLock = new Object(); private static volatile boolean isInitialized = false; - private static DcAccounts dcAccounts; - private Rpc rpc; - private DcContext dcContext; + private static DcAccounts dcAccounts; + private Rpc rpc; + private DcContext dcContext; - private DcLocationManager dcLocationManager; - private DcEventCenter eventCenter; - private NotificationCenter notificationCenter; - private JobManager jobManager; + private DcLocationManager dcLocationManager; + private DcEventCenter eventCenter; + private NotificationCenter notificationCenter; + private JobManager jobManager; - private int debugOnAvailableCount; - private int debugOnBlockedStatusChangedCount; - private int debugOnCapabilitiesChangedCount; - private int debugOnLinkPropertiesChangedCount; + private int debugOnAvailableCount; + private int debugOnBlockedStatusChangedCount; + private int debugOnCapabilitiesChangedCount; + private int debugOnLinkPropertiesChangedCount; public static ApplicationContext getInstance(@NonNull Context context) { - return (ApplicationContext)context.getApplicationContext(); + return (ApplicationContext) context.getApplicationContext(); } private static void ensureInitialized() { @@ -92,8 +87,8 @@ public class ApplicationContext extends MultiDexApplication { } /** - * Get DcAccounts instance, waiting for initialization if necessary. - * This method is thread-safe and will block until initialization is complete. + * Get DcAccounts instance, waiting for initialization if necessary. This method is thread-safe + * and will block until initialization is complete. */ public static DcAccounts getDcAccounts() { ensureInitialized(); @@ -101,8 +96,8 @@ public class ApplicationContext extends MultiDexApplication { } /** - * Get Rpc instance, waiting for initialization if necessary. - * This method is thread-safe and will block until initialization is complete. + * Get Rpc instance, waiting for initialization if necessary. This method is thread-safe and will + * block until initialization is complete. */ public Rpc getRpc() { ensureInitialized(); @@ -110,8 +105,8 @@ public class ApplicationContext extends MultiDexApplication { } /** - * Get DcContext instance, waiting for initialization if necessary. - * This method is thread-safe and will block until initialization is complete. + * Get DcContext instance, waiting for initialization if necessary. This method is thread-safe and + * will block until initialization is complete. */ public DcContext getDcContext() { ensureInitialized(); @@ -120,8 +115,8 @@ public class ApplicationContext extends MultiDexApplication { /** * Set DcContext instance. This should only be called by AccountManager when switching accounts, - * which only happens after initial initialization is complete. - * This method is thread-safe but does NOT trigger initialization or notify waiting threads. + * which only happens after initial initialization is complete. This method is thread-safe but + * does NOT trigger initialization or notify waiting threads. */ public void setDcContext(DcContext dcContext) { synchronized (initLock) { @@ -130,8 +125,8 @@ public class ApplicationContext extends MultiDexApplication { } /** - * Get DcLocationManager instance, waiting for initialization if necessary. - * This method is thread-safe and will block until initialization is complete. + * Get DcLocationManager instance, waiting for initialization if necessary. This method is + * thread-safe and will block until initialization is complete. */ public DcLocationManager getLocationManager() { ensureInitialized(); @@ -139,8 +134,8 @@ public class ApplicationContext extends MultiDexApplication { } /** - * Get DcEventCenter instance, waiting for initialization if necessary. - * This method is thread-safe and will block until initialization is complete. + * Get DcEventCenter instance, waiting for initialization if necessary. This method is thread-safe + * and will block until initialization is complete. */ public DcEventCenter getEventCenter() { ensureInitialized(); @@ -148,8 +143,8 @@ public class ApplicationContext extends MultiDexApplication { } /** - * Get NotificationCenter instance, waiting for initialization if necessary. - * This method is thread-safe and will block until initialization is complete. + * Get NotificationCenter instance, waiting for initialization if necessary. This method is + * thread-safe and will block until initialization is complete. */ public NotificationCenter getNotificationCenter() { ensureInitialized(); @@ -172,90 +167,114 @@ public class ApplicationContext extends MultiDexApplication { System.loadLibrary("native-utils"); // Initialize DcAccounts in background to avoid ANR during SQL migrations - Util.runOnBackground(() -> { - synchronized (initLock) { - try { - DcEventChannel eventChannel = new DcEventChannel(); - DcEventEmitter emitter = eventChannel.getEventEmitter(); - eventCenter = new DcEventCenter(this); - - new Thread(() -> { - Log.i(TAG, "Starting event loop"); - while (true) { - DcEvent event = emitter.getNextEvent(); - if (event == null) { - break; - } - if (isInitialized) { - eventCenter.handleEvent(event); - } else { - // not fully initialized, only handle logging events, - // ex. account migrations during DcAccounts initialization - eventCenter.handleLogging(event); - } - } - Log.i("DeltaChat", "shutting down event handler"); - }, "eventThread").start(); - - dcAccounts = new DcAccounts(new File(getFilesDir(), "accounts").getAbsolutePath(), eventChannel); - Log.i(TAG, "DcAccounts created"); - rpc = new Rpc(new FFITransport(dcAccounts.getJsonrpcInstance())); - Log.i(TAG, "Rpc created"); - AccountManager.getInstance().migrateToDcAccounts(this); - - int[] allAccounts = dcAccounts.getAll(); - Log.i(TAG, "Number of profiles: " + allAccounts.length); - for (int accountId : allAccounts) { - DcContext ac = dcAccounts.getAccount(accountId); - if (!ac.isOpen()) { - try { - DatabaseSecret secret = DatabaseSecretProvider.getOrCreateDatabaseSecret(this, accountId); - boolean res = ac.open(secret.asString()); - if (res) Log.i(TAG, "Successfully opened account " + accountId + ", path: " + ac.getBlobdir()); - else Log.e(TAG, "Error opening account " + accountId + ", path: " + ac.getBlobdir()); - } catch (Exception e) { - Log.e(TAG, "Failed to open account " + accountId + ", path: " + ac.getBlobdir() + ": " + e); - e.printStackTrace(); - } - } - - // 2025-12-16: The setting was removed. - // Revert it to the default if it was changed in the past. - ac.setConfigInt("webxdc_realtime_enabled", 1); - - // 2025-11-12: this is needed until core starts ignoring "delete_server_after" for chatmail - if (ac.isChatmail()) { - ac.setConfig("delete_server_after", null); // reset - } - } - if (allAccounts.length == 0) { + Util.runOnBackground( + () -> { + synchronized (initLock) { try { - rpc.addAccount(); - } catch (RpcException e) { - e.printStackTrace(); + DcEventChannel eventChannel = new DcEventChannel(); + DcEventEmitter emitter = eventChannel.getEventEmitter(); + eventCenter = new DcEventCenter(this); + + new Thread( + () -> { + Log.i(TAG, "Starting event loop"); + while (true) { + DcEvent event = emitter.getNextEvent(); + if (event == null) { + break; + } + if (isInitialized) { + eventCenter.handleEvent(event); + } else { + // not fully initialized, only handle logging events, + // ex. account migrations during DcAccounts initialization + eventCenter.handleLogging(event); + } + } + Log.i("DeltaChat", "shutting down event handler"); + }, + "eventThread") + .start(); + + dcAccounts = + new DcAccounts( + new File(getFilesDir(), "accounts").getAbsolutePath(), eventChannel); + Log.i(TAG, "DcAccounts created"); + rpc = new Rpc(new FFITransport(dcAccounts.getJsonrpcInstance())); + Log.i(TAG, "Rpc created"); + AccountManager.getInstance().migrateToDcAccounts(this); + + int[] allAccounts = dcAccounts.getAll(); + Log.i(TAG, "Number of profiles: " + allAccounts.length); + for (int accountId : allAccounts) { + DcContext ac = dcAccounts.getAccount(accountId); + if (!ac.isOpen()) { + try { + DatabaseSecret secret = + DatabaseSecretProvider.getOrCreateDatabaseSecret(this, accountId); + boolean res = ac.open(secret.asString()); + if (res) + Log.i( + TAG, + "Successfully opened account " + + accountId + + ", path: " + + ac.getBlobdir()); + else + Log.e( + TAG, "Error opening account " + accountId + ", path: " + ac.getBlobdir()); + } catch (Exception e) { + Log.e( + TAG, + "Failed to open account " + + accountId + + ", path: " + + ac.getBlobdir() + + ": " + + e); + e.printStackTrace(); + } + } + + // 2025-12-16: The setting was removed. + // Revert it to the default if it was changed in the past. + ac.setConfigInt("webxdc_realtime_enabled", 1); + + // 2025-11-12: this is needed until core starts ignoring "delete_server_after" for + // chatmail + if (ac.isChatmail()) { + ac.setConfig("delete_server_after", null); // reset + } + } + if (allAccounts.length == 0) { + try { + rpc.addAccount(); + } catch (RpcException e) { + e.printStackTrace(); + } + } + dcContext = dcAccounts.getSelectedAccount(); + notificationCenter = new NotificationCenter(this); + dcLocationManager = new DcLocationManager(this, dcContext); + + isInitialized = true; + initLock.notifyAll(); + Log.i(TAG, "DcAccounts initialization complete"); + + // set translations before starting I/O to avoid sending untranslated MDNs (issue + // #2288) + DcHelper.setStockTranslations(this); + + dcAccounts.startIo(); + } catch (Exception e) { + Log.e(TAG, "Fatal error during DcAccounts initialization", e); + // Mark as initialized even on error to avoid deadlock + isInitialized = true; + initLock.notifyAll(); + throw new RuntimeException("Failed to initialize DcAccounts", e); } } - dcContext = dcAccounts.getSelectedAccount(); - notificationCenter = new NotificationCenter(this); - dcLocationManager = new DcLocationManager(this, dcContext); - - isInitialized = true; - initLock.notifyAll(); - Log.i(TAG, "DcAccounts initialization complete"); - - // set translations before starting I/O to avoid sending untranslated MDNs (issue #2288) - DcHelper.setStockTranslations(this); - - dcAccounts.startIo(); - } catch (Exception e) { - Log.e(TAG, "Fatal error during DcAccounts initialization", e); - // Mark as initialized even on error to avoid deadlock - isInitialized = true; - initLock.notifyAll(); - throw new RuntimeException("Failed to initialize DcAccounts", e); - } - } - }); + }); // October-2025 migration: delete deprecated "permanent channel" id NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); @@ -266,33 +285,50 @@ public class ApplicationContext extends MultiDexApplication { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { ConnectivityManager connectivityManager = - (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); - connectivityManager.registerDefaultNetworkCallback(new ConnectivityManager.NetworkCallback() { - @Override - public void onAvailable(@NonNull android.net.Network network) { - Log.i("DeltaChat", "++++++++++++++++++ NetworkCallback.onAvailable() #" + debugOnAvailableCount++); - getDcAccounts().maybeNetwork(); - } + (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); + connectivityManager.registerDefaultNetworkCallback( + new ConnectivityManager.NetworkCallback() { + @Override + public void onAvailable(@NonNull android.net.Network network) { + Log.i( + "DeltaChat", + "++++++++++++++++++ NetworkCallback.onAvailable() #" + debugOnAvailableCount++); + getDcAccounts().maybeNetwork(); + } - @Override - public void onBlockedStatusChanged(@NonNull android.net.Network network, boolean blocked) { - Log.i("DeltaChat", "++++++++++++++++++ NetworkCallback.onBlockedStatusChanged() #" + debugOnBlockedStatusChangedCount++); - } + @Override + public void onBlockedStatusChanged( + @NonNull android.net.Network network, boolean blocked) { + Log.i( + "DeltaChat", + "++++++++++++++++++ NetworkCallback.onBlockedStatusChanged() #" + + debugOnBlockedStatusChangedCount++); + } - @Override - public void onCapabilitiesChanged(@NonNull android.net.Network network, NetworkCapabilities networkCapabilities) { - // usually called after onAvailable(), so a maybeNetwork seems contraproductive - Log.i("DeltaChat", "++++++++++++++++++ NetworkCallback.onCapabilitiesChanged() #" + debugOnCapabilitiesChangedCount++); - } + @Override + public void onCapabilitiesChanged( + @NonNull android.net.Network network, NetworkCapabilities networkCapabilities) { + // usually called after onAvailable(), so a maybeNetwork seems contraproductive + Log.i( + "DeltaChat", + "++++++++++++++++++ NetworkCallback.onCapabilitiesChanged() #" + + debugOnCapabilitiesChangedCount++); + } - @Override - public void onLinkPropertiesChanged(@NonNull android.net.Network network, LinkProperties linkProperties) { - Log.i("DeltaChat", "++++++++++++++++++ NetworkCallback.onLinkPropertiesChanged() #" + debugOnLinkPropertiesChangedCount++); - } - }); + @Override + public void onLinkPropertiesChanged( + @NonNull android.net.Network network, LinkProperties linkProperties) { + Log.i( + "DeltaChat", + "++++++++++++++++++ NetworkCallback.onLinkPropertiesChanged() #" + + debugOnLinkPropertiesChangedCount++); + } + }); } // no else: use old method for debugging BroadcastReceiver networkStateReceiver = new NetworkStateReceiver(); - registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION)); + registerReceiver( + networkStateReceiver, + new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION)); KeepAliveService.maybeStartSelf(this); @@ -308,13 +344,15 @@ public class ApplicationContext extends MultiDexApplication { DynamicTheme.setDefaultDayNightMode(this); IntentFilter filter = new IntentFilter(Intent.ACTION_LOCALE_CHANGED); - registerReceiver(new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { + registerReceiver( + new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { Util.localeChanged(); DcHelper.setStockTranslations(context); - } - }, filter); + } + }, + filter); AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); @@ -325,31 +363,34 @@ public class ApplicationContext extends MultiDexApplication { // MAYBE TODO: i think the ApplicationContext is also created // when the app is stated by FetchWorker timeouts. // in this case, the normal threads shall not be started. - Constraints constraints = new Constraints.Builder() - .setRequiredNetworkType(NetworkType.CONNECTED) - .build(); - PeriodicWorkRequest fetchWorkRequest = new PeriodicWorkRequest.Builder( - FetchWorker.class, - PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS, // usually 15 minutes - TimeUnit.MILLISECONDS, - PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS, // the start may be preferred by up to 5 minutes, so we run every 10-15 minutes - TimeUnit.MILLISECONDS) + Constraints constraints = + new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build(); + PeriodicWorkRequest fetchWorkRequest = + new PeriodicWorkRequest.Builder( + FetchWorker.class, + PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS, // usually 15 minutes + TimeUnit.MILLISECONDS, + PeriodicWorkRequest + .MIN_PERIODIC_FLEX_MILLIS, // the start may be preferred by up to 5 minutes, + // so we run every 10-15 minutes + TimeUnit.MILLISECONDS) .setConstraints(constraints) .build(); - WorkManager.getInstance(this).enqueueUniquePeriodicWork( - "FetchWorker", - ExistingPeriodicWorkPolicy.KEEP, - fetchWorkRequest); + WorkManager.getInstance(this) + .enqueueUniquePeriodicWork( + "FetchWorker", ExistingPeriodicWorkPolicy.KEEP, fetchWorkRequest); } - PeriodicWorkRequest webxdcGarbageCollectionRequest = new PeriodicWorkRequest.Builder( - WebxdcGarbageCollectionWorker.class, - PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS, - TimeUnit.MILLISECONDS, - PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS, - TimeUnit.MILLISECONDS) + PeriodicWorkRequest webxdcGarbageCollectionRequest = + new PeriodicWorkRequest.Builder( + WebxdcGarbageCollectionWorker.class, + PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS, + TimeUnit.MILLISECONDS, + PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS, + TimeUnit.MILLISECONDS) .build(); - WorkManager.getInstance(this).enqueueUniquePeriodicWork( + WorkManager.getInstance(this) + .enqueueUniquePeriodicWork( "WebxdcGarbageCollectionWorker", ExistingPeriodicWorkPolicy.KEEP, webxdcGarbageCollectionRequest); diff --git a/src/main/java/org/thoughtcrime/securesms/ConversationActivity.java b/src/main/java/org/thoughtcrime/securesms/ConversationActivity.java index e2f75cb5e..19ed898f9 100644 --- a/src/main/java/org/thoughtcrime/securesms/ConversationActivity.java +++ b/src/main/java/org/thoughtcrime/securesms/ConversationActivity.java @@ -58,7 +58,6 @@ import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; - import androidx.activity.OnBackPressedCallback; import androidx.annotation.NonNull; import androidx.annotation.Nullable; @@ -73,13 +72,20 @@ import androidx.lifecycle.ViewModelProvider; import androidx.media3.session.MediaController; import androidx.media3.session.SessionCommand; import androidx.media3.session.SessionToken; - +import chat.delta.rpc.Rpc; +import chat.delta.rpc.RpcException; +import chat.delta.util.ListenableFuture; +import chat.delta.util.SettableFuture; import com.b44t.messenger.DcChat; import com.b44t.messenger.DcContact; import com.b44t.messenger.DcContext; import com.b44t.messenger.DcEvent; import com.b44t.messenger.DcMsg; - +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ExecutionException; import org.thoughtcrime.securesms.attachments.Attachment; import org.thoughtcrime.securesms.attachments.UriAttachment; import org.thoughtcrime.securesms.audio.AudioRecorder; @@ -127,81 +133,70 @@ import org.thoughtcrime.securesms.util.guava.Optional; import org.thoughtcrime.securesms.util.views.ProgressDialog; import org.thoughtcrime.securesms.video.recode.VideoRecoder; -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.ExecutionException; - -import chat.delta.rpc.Rpc; -import chat.delta.rpc.RpcException; -import chat.delta.util.ListenableFuture; -import chat.delta.util.SettableFuture; - /** - * Activity for displaying a message thread, as well as - * composing/sending a new message into that thread. + * Activity for displaying a message thread, as well as composing/sending a new message into that + * thread. * * @author Moxie Marlinspike - * */ @SuppressLint("StaticFieldLeak") public class ConversationActivity extends PassphraseRequiredActionBarActivity - implements ConversationFragment.ConversationFragmentListener, - AttachmentManager.AttachmentListener, - SearchView.OnQueryTextListener, - DcEventCenter.DcEventDelegate, - OnKeyboardShownListener, - InputPanel.Listener, - InputPanel.MediaListener, AudioView.OnActionListener { + implements ConversationFragment.ConversationFragmentListener, + AttachmentManager.AttachmentListener, + SearchView.OnQueryTextListener, + DcEventCenter.DcEventDelegate, + OnKeyboardShownListener, + InputPanel.Listener, + InputPanel.MediaListener, + AudioView.OnActionListener { private static final String TAG = ConversationActivity.class.getSimpleName(); - public static final String ACCOUNT_ID_EXTRA = "account_id"; - public static final String CHAT_ID_EXTRA = "chat_id"; + public static final String ACCOUNT_ID_EXTRA = "account_id"; + public static final String CHAT_ID_EXTRA = "chat_id"; public static final String FROM_ARCHIVED_CHATS_EXTRA = "from_archived"; - public static final String TEXT_EXTRA = "draft_text"; + public static final String TEXT_EXTRA = "draft_text"; public static final String STARTING_POSITION_EXTRA = "starting_position"; - private static final int PICK_GALLERY = 1; - private static final int PICK_DOCUMENT = 2; - private static final int PICK_CONTACT = 4; - private static final int GROUP_EDIT = 6; - private static final int TAKE_PHOTO = 7; - private static final int RECORD_VIDEO = 8; - private static final int PICK_WEBXDC = 9; + private static final int PICK_GALLERY = 1; + private static final int PICK_DOCUMENT = 2; + private static final int PICK_CONTACT = 4; + private static final int GROUP_EDIT = 6; + private static final int TAKE_PHOTO = 7; + private static final int RECORD_VIDEO = 8; + private static final int PICK_WEBXDC = 9; - private GlideRequests glideRequests; - protected ComposeText composeText; - private AnimatingToggle buttonToggle; - private SendButton sendButton; - private ImageButton attachButton; - protected ConversationTitleView titleView; - private ConversationFragment fragment; - private InputAwareLayout container; - private View composePanel; - private ScaleStableImageView backgroundView; - private MessageRequestsBottomView messageRequestBottomView; - private ProgressDialog progressDialog; + private GlideRequests glideRequests; + protected ComposeText composeText; + private AnimatingToggle buttonToggle; + private SendButton sendButton; + private ImageButton attachButton; + protected ConversationTitleView titleView; + private ConversationFragment fragment; + private InputAwareLayout container; + private View composePanel; + private ScaleStableImageView backgroundView; + private MessageRequestsBottomView messageRequestBottomView; + private ProgressDialog progressDialog; - private AttachmentTypeSelector attachmentTypeSelector; - private AttachmentManager attachmentManager; - private AudioRecorder audioRecorder; - private FrameLayout emojiPickerContainer; - private MediaKeyboard emojiPicker; - protected HidingLinearLayout quickAttachmentToggle; - private InputPanel inputPanel; - private @Nullable MediaController mediaController; - private com.google.common.util.concurrent.ListenableFuture mediaControllerFuture; - private AudioPlaybackViewModel playbackViewModel; + private AttachmentTypeSelector attachmentTypeSelector; + private AttachmentManager attachmentManager; + private AudioRecorder audioRecorder; + private FrameLayout emojiPickerContainer; + private MediaKeyboard emojiPicker; + protected HidingLinearLayout quickAttachmentToggle; + private InputPanel inputPanel; + private @Nullable MediaController mediaController; + private com.google.common.util.concurrent.ListenableFuture mediaControllerFuture; + private AudioPlaybackViewModel playbackViewModel; private ApplicationContext context; - private Recipient recipient; + private Recipient recipient; private Rpc rpc; - private DcChat dcChat = new DcChat(0, 0); - private int chatId; - private final boolean isSecureText = true; - private boolean isDefaultSms = true; - private boolean isSecurityInitialized = false; + private DcChat dcChat = new DcChat(0, 0); + private int chatId; + private final boolean isSecureText = true; + private boolean isDefaultSms = true; + private boolean isSecurityInitialized = false; private boolean successfulForwardingAttempt = false; private boolean isEditing = false; private boolean switchedProfile = false; @@ -229,36 +224,46 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity playbackViewModel = new ViewModelProvider(this).get(AudioPlaybackViewModel.class); initializeMediaController(); - initializeSecurity(false, isDefaultSms).addListener(new AssertedSuccessListener() { - @Override - public void onSuccess(Boolean result) { - initializeDraft().addListener(new AssertedSuccessListener() { - @Override - public void onSuccess(Boolean result) { - if (result != null && result) { - Util.runOnMain(() -> { - if (fragment != null && fragment.isResumed()) { - fragment.moveToLastSeen(); - } else { - Log.w(TAG, "Wanted to move to the last seen position, but the fragment was in an invalid state"); - } - }); - } - } - }); - } - }); + initializeSecurity(false, isDefaultSms) + .addListener( + new AssertedSuccessListener() { + @Override + public void onSuccess(Boolean result) { + initializeDraft() + .addListener( + new AssertedSuccessListener() { + @Override + public void onSuccess(Boolean result) { + if (result != null && result) { + Util.runOnMain( + () -> { + if (fragment != null && fragment.isResumed()) { + fragment.moveToLastSeen(); + } else { + Log.w( + TAG, + "Wanted to move to the last seen position, but the fragment was in an invalid state"); + } + }); + } + } + }); + } + }); - getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) { - @Override - public void handleOnBackPressed() { - if (container.isInputOpen()) { - container.hideCurrentInput(composeText); - } else { - handleReturnToConversationList(); - } - } - }); + getOnBackPressedDispatcher() + .addCallback( + this, + new OnBackPressedCallback(true) { + @Override + public void handleOnBackPressed() { + if (container.isInputOpen()) { + container.hideCurrentInput(composeText); + } else { + handleReturnToConversationList(); + } + } + }); setDcEventListener(); handleRelaying(); @@ -280,18 +285,19 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity } private void initializeMediaController() { - SessionToken sessionToken = new SessionToken(this, - new ComponentName(this, AudioPlaybackService.class)); - mediaControllerFuture = new MediaController.Builder(this, sessionToken) - .buildAsync(); - mediaControllerFuture.addListener(() -> { - try { - mediaController = mediaControllerFuture.get(); - playbackViewModel.setMediaController(mediaController); - } catch (Exception e) { - Log.e(TAG, "Error connecting to audio playback service", e); - } - }, ContextCompat.getMainExecutor(this)); + SessionToken sessionToken = + new SessionToken(this, new ComponentName(this, AudioPlaybackService.class)); + mediaControllerFuture = new MediaController.Builder(this, sessionToken).buildAsync(); + mediaControllerFuture.addListener( + () -> { + try { + mediaController = mediaControllerFuture.get(); + playbackViewModel.setMediaController(mediaController); + } catch (Exception e) { + Log.e(TAG, "Error connecting to audio playback service", e); + } + }, + ContextCompat.getMainExecutor(this)); } private void addActivityContext(Bundle extras, String activityClassName) { @@ -304,7 +310,7 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity } SessionCommand updateContextCommand = - new SessionCommand("UPDATE_ACTIVITY_CONTEXT", Bundle.EMPTY); + new SessionCommand("UPDATE_ACTIVITY_CONTEXT", Bundle.EMPTY); mediaController.sendCustomCommand(updateContextCommand, commandArgs); } @@ -325,12 +331,14 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity setIntent(intent); initializeResources(); - initializeSecurity(false, isDefaultSms).addListener(new AssertedSuccessListener() { - @Override - public void onSuccess(Boolean result) { - initializeDraft(); - } - }); + initializeSecurity(false, isDefaultSms) + .addListener( + new AssertedSuccessListener() { + @Override + public void onSuccess(Boolean result) { + initializeDraft(); + } + }); setDcEventListener(); // reset event listener handleRelaying(); @@ -366,7 +374,6 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity Log.e(TAG, "rpc.getSelectedAccountId() failed", e); } - attachmentManager.onResume(); } @@ -410,80 +417,87 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity public void onActivityResult(final int reqCode, int resultCode, Intent data) { super.onActivityResult(reqCode, resultCode, data); - if (resultCode != RESULT_OK || (data == null && reqCode != TAKE_PHOTO && reqCode != RECORD_VIDEO)) - { + if (resultCode != RESULT_OK + || (data == null && reqCode != TAKE_PHOTO && reqCode != RECORD_VIDEO)) { return; } switch (reqCode) { - case PICK_GALLERY: - final Uri singleUri = data.getData(); - if (singleUri != null) { - MediaType mediaType; - String mimeType = MediaUtil.getMimeType(this, singleUri); - if (MediaUtil.isGif(mimeType)) mediaType = MediaType.GIF; - else if (MediaUtil.isVideo(mimeType)) mediaType = MediaType.VIDEO; - else mediaType = MediaType.IMAGE; - setMedia(singleUri, mediaType); - } else { - final ClipData multipleUris = data.getClipData(); - if (multipleUris != null) { - final int uriCount = multipleUris.getItemCount(); - if (uriCount > 0) { - ArrayList uriList = new ArrayList<>(uriCount); - for (int i = 0; i < uriCount; i++) { - uriList.add(multipleUris.getItemAt(i).getUri()); + case PICK_GALLERY: + final Uri singleUri = data.getData(); + if (singleUri != null) { + MediaType mediaType; + String mimeType = MediaUtil.getMimeType(this, singleUri); + if (MediaUtil.isGif(mimeType)) mediaType = MediaType.GIF; + else if (MediaUtil.isVideo(mimeType)) mediaType = MediaType.VIDEO; + else mediaType = MediaType.IMAGE; + setMedia(singleUri, mediaType); + } else { + final ClipData multipleUris = data.getClipData(); + if (multipleUris != null) { + final int uriCount = multipleUris.getItemCount(); + if (uriCount > 0) { + ArrayList uriList = new ArrayList<>(uriCount); + for (int i = 0; i < uriCount; i++) { + uriList.add(multipleUris.getItemAt(i).getUri()); + } + askSendingFiles( + uriList, + () -> { + Util.runOnAnyBackgroundThread( + () -> { + SendRelayedMessageUtil.sendMultipleMsgs(this, chatId, uriList, null); + }); + }); } - askSendingFiles(uriList, () -> { - Util.runOnAnyBackgroundThread(() -> { - SendRelayedMessageUtil.sendMultipleMsgs(this, chatId, uriList, null); - }); - }); } } - } - break; + break; - case PICK_DOCUMENT: - final String docMimeType = MediaUtil.getMimeType(this, data.getData()); - final MediaType docMediaType = MediaUtil.isAudioType(docMimeType) ? MediaType.AUDIO : MediaType.DOCUMENT; - setMedia(data.getData(), docMediaType); - break; + case PICK_DOCUMENT: + final String docMimeType = MediaUtil.getMimeType(this, data.getData()); + final MediaType docMediaType = + MediaUtil.isAudioType(docMimeType) ? MediaType.AUDIO : MediaType.DOCUMENT; + setMedia(data.getData(), docMediaType); + break; - case PICK_WEBXDC: - setMedia(data.getData(), MediaType.DOCUMENT); - break; + case PICK_WEBXDC: + setMedia(data.getData(), MediaType.DOCUMENT); + break; - case PICK_CONTACT: - addAttachmentContactInfo(data.getIntExtra(AttachContactActivity.CONTACT_ID_EXTRA, 0)); - break; + case PICK_CONTACT: + addAttachmentContactInfo(data.getIntExtra(AttachContactActivity.CONTACT_ID_EXTRA, 0)); + break; - case GROUP_EDIT: - dcChat = DcHelper.getContext(context).getChat(chatId); - titleView.setTitle(glideRequests, dcChat); - break; + case GROUP_EDIT: + dcChat = DcHelper.getContext(context).getChat(chatId); + titleView.setTitle(glideRequests, dcChat); + break; - case TAKE_PHOTO: - if (attachmentManager.getImageCaptureUri() != null) { - setMedia(attachmentManager.getImageCaptureUri(), MediaType.IMAGE); - } - break; + case TAKE_PHOTO: + if (attachmentManager.getImageCaptureUri() != null) { + setMedia(attachmentManager.getImageCaptureUri(), MediaType.IMAGE); + } + break; - case RECORD_VIDEO: - Uri uri = null; - if (data!=null) { uri = data.getData(); } - if (uri==null) { uri = attachmentManager.getVideoCaptureUri(); } - if (uri!=null) { - setMedia(uri, MediaType.VIDEO); - } - else { - Toast.makeText(this, "No video returned from system", Toast.LENGTH_LONG).show(); - } - break; + case RECORD_VIDEO: + Uri uri = null; + if (data != null) { + uri = data.getData(); + } + if (uri == null) { + uri = attachmentManager.getVideoCaptureUri(); + } + if (uri != null) { + setMedia(uri, MediaType.VIDEO); + } else { + Toast.makeText(this, "No video returned from system", Toast.LENGTH_LONG).show(); + } + break; - case ScribbleActivity.SCRIBBLE_REQUEST_CODE: - setMedia(data.getData(), MediaType.IMAGE); - break; + case ScribbleActivity.SCRIBBLE_REQUEST_CODE: + setMedia(data.getData(), MediaType.IMAGE); + break; } } @@ -501,7 +515,6 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity } } - @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.clear(); @@ -510,7 +523,7 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity if (dcChat.isSelfTalk() || dcChat.isOutBroadcast()) { menu.findItem(R.id.menu_mute_notifications).setVisible(false); - } else if(dcChat.isMuted()) { + } else if (dcChat.isMuted()) { menu.findItem(R.id.menu_mute_notifications).setTitle(R.string.menu_unmute); } @@ -518,16 +531,16 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity menu.findItem(R.id.menu_show_map).setVisible(false); } - menu.findItem(R.id.menu_start_call).setVisible( - Prefs.isCallsEnabled(this) - && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O - && dcChat.canSend() - && dcChat.isEncrypted() - && !dcChat.isSelfTalk() - && !dcChat.isMultiUser() - ); + menu.findItem(R.id.menu_start_call) + .setVisible( + Prefs.isCallsEnabled(this) + && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O + && dcChat.canSend() + && dcChat.isEncrypted() + && !dcChat.isSelfTalk() + && !dcChat.isMultiUser()); - if (!dcChat.isEncrypted() || !dcChat.canSend() || dcChat.isMailingList() ) { + if (!dcChat.isEncrypted() || !dcChat.canSend() || dcChat.isMailingList()) { menu.findItem(R.id.menu_ephemeral_messages).setVisible(false); } @@ -543,34 +556,35 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity menu.findItem(R.id.menu_archive_chat).setTitle(R.string.menu_unarchive_chat); } - Util.redMenuItem(menu, R.id.menu_leave); Util.redMenuItem(menu, R.id.menu_clear_chat); Util.redMenuItem(menu, R.id.menu_delete_chat); try { MenuItem searchItem = menu.findItem(R.id.menu_search_chat); - searchItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() { - @Override - public boolean onMenuItemActionExpand(final MenuItem item) { - searchExpand(menu, item); - return true; - } + searchItem.setOnActionExpandListener( + new MenuItem.OnActionExpandListener() { + @Override + public boolean onMenuItemActionExpand(final MenuItem item) { + searchExpand(menu, item); + return true; + } - @Override - public boolean onMenuItemActionCollapse(final MenuItem item) { - searchCollapse(menu, item); - return true; - } - }); + @Override + public boolean onMenuItemActionCollapse(final MenuItem item) { + searchCollapse(menu, item); + return true; + } + }); SearchView searchView = (SearchView) searchItem.getActionView(); searchView.setOnQueryTextListener(this); searchView.setQueryHint(getString(R.string.search)); searchView.setIconifiedByDefault(true); - // hide the [X] beside the search field - this is too much noise, search can be aborted eg. by "back" + // hide the [X] beside the search field - this is too much noise, search can be aborted eg. by + // "back" ImageView closeBtn = searchView.findViewById(R.id.search_close_btn); - if (closeBtn!=null) { + if (closeBtn != null) { closeBtn.setEnabled(false); closeBtn.setImageDrawable(null); } @@ -579,8 +593,8 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity } if (!dcChat.canSend() || isEditing) { - MenuItem attachItem = menu.findItem(R.id.menu_add_attachment); - if (attachItem!=null) { + MenuItem attachItem = menu.findItem(R.id.menu_add_attachment); + if (attachItem != null) { attachItem.setVisible(false); } } @@ -650,7 +664,8 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity } @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + public void onRequestPermissionsResult( + int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { Permissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults); } @@ -666,11 +681,14 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity //////// Event Handlers private void handleEphemeralMessages() { - DcContext dcContext = DcHelper.getContext(context); - int preselected = dcContext.getChatEphemeralTimer(chatId); - EphemeralMessagesDialog.show(this, preselected, duration -> { - dcContext.setChatEphemeralTimer(chatId, (int) duration); - }); + DcContext dcContext = DcHelper.getContext(context); + int preselected = dcContext.getChatEphemeralTimer(chatId); + EphemeralMessagesDialog.show( + this, + preselected, + duration -> { + dcContext.setChatEphemeralTimer(chatId, (int) duration); + }); } private void handleReturnToConversationList() { @@ -686,7 +704,10 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity playbackViewModel.stopNonMessageAudioPlayback(); boolean archived = getIntent().getBooleanExtra(FROM_ARCHIVED_CHATS_EXTRA, false); - Intent intent = new Intent(this, (archived ? ConversationListArchiveActivity.class : ConversationListActivity.class)); + Intent intent = + new Intent( + this, + (archived ? ConversationListArchiveActivity.class : ConversationListActivity.class)); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); if (extras != null) intent.putExtras(extras); startActivity(intent); @@ -695,11 +716,13 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity private void handleMuteNotifications() { DcContext dcContext = DcHelper.getContext(context); - if(!dcChat.isMuted()) { - MuteDialog.show(this, duration -> { - dcContext.setChatMuteDuration(chatId, duration); - titleView.setTitle(glideRequests, dcChat); - }); + if (!dcChat.isMuted()) { + MuteDialog.show( + this, + duration -> { + dcContext.setChatMuteDuration(chatId, duration); + titleView.setTitle(glideRequests, dcChat); + }); } else { // unmute dcContext.setChatMuteDuration(chatId, 0); @@ -727,31 +750,38 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity leaveLabel = R.string.menu_leave_group; } - AlertDialog dialog = new AlertDialog.Builder(this) - .setMessage(getString(R.string.ask_leave_group)) - .setPositiveButton(leaveLabel, (d, which) -> { - DcHelper.getContext(context).removeContactFromChat(chatId, DcContact.DC_CONTACT_ID_SELF); - Toast.makeText(this, getString(R.string.done), Toast.LENGTH_SHORT).show(); - }) - .setNegativeButton(R.string.menu_leave_and_delete, (d, which) -> { - DcHelper.getContext(context).removeContactFromChat(chatId, DcContact.DC_CONTACT_ID_SELF); - DcHelper.getContext(context).deleteChat(chatId); - DirectShareUtil.clearShortcut(this, chatId); - finish(); - }) - .setNeutralButton(R.string.cancel, null) - .show(); + AlertDialog dialog = + new AlertDialog.Builder(this) + .setMessage(getString(R.string.ask_leave_group)) + .setPositiveButton( + leaveLabel, + (d, which) -> { + DcHelper.getContext(context) + .removeContactFromChat(chatId, DcContact.DC_CONTACT_ID_SELF); + Toast.makeText(this, getString(R.string.done), Toast.LENGTH_SHORT).show(); + }) + .setNegativeButton( + R.string.menu_leave_and_delete, + (d, which) -> { + DcHelper.getContext(context) + .removeContactFromChat(chatId, DcContact.DC_CONTACT_ID_SELF); + DcHelper.getContext(context).deleteChat(chatId); + DirectShareUtil.clearShortcut(this, chatId); + finish(); + }) + .setNeutralButton(R.string.cancel, null) + .show(); Util.redPositiveButton(dialog); Util.redButton(dialog, AlertDialog.BUTTON_NEGATIVE); } private void handleArchiveChat() { DcContext dcContext = DcHelper.getContext(context); - int newVisibility = isArchived() ? - DcChat.DC_CHAT_VISIBILITY_NORMAL : DcChat.DC_CHAT_VISIBILITY_ARCHIVED; + int newVisibility = + isArchived() ? DcChat.DC_CHAT_VISIBILITY_NORMAL : DcChat.DC_CHAT_VISIBILITY_ARCHIVED; dcContext.setChatVisibility(chatId, newVisibility); Toast.makeText(this, getString(R.string.done), Toast.LENGTH_SHORT).show(); - if (newVisibility==DcChat.DC_CHAT_VISIBILITY_ARCHIVED) { + if (newVisibility == DcChat.DC_CHAT_VISIBILITY_ARCHIVED) { finish(); return; } @@ -759,32 +789,39 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity } private void handleDeleteChat() { - AlertDialog dialog = new AlertDialog.Builder(this) - .setMessage(getResources().getString(R.string.ask_delete_named_chat, dcChat.getName())) - .setPositiveButton(R.string.delete_for_me, (d, which) -> { - DcHelper.getContext(context).deleteChat(chatId); - DirectShareUtil.clearShortcut(this, chatId); - finish(); - }) - .setNegativeButton(R.string.cancel, null) - .show(); + AlertDialog dialog = + new AlertDialog.Builder(this) + .setMessage(getResources().getString(R.string.ask_delete_named_chat, dcChat.getName())) + .setPositiveButton( + R.string.delete_for_me, + (d, which) -> { + DcHelper.getContext(context).deleteChat(chatId); + DirectShareUtil.clearShortcut(this, chatId); + finish(); + }) + .setNegativeButton(R.string.cancel, null) + .show(); Util.redPositiveButton(dialog); } private void handleAddAttachment() { if (attachmentTypeSelector == null) { - attachmentTypeSelector = new AttachmentTypeSelector(this, getSupportLoaderManager(), new AttachmentTypeListener(), chatId); + attachmentTypeSelector = + new AttachmentTypeSelector( + this, getSupportLoaderManager(), new AttachmentTypeListener(), chatId); } attachmentTypeSelector.show(this, attachButton); } private void handleSecurityChange(boolean isSecureText, boolean isDefaultSms) { Log.i(TAG, "handleSecurityChange(" + isSecureText + ", " + isDefaultSms + ")"); - if (isSecurityInitialized && isSecureText == this.isSecureText && isDefaultSms == this.isDefaultSms) { + if (isSecurityInitialized + && isSecureText == this.isSecureText + && isDefaultSms == this.isDefaultSms) { return; } - this.isDefaultSms = isDefaultSms; + this.isDefaultSms = isDefaultSms; this.isSecurityInitialized = true; sendButton.resetAvailableTransports(); @@ -805,32 +842,35 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity } } new AlertDialog.Builder(this) - .setMessage(getString(R.string.ask_forward, name)) - .setPositiveButton(R.string.ok, (dialogInterface, i) -> { + .setMessage(getString(R.string.ask_forward, name)) + .setPositiveButton( + R.string.ok, + (dialogInterface, i) -> { SendRelayedMessageUtil.immediatelyRelay(this, chatId); successfulForwardingAttempt = true; }) - .setNegativeButton(R.string.cancel, (dialogInterface, i) -> finish()) - .setOnCancelListener(dialog -> finish()) - .show(); + .setNegativeButton(R.string.cancel, (dialogInterface, i) -> finish()) + .setOnCancelListener(dialog -> finish()) + .show(); } } private void askSendingFiles(ArrayList uriList, Runnable onConfirm) { - String message = String.format(getString(R.string.ask_send_files_to_chat), uriList.size(), dcChat.getName()); + String message = + String.format(getString(R.string.ask_send_files_to_chat), uriList.size(), dcChat.getName()); if (SendRelayedMessageUtil.containsVideoType(context, uriList)) { message += "\n\n" + getString(R.string.videos_sent_without_recoding); } new AlertDialog.Builder(this) - .setMessage(message) - .setCancelable(false) - .setNegativeButton(android.R.string.cancel, null) - .setPositiveButton(R.string.menu_send, (dialog, which) -> onConfirm.run()) - .show(); + .setMessage(message) + .setCancelable(false) + .setNegativeButton(android.R.string.cancel, null) + .setPositiveButton(R.string.menu_send, (dialog, which) -> onConfirm.run()) + .show(); } private void handleSharing() { - ArrayList uriList = ShareUtil.getSharedUris(this); + ArrayList uriList = ShareUtil.getSharedUris(this); int sharedContactId = ShareUtil.getSharedContactId(this); if (uriList.size() > 1) { askSendingFiles(uriList, () -> SendRelayedMessageUtil.immediatelyRelay(this, chatId)); @@ -838,9 +878,14 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity if (sharedContactId != 0) { addAttachmentContactInfo(sharedContactId); } else if (uriList.isEmpty()) { - DcHelper.getContext(context).setDraft(chatId, SendRelayedMessageUtil.createMessage(this, null, getSharedText(this))); + DcHelper.getContext(context) + .setDraft( + chatId, SendRelayedMessageUtil.createMessage(this, null, getSharedText(this))); } else { - DcHelper.getContext(context).setDraft(chatId, SendRelayedMessageUtil.createMessage(this, uriList.get(0), getSharedText(this))); + DcHelper.getContext(context) + .setDraft( + chatId, + SendRelayedMessageUtil.createMessage(this, uriList.get(0), getSharedText(this))); } initializeDraft(); } @@ -850,6 +895,7 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity /** * Drafts can be initialized by click on a mailto: link or from the database + * * @return */ private ListenableFuture initializeDraft() { @@ -869,8 +915,8 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity return future; } - final String text = TextUtils.isEmpty(sharedText)? draft.getText() : sharedText; - if(!text.isEmpty()) { + final String text = TextUtils.isEmpty(sharedText) ? draft.getText() : sharedText; + if (!text.isEmpty()) { composeText.setText(text); composeText.setSelection(composeText.getText().length()); } @@ -889,19 +935,20 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity return future; } - ListenableFuture.Listener listener = new ListenableFuture.Listener() { - @Override - public void onSuccess(Boolean result) { - future.set(result || !text.isEmpty()); - updateToggleButtonState(); - } + ListenableFuture.Listener listener = + new ListenableFuture.Listener() { + @Override + public void onSuccess(Boolean result) { + future.set(result || !text.isEmpty()); + updateToggleButtonState(); + } - @Override - public void onFailure(ExecutionException e) { - future.set(!text.isEmpty()); - updateToggleButtonState(); - } - }; + @Override + public void onFailure(ExecutionException e) { + future.set(!text.isEmpty()); + updateToggleButtonState(); + } + }; switch (draft.getType()) { case DcMsg.DC_MSG_IMAGE: @@ -931,9 +978,8 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity attachButton.setEnabled(enabled); } - private ListenableFuture initializeSecurity(final boolean currentSecureText, - final boolean currentIsDefaultSms) - { + private ListenableFuture initializeSecurity( + final boolean currentSecureText, final boolean currentIsDefaultSms) { final SettableFuture future = new SettableFuture<>(); handleSecurityChange(currentSecureText || isMultiUser(), currentIsDefaultSms); @@ -946,26 +992,33 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity ActionBar supportActionBar = getSupportActionBar(); if (supportActionBar == null) throw new AssertionError(); - titleView = (ConversationTitleView) supportActionBar.getCustomView(); - buttonToggle = ViewUtil.findById(this, R.id.button_toggle); - sendButton = ViewUtil.findById(this, R.id.send_button); - attachButton = ViewUtil.findById(this, R.id.attach_button); - composeText = ViewUtil.findById(this, R.id.embedded_text_editor); - emojiPickerContainer = ViewUtil.findById(this, R.id.emoji_picker_container); - composePanel = ViewUtil.findById(this, R.id.bottom_panel); - container = ViewUtil.findById(this, R.id.layout_container); + titleView = (ConversationTitleView) supportActionBar.getCustomView(); + buttonToggle = ViewUtil.findById(this, R.id.button_toggle); + sendButton = ViewUtil.findById(this, R.id.send_button); + attachButton = ViewUtil.findById(this, R.id.attach_button); + composeText = ViewUtil.findById(this, R.id.embedded_text_editor); + emojiPickerContainer = ViewUtil.findById(this, R.id.emoji_picker_container); + composePanel = ViewUtil.findById(this, R.id.bottom_panel); + container = ViewUtil.findById(this, R.id.layout_container); quickAttachmentToggle = ViewUtil.findById(this, R.id.quick_attachment_toggle); - inputPanel = ViewUtil.findById(this, R.id.bottom_panel); - backgroundView = ViewUtil.findById(this, R.id.conversation_background); - messageRequestBottomView = ViewUtil.findById(this, R.id.conversation_activity_message_request_bottom_bar); + inputPanel = ViewUtil.findById(this, R.id.bottom_panel); + backgroundView = ViewUtil.findById(this, R.id.conversation_background); + messageRequestBottomView = + ViewUtil.findById(this, R.id.conversation_activity_message_request_bottom_bar); ImageButton quickCameraToggle = ViewUtil.findById(this, R.id.quick_camera_toggle); if (!ViewUtil.isEdgeToEdgeSupported()) { - // since insets will not be applied, we need to set top padding to avoid drawing behind toolbar - try (TypedArray typedArray = obtainStyledAttributes(new int[]{android.R.attr.actionBarSize})) { + // since insets will not be applied, we need to set top padding to avoid drawing behind + // toolbar + try (TypedArray typedArray = + obtainStyledAttributes(new int[] {android.R.attr.actionBarSize})) { int paddingTop = typedArray.getDimensionPixelSize(0, 0); - container.setPadding(container.getPaddingLeft(), paddingTop, container.getPaddingRight() , container.getPaddingBottom()); + container.setPadding( + container.getPaddingLeft(), + paddingTop, + container.getPaddingRight(), + container.getPaddingBottom()); } } // apply padding top to avoid drawing behind top bar @@ -980,10 +1033,10 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity inputPanel.setMediaListener(this); attachmentTypeSelector = null; - attachmentManager = new AttachmentManager(this, this); - audioRecorder = new AudioRecorder(this); + attachmentManager = new AttachmentManager(this, this); + audioRecorder = new AudioRecorder(this); - SendButtonListener sendButtonListener = new SendButtonListener(); + SendButtonListener sendButtonListener = new SendButtonListener(); ComposeKeyPressedListener composeKeyPressedListener = new ComposeKeyPressedListener(); composeText.setOnEditorActionListener(sendButtonListener); @@ -991,10 +1044,11 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity attachButton.setOnLongClickListener(new AttachButtonLongClickListener()); sendButton.setOnClickListener(sendButtonListener); sendButton.setEnabled(true); - sendButton.addOnTransportChangedListener((newTransport, manuallySelected) -> { - composeText.setTransport(newTransport); - buttonToggle.getBackground().invalidateSelf(); - }); + sendButton.addOnTransportChangedListener( + (newTransport, manuallySelected) -> { + composeText.setTransport(newTransport); + buttonToggle.getBackground().invalidateSelf(); + }); titleView.setOnClickListener(v -> handleProfile()); titleView.setOnBackClickedListener(view -> handleReturnToConversationList()); @@ -1005,7 +1059,8 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity composeText.setOnClickListener(composeKeyPressedListener); composeText.setOnFocusChangeListener(composeKeyPressedListener); - quickCameraToggle.setOnClickListener(v -> attachmentManager.capturePhoto(ConversationActivity.this, TAKE_PHOTO)); + quickCameraToggle.setOnClickListener( + v -> attachmentManager.capturePhoto(ConversationActivity.this, TAKE_PHOTO)); initializeBackground(); } @@ -1021,13 +1076,11 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity String backgroundImagePath = Prefs.getBackgroundImagePath(this, accId); Drawable background; - if(!backgroundImagePath.isEmpty()) { + if (!backgroundImagePath.isEmpty()) { background = Drawable.createFromPath(backgroundImagePath); - } - else if(DynamicTheme.isDarkTheme(this)) { + } else if (DynamicTheme.isDarkTheme(this)) { background = getResources().getDrawable(R.drawable.background_hd_dark); - } - else { + } else { background = getResources().getDrawable(R.drawable.background_hd); } backgroundView.setImageDrawable(background); @@ -1043,8 +1096,8 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity supportActionBar.setDisplayShowTitleEnabled(false); Toolbar parent = (Toolbar) supportActionBar.getCustomView().getParent(); - parent.setPadding(0,0,0,0); - parent.setContentInsetsAbsolute(0,0); + parent.setPadding(0, 0, 0, 0); + parent.setContentInsetsAbsolute(0, 0); } private void initializeResources() { @@ -1056,11 +1109,11 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity initializeBackground(); } chatId = getIntent().getIntExtra(CHAT_ID_EXTRA, -1); - if(chatId == DcChat.DC_CHAT_NO_CHAT) + if (chatId == DcChat.DC_CHAT_NO_CHAT) throw new IllegalStateException("can't display a conversation for no chat."); - dcChat = DcHelper.getContext(context).getChat(chatId); - recipient = new Recipient(this, dcChat); - glideRequests = GlideApp.with(this); + dcChat = DcHelper.getContext(context).getChat(chatId); + recipient = new Recipient(this, dcChat); + glideRequests = GlideApp.with(this); setComposePanelVisibility(true); initializeContactRequest(); @@ -1070,14 +1123,16 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity if (dcChat.canSend()) { composePanel.setVisibility(View.VISIBLE); attachmentManager.setHidden(false); - // FIXME: disabled for now to avoid problems with chat scrolling and keyboard covering input bar + // FIXME: disabled for now to avoid problems with chat scrolling and keyboard covering input + // bar // ViewUtil.forceApplyWindowInsets(findViewById(R.id.root_layout), true, false, true, true); // fragment.handleRemoveBottomInsets(); } else { composePanel.setVisibility(View.GONE); attachmentManager.setHidden(true); hideSoftKeyboard(); - // FIXME: disabled for now to avoid problems with chat scrolling and keyboard covering input bar + // FIXME: disabled for now to avoid problems with chat scrolling and keyboard covering input + // bar /* if (isInitialization) { ViewUtil.forceApplyWindowInsets(findViewById(R.id.root_layout), true, false, true, false); @@ -1091,21 +1146,27 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity private void addAttachment(int type) { switch (type) { - case AttachmentTypeSelector.ADD_GALLERY: - AttachmentManager.selectGallery(this, PICK_GALLERY); break; - case AttachmentTypeSelector.ADD_DOCUMENT: - AttachmentManager.selectDocument(this, PICK_DOCUMENT); break; - case AttachmentTypeSelector.ADD_CONTACT_INFO: - startContactChooserActivity(); break; - case AttachmentTypeSelector.ADD_LOCATION: - AttachmentManager.selectLocation(this, chatId); break; - case AttachmentTypeSelector.TAKE_PHOTO: - attachmentManager.capturePhoto(this, TAKE_PHOTO); break; - case AttachmentTypeSelector.RECORD_VIDEO: - attachmentManager.captureVideo(this, RECORD_VIDEO); - break; - case AttachmentTypeSelector.ADD_WEBXDC: - AttachmentManager.selectWebxdc(this, PICK_WEBXDC); break; + case AttachmentTypeSelector.ADD_GALLERY: + AttachmentManager.selectGallery(this, PICK_GALLERY); + break; + case AttachmentTypeSelector.ADD_DOCUMENT: + AttachmentManager.selectDocument(this, PICK_DOCUMENT); + break; + case AttachmentTypeSelector.ADD_CONTACT_INFO: + startContactChooserActivity(); + break; + case AttachmentTypeSelector.ADD_LOCATION: + AttachmentManager.selectLocation(this, chatId); + break; + case AttachmentTypeSelector.TAKE_PHOTO: + attachmentManager.capturePhoto(this, TAKE_PHOTO); + break; + case AttachmentTypeSelector.RECORD_VIDEO: + attachmentManager.captureVideo(this, RECORD_VIDEO); + break; + case AttachmentTypeSelector.ADD_WEBXDC: + AttachmentManager.selectWebxdc(this, PICK_WEBXDC); + break; } } @@ -1120,11 +1181,20 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity return new SettableFuture<>(false); } - return attachmentManager.setMedia(glideRequests, uri, null, mediaType, 0, 0, chatId, playbackViewModel); + return attachmentManager.setMedia( + glideRequests, uri, null, mediaType, 0, 0, chatId, playbackViewModel); } private ListenableFuture setMedia(DcMsg msg, @NonNull MediaType mediaType) { - return attachmentManager.setMedia(glideRequests, Uri.fromFile(new File(msg.getFile())), msg, mediaType, 0, 0, chatId, playbackViewModel); + return attachmentManager.setMedia( + glideRequests, + Uri.fromFile(new File(msg.getFile())), + msg, + mediaType, + 0, + 0, + chatId, + playbackViewModel); } private void addAttachmentContactInfo(int contactId) { @@ -1133,9 +1203,13 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity } try { - byte[] vcard = rpc.makeVcard(rpc.getSelectedAccountId(), Collections.singletonList(contactId)).getBytes(); + byte[] vcard = + rpc.makeVcard(rpc.getSelectedAccountId(), Collections.singletonList(contactId)) + .getBytes(); String mimeType = "application/octet-stream"; - setMedia(PersistentBlobProvider.getInstance().create(this, vcard, mimeType, "vcard.vcf"), MediaType.DOCUMENT); + setMedia( + PersistentBlobProvider.getInstance().create(this, vcard, mimeType, "vcard.vcf"), + MediaType.DOCUMENT); } catch (RpcException e) { Log.e(TAG, "RPC failed", e); } @@ -1155,21 +1229,23 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity protected static final int ACTION_SAVE_DRAFT = 2; protected ListenableFuture processComposeControls(int action) { - return processComposeControls(action, composeText.getTextTrimmed(), - attachmentManager.isAttachmentPresent() ? - attachmentManager.buildSlideDeck() : null); + return processComposeControls( + action, + composeText.getTextTrimmed(), + attachmentManager.isAttachmentPresent() ? attachmentManager.buildSlideDeck() : null); } - protected ListenableFuture processComposeControls(final int action, String body, SlideDeck slideDeck) { + protected ListenableFuture processComposeControls( + final int action, String body, SlideDeck slideDeck) { - final SettableFuture future = new SettableFuture<>(); + final SettableFuture future = new SettableFuture<>(); Optional quote = inputPanel.getQuote(); boolean editing = isEditing; // for a quick ui feedback, we clear the related controls immediately on sending messages. // for drafts, however, we do not change the controls, the activity may be resumed. - if (action==ACTION_SEND_OUT) { + if (action == ACTION_SEND_OUT) { composeText.setText(""); inputPanel.clearQuote(); } @@ -1180,124 +1256,132 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity DcContext dcContext = DcHelper.getContext(context); final int currentChatId = dcChat.getId(); - Util.runOnAnyBackgroundThread(() -> { - DcMsg msg = null; - int recompress = 0; + Util.runOnAnyBackgroundThread( + () -> { + DcMsg msg = null; + int recompress = 0; - if (editing) { - int msgId = quote.get().getQuotedMsg().getId(); - if (action == ACTION_SEND_OUT) { - dcContext.sendEditRequest(msgId, body); - } else { - dcContext.setDraft(currentChatId, null); - } - future.set(currentChatId); - return; - } - - if(slideDeck!=null) { - if (action==ACTION_SEND_OUT) { - Util.runOnMain(() -> attachmentManager.clear(glideRequests, false)); - } - - try { - if (slideDeck.getWebxdctDraftId() != 0) { - msg = dcContext.getDraft(currentChatId); - } else { - List attachments = slideDeck.asAttachments(); - for (Attachment attachment : attachments) { - String contentType = attachment.getContentType(); - if (MediaUtil.isImageType(contentType) && slideDeck.getDocumentSlide() == null) { - msg = new DcMsg(dcContext, - MediaUtil.isGif(contentType) ? DcMsg.DC_MSG_GIF : DcMsg.DC_MSG_IMAGE); - msg.setDimension(attachment.getWidth(), attachment.getHeight()); - } else if (MediaUtil.isAudioType(contentType)) { - msg = new DcMsg(dcContext, - attachment.isVoiceNote() ? DcMsg.DC_MSG_VOICE : DcMsg.DC_MSG_AUDIO); - } else if (MediaUtil.isVideoType(contentType) && slideDeck.getDocumentSlide() == null) { - msg = new DcMsg(dcContext, DcMsg.DC_MSG_VIDEO); - recompress = DcMsg.DC_MSG_VIDEO; - } else { - msg = new DcMsg(dcContext, DcMsg.DC_MSG_FILE); - } - String path = attachment.getRealPath(this); - msg.setFileAndDeduplicate(path, attachment.getFileName(), null); + if (editing) { + int msgId = quote.get().getQuotedMsg().getId(); + if (action == ACTION_SEND_OUT) { + dcContext.sendEditRequest(msgId, body); + } else { + dcContext.setDraft(currentChatId, null); } + future.set(currentChatId); + return; } - if (msg != null) { + + if (slideDeck != null) { + if (action == ACTION_SEND_OUT) { + Util.runOnMain(() -> attachmentManager.clear(glideRequests, false)); + } + + try { + if (slideDeck.getWebxdctDraftId() != 0) { + msg = dcContext.getDraft(currentChatId); + } else { + List attachments = slideDeck.asAttachments(); + for (Attachment attachment : attachments) { + String contentType = attachment.getContentType(); + if (MediaUtil.isImageType(contentType) && slideDeck.getDocumentSlide() == null) { + msg = + new DcMsg( + dcContext, + MediaUtil.isGif(contentType) ? DcMsg.DC_MSG_GIF : DcMsg.DC_MSG_IMAGE); + msg.setDimension(attachment.getWidth(), attachment.getHeight()); + } else if (MediaUtil.isAudioType(contentType)) { + msg = + new DcMsg( + dcContext, + attachment.isVoiceNote() ? DcMsg.DC_MSG_VOICE : DcMsg.DC_MSG_AUDIO); + } else if (MediaUtil.isVideoType(contentType) + && slideDeck.getDocumentSlide() == null) { + msg = new DcMsg(dcContext, DcMsg.DC_MSG_VIDEO); + recompress = DcMsg.DC_MSG_VIDEO; + } else { + msg = new DcMsg(dcContext, DcMsg.DC_MSG_FILE); + } + String path = attachment.getRealPath(this); + msg.setFileAndDeduplicate(path, attachment.getFileName(), null); + } + } + if (msg != null) { + msg.setText(body); + } + } catch (Exception e) { + e.printStackTrace(); + } + } else if (!body.isEmpty()) { + msg = new DcMsg(dcContext, DcMsg.DC_MSG_TEXT); msg.setText(body); } - } - catch(Exception e) { - e.printStackTrace(); - } - } - else if (!body.isEmpty()){ - msg = new DcMsg(dcContext, DcMsg.DC_MSG_TEXT); - msg.setText(body); - } - if (quote.isPresent()) { - if (msg == null) msg = new DcMsg(dcContext, DcMsg.DC_MSG_TEXT); - msg.setQuote(quote.get().getQuotedMsg()); - } - - if (action==ACTION_SEND_OUT) { - - // for WEBXDC, drafts are just sent out as is. - // for preparations and other cases, cleanup draft soon. - if (msg == null || msg.getType() != DcMsg.DC_MSG_WEBXDC) { - dcContext.setDraft(currentChatId, null); - } - - if(msg!=null) { - boolean doSend = true; - if (recompress==DcMsg.DC_MSG_VIDEO) { - Util.runOnMain(() -> { - if (isFinishing()) return; - progressDialog = ProgressDialog.show( - ConversationActivity.this, - "", - getString(R.string.one_moment), - true, - false - ); - }); - doSend = VideoRecoder.prepareVideo(ConversationActivity.this, currentChatId, msg); - Util.runOnMain(() -> { - try { - if (progressDialog != null) progressDialog.dismiss(); - } catch (final IllegalArgumentException e) { - // The activity is finishing/destroyed, do nothing. - } - }); + if (quote.isPresent()) { + if (msg == null) msg = new DcMsg(dcContext, DcMsg.DC_MSG_TEXT); + msg.setQuote(quote.get().getQuotedMsg()); } - if (doSend) { - if (dcContext.sendMsg(currentChatId, msg) == 0) { - String lastError = dcContext.getLastError(); - if (!"".equals(lastError)) { - Util.runOnMain(() -> Toast.makeText(ConversationActivity.this, lastError, Toast.LENGTH_LONG).show()); - } - future.set(currentChatId); - return; + if (action == ACTION_SEND_OUT) { + + // for WEBXDC, drafts are just sent out as is. + // for preparations and other cases, cleanup draft soon. + if (msg == null || msg.getType() != DcMsg.DC_MSG_WEBXDC) { + dcContext.setDraft(currentChatId, null); } - } - if (currentChatId == this.chatId) { - Util.runOnMain(() -> sendComplete()); + if (msg != null) { + boolean doSend = true; + if (recompress == DcMsg.DC_MSG_VIDEO) { + Util.runOnMain( + () -> { + if (isFinishing()) return; + progressDialog = + ProgressDialog.show( + ConversationActivity.this, + "", + getString(R.string.one_moment), + true, + false); + }); + doSend = VideoRecoder.prepareVideo(ConversationActivity.this, currentChatId, msg); + Util.runOnMain( + () -> { + try { + if (progressDialog != null) progressDialog.dismiss(); + } catch (final IllegalArgumentException e) { + // The activity is finishing/destroyed, do nothing. + } + }); + } + + if (doSend) { + if (dcContext.sendMsg(currentChatId, msg) == 0) { + String lastError = dcContext.getLastError(); + if (!"".equals(lastError)) { + Util.runOnMain( + () -> + Toast.makeText(ConversationActivity.this, lastError, Toast.LENGTH_LONG) + .show()); + } + future.set(currentChatId); + return; + } + } + + if (currentChatId == this.chatId) { + Util.runOnMain(() -> sendComplete()); + } + } + } else { + dcContext.setDraft(currentChatId, msg); } - } - } else { - dcContext.setDraft(currentChatId, msg); - } - future.set(currentChatId); - }); + future.set(currentChatId); + }); return future; } - protected void sendComplete() { if (fragment == null || !fragment.isVisible() || isFinishing()) { return; @@ -1308,7 +1392,6 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity attachmentManager.cleanup(); } - // handle attachment drawer, camera, recorder private void updateToggleButtonState() { @@ -1318,7 +1401,9 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity return; } - if (!isEditing && composeText.getText().length() == 0 && !attachmentManager.isAttachmentPresent()) { + if (!isEditing + && composeText.getText().length() == 0 + && !attachmentManager.isAttachmentPresent()) { buttonToggle.display(attachButton); quickAttachmentToggle.show(); } else { @@ -1330,10 +1415,10 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity @Override public void onRecorderPermissionRequired() { Permissions.with(this) - .request(Manifest.permission.RECORD_AUDIO) - .ifNecessary() - .withPermanentDenialDialog(getString(R.string.perm_explain_access_to_mic_denied)) - .execute(); + .request(Manifest.permission.RECORD_AUDIO) + .ifNecessary() + .withPermanentDenialDialog(getString(R.string.perm_explain_access_to_mic_denied)) + .execute(); } @Override @@ -1362,32 +1447,46 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); ListenableFuture> future = audioRecorder.stopRecording(); - future.addListener(new ListenableFuture.Listener>() { - @Override - public void onSuccess(final @NonNull Pair result) { - AudioSlide audioSlide = new AudioSlide(ConversationActivity.this, result.first, result.second, MediaUtil.AUDIO_M4A, true); - SlideDeck slideDeck = new SlideDeck(); - slideDeck.addSlide(audioSlide); - - processComposeControls(ACTION_SEND_OUT, "", slideDeck).addListener(new AssertedSuccessListener() { + future.addListener( + new ListenableFuture.Listener>() { @Override - public void onSuccess(Integer chatId) { - new AsyncTask() { - @Override - protected Void doInBackground(Void... params) { - PersistentBlobProvider.getInstance().delete(ConversationActivity.this, result.first); - return null; - } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + public void onSuccess(final @NonNull Pair result) { + AudioSlide audioSlide = + new AudioSlide( + ConversationActivity.this, + result.first, + result.second, + MediaUtil.AUDIO_M4A, + true); + SlideDeck slideDeck = new SlideDeck(); + slideDeck.addSlide(audioSlide); + + processComposeControls(ACTION_SEND_OUT, "", slideDeck) + .addListener( + new AssertedSuccessListener() { + @Override + public void onSuccess(Integer chatId) { + new AsyncTask() { + @Override + protected Void doInBackground(Void... params) { + PersistentBlobProvider.getInstance() + .delete(ConversationActivity.this, result.first); + return null; + } + }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } + }); + } + + @Override + public void onFailure(ExecutionException e) { + Toast.makeText( + ConversationActivity.this, + R.string.chat_unable_to_record_audio, + Toast.LENGTH_LONG) + .show(); } }); - } - - @Override - public void onFailure(ExecutionException e) { - Toast.makeText(ConversationActivity.this, R.string.chat_unable_to_record_audio, Toast.LENGTH_LONG).show(); - } - }); } @Override @@ -1399,26 +1498,32 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); ListenableFuture> future = audioRecorder.stopRecording(); - future.addListener(new ListenableFuture.Listener>() { - @Override - public void onSuccess(final Pair result) { - new AsyncTask() { + future.addListener( + new ListenableFuture.Listener>() { @Override - protected Void doInBackground(Void... params) { - PersistentBlobProvider.getInstance().delete(ConversationActivity.this, result.first); - return null; + public void onSuccess(final Pair result) { + new AsyncTask() { + @Override + protected Void doInBackground(Void... params) { + PersistentBlobProvider.getInstance() + .delete(ConversationActivity.this, result.first); + return null; + } + }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } - @Override - public void onFailure(ExecutionException e) {} - }); + @Override + public void onFailure(ExecutionException e) {} + }); } private void reloadEmojiPicker() { emojiPickerContainer.removeAllViews(); - emojiPicker = (MediaKeyboard) LayoutInflater.from(this).inflate(R.layout.conversation_activity_emojidrawer_stub, emojiPickerContainer, false); + emojiPicker = + (MediaKeyboard) + LayoutInflater.from(this) + .inflate( + R.layout.conversation_activity_emojidrawer_stub, emojiPickerContainer, false); emojiPickerContainer.addView(emojiPicker); inputPanel.setMediaKeyboard(emojiPicker); } @@ -1468,8 +1573,18 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity } private void sendSticker(@NonNull Uri uri, String contentType) { - Attachment attachment = new UriAttachment(uri, null, contentType, - AttachmentDatabase.TRANSFER_PROGRESS_STARTED, 0, 0, 0, null, null, false); + Attachment attachment = + new UriAttachment( + uri, + null, + contentType, + AttachmentDatabase.TRANSFER_PROGRESS_STARTED, + 0, + 0, + 0, + null, + null, + false); String path = attachment.getRealPath(this); Optional quote = inputPanel.getQuote(); @@ -1488,10 +1603,7 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity @Override public void onPlayPauseButtonClicked(View view) { - addActivityContext( - this.getIntent().getExtras(), - this.getClass().getName() - ); + addActivityContext(this.getIntent().getExtras(), this.getClass().getName()); } private class AttachmentTypeListener implements AttachmentTypeSelector.AttachmentClickedListener { @@ -1519,16 +1631,19 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity String rawText = composeText.getTextTrimmed(); if (rawText.length() < 1 && !attachmentManager.isAttachmentPresent()) { - Toast.makeText(ConversationActivity.this, R.string.chat_please_enter_message, - Toast.LENGTH_SHORT).show(); - } - else { - processComposeControls(ACTION_SEND_OUT).addListener(new AssertedSuccessListener() { - @Override - public void onSuccess(Integer chatId) { - DcHelper.getNotificationCenter(ConversationActivity.this).maybePlaySendSound(dcChat); - } - }); + Toast.makeText( + ConversationActivity.this, R.string.chat_please_enter_message, Toast.LENGTH_SHORT) + .show(); + } else { + processComposeControls(ACTION_SEND_OUT) + .addListener( + new AssertedSuccessListener() { + @Override + public void onSuccess(Integer chatId) { + DcHelper.getNotificationCenter(ConversationActivity.this) + .maybePlaySendSound(dcChat); + } + }); } } @@ -1557,7 +1672,8 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity } } - private class ComposeKeyPressedListener implements OnKeyListener, OnClickListener, TextWatcher, OnFocusChangeListener { + private class ComposeKeyPressedListener + implements OnKeyListener, OnClickListener, TextWatcher, OnFocusChangeListener { int beforeLength; @@ -1581,7 +1697,7 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity } @Override - public void beforeTextChanged(CharSequence s, int start, int count,int after) { + public void beforeTextChanged(CharSequence s, int start, int count, int after) { beforeLength = composeText.getTextTrimmed().length(); } @@ -1593,7 +1709,7 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity } @Override - public void onTextChanged(CharSequence s, int start, int before,int count) {} + public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void onFocusChange(View v, boolean hasFocus) {} @@ -1604,7 +1720,8 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity if (isEditing) composeText.setText(""); isEditing = false; // If you modify these lines you may also want to modify ConversationItem.setQuote(): - Recipient author = new Recipient(this, DcHelper.getContext(context).getContact(msg.getFromId())); + Recipient author = + new Recipient(this, DcHelper.getContext(context).getContact(msg.getFromId())); SlideDeck slideDeck = new SlideDeck(); if (msg.hasFile()) { @@ -1613,13 +1730,8 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity String text = msg.getSummarytext(500); - inputPanel.setQuote(GlideApp.with(this), - msg, - msg.getTimestamp(), - author, - text, - slideDeck, - false); + inputPanel.setQuote( + GlideApp.with(this), msg, msg.getTimestamp(), author, text, slideDeck, false); inputPanel.clickOnComposeInput(); } @@ -1627,18 +1739,14 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity @Override public void handleEditMessage(DcMsg msg) { isEditing = true; - Recipient author = new Recipient(this, DcHelper.getContext(context).getContact(msg.getFromId())); + Recipient author = + new Recipient(this, DcHelper.getContext(context).getContact(msg.getFromId())); SlideDeck slideDeck = new SlideDeck(); String text = msg.getSummarytext(500); - inputPanel.setQuote(GlideApp.with(this), - msg, - msg.getTimestamp(), - author, - text, - slideDeck, - true); + inputPanel.setQuote( + GlideApp.with(this), msg, msg.getTimestamp(), author, text, slideDeck, true); setDraftText(msg.getText()); inputPanel.clickOnComposeInput(); @@ -1657,37 +1765,38 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity int eventId = event.getId(); if ((eventId == DcContext.DC_EVENT_CHAT_MODIFIED && event.getData1Int() == chatId) - || (eventId == DcContext.DC_EVENT_CHAT_EPHEMERAL_TIMER_MODIFIED && event.getData1Int() == chatId) - || eventId == DcContext.DC_EVENT_CONTACTS_CHANGED) { + || (eventId == DcContext.DC_EVENT_CHAT_EPHEMERAL_TIMER_MODIFIED + && event.getData1Int() == chatId) + || eventId == DcContext.DC_EVENT_CONTACTS_CHANGED) { dcChat = dcContext.getChat(chatId); titleView.setTitle(glideRequests, dcChat); initializeSecurity(isSecureText, isDefaultSms); setComposePanelVisibility(false); initializeContactRequest(); } else if ((eventId == DcContext.DC_EVENT_INCOMING_MSG - || eventId == DcContext.DC_EVENT_MSG_READ) - && event.getData1Int() == chatId) { - DcContact contact = recipient.getDcContact(); - titleView.setSeenRecently(contact!=null? dcContext.getContact(contact.getId()).wasSeenRecently() : false); + || eventId == DcContext.DC_EVENT_MSG_READ) + && event.getData1Int() == chatId) { + DcContact contact = recipient.getDcContact(); + titleView.setSeenRecently( + contact != null ? dcContext.getContact(contact.getId()).wasSeenRecently() : false); } } - // in-chat search private int beforeSearchComposeVisibility = View.VISIBLE; - private Menu searchMenu = null; + private Menu searchMenu = null; private int[] searchResult = {}; - private int searchResultPosition = -1; + private int searchResultPosition = -1; private Toast lastToast = null; private void updateResultCounter(int curr, int total) { - if (searchMenu!=null) { + if (searchMenu != null) { MenuItem item = searchMenu.findItem(R.id.menu_search_counter); - if (curr!=-1) { - item.setTitle(String.format("%d/%d", total==0? 0 : curr+1, total)); + if (curr != -1) { + item.setTitle(String.format("%d/%d", total == 0 ? 0 : curr + 1, total)); item.setVisible(true); } else { item.setVisible(false); @@ -1712,15 +1821,15 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity } private void handleMenuSearchNext(boolean searchNext) { - if(searchResult.length>0) { - searchResultPosition += searchNext? 1 : -1; - if(searchResultPosition<0) searchResultPosition = searchResult.length-1; - if(searchResultPosition>=searchResult.length) searchResultPosition = 0; + if (searchResult.length > 0) { + searchResultPosition += searchNext ? 1 : -1; + if (searchResultPosition < 0) searchResultPosition = searchResult.length - 1; + if (searchResultPosition >= searchResult.length) searchResultPosition = 0; fragment.scrollToMsgId(searchResult[searchResultPosition]); updateResultCounter(searchResultPosition, searchResult.length); } else { // no search, scroll to first/last message - if(searchNext) { + if (searchNext) { fragment.scrollToBottom(); } else { fragment.scrollToTop(); @@ -1735,7 +1844,7 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity @Override public boolean onQueryTextChange(String query) { - if (lastToast!=null) { + if (lastToast != null) { lastToast.cancel(); lastToast = null; } @@ -1743,7 +1852,7 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity String normQuery = query.trim(); searchResult = DcHelper.getContext(context).searchMsgs(chatId, normQuery); - if(searchResult.length>0) { + if (searchResult.length > 0) { searchResultPosition = searchResult.length - 1; fragment.scrollToMsgId(searchResult[searchResultPosition]); updateResultCounter(searchResultPosition, searchResult.length); @@ -1771,12 +1880,12 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity } messageRequestBottomView.setVisibility(View.VISIBLE); - messageRequestBottomView.setAcceptOnClickListener(v -> { - DcHelper.getContext(context).acceptChat(chatId); - messageRequestBottomView.setVisibility(View.GONE); - composePanel.setVisibility(View.VISIBLE); - }); - + messageRequestBottomView.setAcceptOnClickListener( + v -> { + DcHelper.getContext(context).acceptChat(chatId); + messageRequestBottomView.setVisibility(View.GONE); + composePanel.setVisibility(View.VISIBLE); + }); if (dcChat.getType() == DcChat.DC_CHAT_TYPE_GROUP) { // We don't support blocking groups yet, so offer to delete it instead @@ -1786,15 +1895,17 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity } else { messageRequestBottomView.setBlockText(R.string.block); - messageRequestBottomView.setBlockOnClickListener(v -> { - // avoid showing compose panel on receiving DC_EVENT_CONTACTS_CHANGED for the chat that is no longer a request after blocking - DcHelper.getEventCenter(this).removeObserver(DcContext.DC_EVENT_CONTACTS_CHANGED, this); + messageRequestBottomView.setBlockOnClickListener( + v -> { + // avoid showing compose panel on receiving DC_EVENT_CONTACTS_CHANGED for the chat that + // is no longer a request after blocking + DcHelper.getEventCenter(this).removeObserver(DcContext.DC_EVENT_CONTACTS_CHANGED, this); - DcHelper.getContext(context).blockChat(chatId); - Bundle extras = new Bundle(); - extras.putInt(ConversationListFragment.RELOAD_LIST, 1); - handleReturnToConversationList(extras); - }); + DcHelper.getContext(context).blockChat(chatId); + Bundle extras = new Bundle(); + extras.putInt(ConversationListFragment.RELOAD_LIST, 1); + handleReturnToConversationList(extras); + }); messageRequestBottomView.setQuestion(null); } } diff --git a/src/main/java/org/thoughtcrime/securesms/ConversationItem.java b/src/main/java/org/thoughtcrime/securesms/ConversationItem.java index f91bf864d..47ee7d153 100644 --- a/src/main/java/org/thoughtcrime/securesms/ConversationItem.java +++ b/src/main/java/org/thoughtcrime/securesms/ConversationItem.java @@ -32,16 +32,20 @@ import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; - import androidx.annotation.DimenRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; - +import chat.delta.rpc.RpcException; +import chat.delta.rpc.types.CallInfo; +import chat.delta.rpc.types.CallState; +import chat.delta.rpc.types.Reactions; +import chat.delta.rpc.types.VcardContact; import com.b44t.messenger.DcChat; import com.b44t.messenger.DcContact; import com.b44t.messenger.DcMsg; - +import java.util.List; +import java.util.Set; import org.thoughtcrime.securesms.calls.CallCoordinator; import org.thoughtcrime.securesms.calls.CallUtil; import org.thoughtcrime.securesms.components.AvatarImageView; @@ -74,58 +78,46 @@ import org.thoughtcrime.securesms.util.Util; import org.thoughtcrime.securesms.util.ViewUtil; import org.thoughtcrime.securesms.util.views.Stub; -import java.util.List; -import java.util.Set; - -import chat.delta.rpc.RpcException; -import chat.delta.rpc.types.CallInfo; -import chat.delta.rpc.types.CallState; -import chat.delta.rpc.types.Reactions; -import chat.delta.rpc.types.VcardContact; - /** - * A view that displays an individual conversation item within a conversation - * thread. Used by ComposeMessageActivity's ListActivity via a ConversationAdapter. + * A view that displays an individual conversation item within a conversation thread. Used by + * ComposeMessageActivity's ListActivity via a ConversationAdapter. * * @author Moxie Marlinspike - * */ - -public class ConversationItem extends BaseConversationItem -{ +public class ConversationItem extends BaseConversationItem { private static final String TAG = ConversationItem.class.getSimpleName(); private static final Rect SWIPE_RECT = new Rect(); private static final int MAX_MEASURE_CALLS = 3; - private DcContact dcContact; + private DcContact dcContact; // Whether the sender's avatar and name should be shown (usually the case in group threads): - private boolean showSender; + private boolean showSender; private GlideRequests glideRequests; - protected ViewGroup bodyBubble; + protected ViewGroup bodyBubble; protected ReactionsConversationView reactionsView; - protected View replyView; - protected View jumptoView; - @Nullable private QuoteView quoteView; - private ConversationItemFooter footer; - private TextView groupSender; - private View groupSenderHolder; - private AvatarImageView contactPhoto; - protected ViewGroup contactPhotoHolder; - private ViewGroup container; - private Button msgActionButton; - private Button showFullButton; + protected View replyView; + protected View jumptoView; + @Nullable private QuoteView quoteView; + private ConversationItemFooter footer; + private TextView groupSender; + private View groupSenderHolder; + private AvatarImageView contactPhoto; + protected ViewGroup contactPhotoHolder; + private ViewGroup container; + private Button msgActionButton; + private Button showFullButton; - private @NonNull Stub mediaThumbnailStub; - private @NonNull Stub audioViewStub; - private @NonNull Stub documentViewStub; - private @NonNull Stub webxdcViewStub; - private Stub stickerStub; - private Stub vcardViewStub; - private Stub callViewStub; - private @Nullable EventListener eventListener; + private @NonNull Stub mediaThumbnailStub; + private @NonNull Stub audioViewStub; + private @NonNull Stub documentViewStub; + private @NonNull Stub webxdcViewStub; + private Stub stickerStub; + private Stub vcardViewStub; + private Stub callViewStub; + private @Nullable EventListener eventListener; private int measureCalls; @@ -146,27 +138,27 @@ public class ConversationItem extends BaseConversationItem initializeAttributes(); - this.bodyText = findViewById(R.id.conversation_item_body); - this.footer = findViewById(R.id.conversation_item_footer); - this.reactionsView = findViewById(R.id.reactions_view); - this.groupSender = findViewById(R.id.group_message_sender); - this.contactPhoto = findViewById(R.id.contact_photo); - this.contactPhotoHolder = findViewById(R.id.contact_photo_container); - this.bodyBubble = findViewById(R.id.body_bubble); - this.mediaThumbnailStub = new Stub<>(findViewById(R.id.image_view_stub)); - this.audioViewStub = new Stub<>(findViewById(R.id.audio_view_stub)); - this.documentViewStub = new Stub<>(findViewById(R.id.document_view_stub)); - this.webxdcViewStub = new Stub<>(findViewById(R.id.webxdc_view_stub)); - this.stickerStub = new Stub<>(findViewById(R.id.sticker_view_stub)); - this.vcardViewStub = new Stub<>(findViewById(R.id.vcard_view_stub)); - this.callViewStub = new Stub<>(findViewById(R.id.call_view_stub)); - this.groupSenderHolder = findViewById(R.id.group_sender_holder); - this.quoteView = findViewById(R.id.quote_view); - this.container = findViewById(R.id.container); - this.replyView = findViewById(R.id.reply_icon); - this.jumptoView = findViewById(R.id.jumpto_icon); - this.msgActionButton = findViewById(R.id.msg_action_button); - this.showFullButton = findViewById(R.id.show_full_button); + this.bodyText = findViewById(R.id.conversation_item_body); + this.footer = findViewById(R.id.conversation_item_footer); + this.reactionsView = findViewById(R.id.reactions_view); + this.groupSender = findViewById(R.id.group_message_sender); + this.contactPhoto = findViewById(R.id.contact_photo); + this.contactPhotoHolder = findViewById(R.id.contact_photo_container); + this.bodyBubble = findViewById(R.id.body_bubble); + this.mediaThumbnailStub = new Stub<>(findViewById(R.id.image_view_stub)); + this.audioViewStub = new Stub<>(findViewById(R.id.audio_view_stub)); + this.documentViewStub = new Stub<>(findViewById(R.id.document_view_stub)); + this.webxdcViewStub = new Stub<>(findViewById(R.id.webxdc_view_stub)); + this.stickerStub = new Stub<>(findViewById(R.id.sticker_view_stub)); + this.vcardViewStub = new Stub<>(findViewById(R.id.vcard_view_stub)); + this.callViewStub = new Stub<>(findViewById(R.id.call_view_stub)); + this.groupSenderHolder = findViewById(R.id.group_sender_holder); + this.quoteView = findViewById(R.id.quote_view); + this.container = findViewById(R.id.container); + this.replyView = findViewById(R.id.reply_icon); + this.jumptoView = findViewById(R.id.jumpto_icon); + this.msgActionButton = findViewById(R.id.msg_action_button); + this.showFullButton = findViewById(R.id.show_full_button); setOnClickListener(new ClickListener(null)); @@ -177,18 +169,20 @@ public class ConversationItem extends BaseConversationItem } @Override - public void bind(@NonNull DcMsg messageRecord, - @NonNull DcChat dcChat, - @NonNull GlideRequests glideRequests, - @NonNull Set batchSelected, - @NonNull Recipient recipients, - boolean pulseHighlight, - @Nullable AudioPlaybackViewModel playbackViewModel, - AudioView.OnActionListener audioPlayPauseListener) - { + public void bind( + @NonNull DcMsg messageRecord, + @NonNull DcChat dcChat, + @NonNull GlideRequests glideRequests, + @NonNull Set batchSelected, + @NonNull Recipient recipients, + boolean pulseHighlight, + @Nullable AudioPlaybackViewModel playbackViewModel, + AudioView.OnActionListener audioPlayPauseListener) { bindPartial(messageRecord, dcChat, batchSelected, pulseHighlight, recipients); - this.glideRequests = glideRequests; - this.showSender = ((dcChat.isMultiUser() || dcChat.isSelfTalk()) && !messageRecord.isOutgoing()) || messageRecord.getOverrideSenderName() != null; + this.glideRequests = glideRequests; + this.showSender = + ((dcChat.isMultiUser() || dcChat.isSelfTalk()) && !messageRecord.isOutgoing()) + || messageRecord.getOverrideSenderName() != null; if (showSender) { this.dcContact = dcContext.getContact(messageRecord.getFromId()); @@ -196,13 +190,14 @@ public class ConversationItem extends BaseConversationItem if (dcChat.isSelfTalk() && messageRecord.getOriginalMsgId() != 0) { jumptoView.setVisibility(View.VISIBLE); - jumptoView.setOnClickListener(view -> { - if (eventListener != null) { - eventListener.onJumpToOriginalClicked(messageRecord); - } - }); + jumptoView.setOnClickListener( + view -> { + if (eventListener != null) { + eventListener.onJumpToOriginalClicked(messageRecord); + } + }); } else { - jumptoView.setVisibility(View.GONE); + jumptoView.setVisibility(View.GONE); } setGutterSizes(messageRecord, showSender); @@ -222,7 +217,6 @@ public class ConversationItem extends BaseConversationItem } } - @Override public void setEventListener(@Nullable EventListener eventListener) { this.eventListener = eventListener; @@ -231,7 +225,8 @@ public class ConversationItem extends BaseConversationItem public boolean disallowSwipe(float downX, float downY) { // If it is possible to reply to a message, it should also be possible to swipe it. // For this to be possible we need a non-null reply icon. - // This means that `replyView != null` must always be the same as ConversationFragment.canReplyToMsg(messageRecord). + // This means that `replyView != null` must always be the same as + // ConversationFragment.canReplyToMsg(messageRecord). if (replyView == null) return true; if (!dcChat.canSend()) return true; @@ -254,7 +249,7 @@ public class ConversationItem extends BaseConversationItem if (quoteView == null) { throw new AssertionError(); } - int quoteWidth = quoteView.getMeasuredWidth(); + int quoteWidth = quoteView.getMeasuredWidth(); int availableWidth = getAvailableMessageBubbleWidth(quoteView); if (quoteWidth != availableWidth) { @@ -276,10 +271,11 @@ public class ConversationItem extends BaseConversationItem } private void initializeAttributes() { - final int[] attributes = new int[] { - R.attr.conversation_item_incoming_bubble_color, - R.attr.conversation_item_outgoing_bubble_color, - }; + final int[] attributes = + new int[] { + R.attr.conversation_item_incoming_bubble_color, + R.attr.conversation_item_outgoing_bubble_color, + }; try (TypedArray attrs = context.obtainStyledAttributes(attributes)) { incomingBubbleColor = attrs.getColor(0, Color.WHITE); outgoingBubbleColor = attrs.getColor(1, Color.WHITE); @@ -287,8 +283,7 @@ public class ConversationItem extends BaseConversationItem } @Override - public void unbind() { - } + public void unbind() {} public DcMsg getMessageRecord() { return messageRecord; @@ -309,8 +304,12 @@ public class ConversationItem extends BaseConversationItem super.setInteractionState(messageRecord, pulseHighlight); if (mediaThumbnailStub.resolved()) { - mediaThumbnailStub.get().setFocusable(!shouldInterceptClicks(messageRecord) && batchSelected.isEmpty()); - mediaThumbnailStub.get().setClickable(!shouldInterceptClicks(messageRecord) && batchSelected.isEmpty()); + mediaThumbnailStub + .get() + .setFocusable(!shouldInterceptClicks(messageRecord) && batchSelected.isEmpty()); + mediaThumbnailStub + .get() + .setClickable(!shouldInterceptClicks(messageRecord) && batchSelected.isEmpty()); mediaThumbnailStub.get().setLongClickable(batchSelected.isEmpty()); } @@ -319,22 +318,30 @@ public class ConversationItem extends BaseConversationItem } if (documentViewStub.resolved()) { - documentViewStub.get().setFocusable(!shouldInterceptClicks(messageRecord) && batchSelected.isEmpty()); + documentViewStub + .get() + .setFocusable(!shouldInterceptClicks(messageRecord) && batchSelected.isEmpty()); documentViewStub.get().setClickable(batchSelected.isEmpty()); } if (webxdcViewStub.resolved()) { - webxdcViewStub.get().setFocusable(!shouldInterceptClicks(messageRecord) && batchSelected.isEmpty()); + webxdcViewStub + .get() + .setFocusable(!shouldInterceptClicks(messageRecord) && batchSelected.isEmpty()); webxdcViewStub.get().setClickable(batchSelected.isEmpty()); } if (vcardViewStub.resolved()) { - vcardViewStub.get().setFocusable(!shouldInterceptClicks(messageRecord) && batchSelected.isEmpty()); + vcardViewStub + .get() + .setFocusable(!shouldInterceptClicks(messageRecord) && batchSelected.isEmpty()); vcardViewStub.get().setClickable(batchSelected.isEmpty()); } if (callViewStub.resolved()) { - callViewStub.get().setFocusable(!shouldInterceptClicks(messageRecord) && batchSelected.isEmpty()); + callViewStub + .get() + .setFocusable(!shouldInterceptClicks(messageRecord) && batchSelected.isEmpty()); callViewStub.get().setClickable(batchSelected.isEmpty()); } } @@ -347,7 +354,8 @@ public class ConversationItem extends BaseConversationItem if (audioViewStub.resolved() && audioViewStub.get().getVisibility() == View.VISIBLE) { desc += audioViewStub.get().getDescription() + "\n"; - } else if (documentViewStub.resolved() && documentViewStub.get().getVisibility() == View.VISIBLE) { + } else if (documentViewStub.resolved() + && documentViewStub.get().getVisibility() == View.VISIBLE) { desc += documentViewStub.get().getDescription() + "\n"; } else if (webxdcViewStub.resolved() && webxdcViewStub.get().getVisibility() == View.VISIBLE) { desc += webxdcViewStub.get().getDescription() + "\n"; @@ -355,7 +363,8 @@ public class ConversationItem extends BaseConversationItem desc += vcardViewStub.get().getDescription() + "\n"; } else if (callViewStub.resolved() && callViewStub.get().getVisibility() == View.VISIBLE) { desc += callViewStub.get().getDescription() + "\n"; - } else if (mediaThumbnailStub.resolved() && mediaThumbnailStub.get().getVisibility() == View.VISIBLE) { + } else if (mediaThumbnailStub.resolved() + && mediaThumbnailStub.get().getVisibility() == View.VISIBLE) { desc += mediaThumbnailStub.get().getDescription() + "\n"; } else if (stickerStub.resolved() && stickerStub.get().getVisibility() == View.VISIBLE) { desc += stickerStub.get().getDescription() + "\n"; @@ -374,7 +383,7 @@ public class ConversationItem extends BaseConversationItem private boolean hasAudio(DcMsg messageRecord) { int type = messageRecord.getType(); - return type==DcMsg.DC_MSG_AUDIO || type==DcMsg.DC_MSG_VOICE; + return type == DcMsg.DC_MSG_AUDIO || type == DcMsg.DC_MSG_VOICE; } private boolean hasQuote(DcMsg messageRecord) { @@ -383,31 +392,31 @@ public class ConversationItem extends BaseConversationItem private boolean hasThumbnail(DcMsg messageRecord) { int type = messageRecord.getType(); - return type==DcMsg.DC_MSG_GIF || type==DcMsg.DC_MSG_IMAGE || type==DcMsg.DC_MSG_VIDEO; + return type == DcMsg.DC_MSG_GIF || type == DcMsg.DC_MSG_IMAGE || type == DcMsg.DC_MSG_VIDEO; } private boolean hasSticker(DcMsg dcMsg) { - return dcMsg.getType()==DcMsg.DC_MSG_STICKER; + return dcMsg.getType() == DcMsg.DC_MSG_STICKER; } private boolean hasOnlyThumbnail(DcMsg messageRecord) { - return hasThumbnail(messageRecord) && - !hasAudio(messageRecord) && - !hasDocument(messageRecord) && - !hasWebxdc(messageRecord) && - !hasSticker(messageRecord); + return hasThumbnail(messageRecord) + && !hasAudio(messageRecord) + && !hasDocument(messageRecord) + && !hasWebxdc(messageRecord) + && !hasSticker(messageRecord); } private boolean hasWebxdc(DcMsg dcMsg) { - return dcMsg.getType()==DcMsg.DC_MSG_WEBXDC; + return dcMsg.getType() == DcMsg.DC_MSG_WEBXDC; } private boolean hasVcard(DcMsg dcMsg) { - return dcMsg.getType()==DcMsg.DC_MSG_VCARD; + return dcMsg.getType() == DcMsg.DC_MSG_VCARD; } private boolean hasDocument(DcMsg dcMsg) { - return dcMsg.getType()==DcMsg.DC_MSG_FILE; + return dcMsg.getType() == DcMsg.DC_MSG_FILE; } private void setBodyText(DcMsg messageRecord) { @@ -418,8 +427,7 @@ public class ConversationItem extends BaseConversationItem if (messageRecord.getType() == DcMsg.DC_MSG_CALL || text.isEmpty()) { bodyText.setVisibility(View.GONE); - } - else { + } else { SpannableString spannable = new SpannableString(text); if (batchSelected.isEmpty()) { spannable = Linkifier.linkify(spannable); @@ -429,13 +437,15 @@ public class ConversationItem extends BaseConversationItem } int downloadState = messageRecord.getDownloadState(); - if (downloadState == DcMsg.DC_DOWNLOAD_AVAILABLE || downloadState == DcMsg.DC_DOWNLOAD_FAILURE || downloadState == DcMsg.DC_DOWNLOAD_IN_PROGRESS) { + if (downloadState == DcMsg.DC_DOWNLOAD_AVAILABLE + || downloadState == DcMsg.DC_DOWNLOAD_FAILURE + || downloadState == DcMsg.DC_DOWNLOAD_IN_PROGRESS) { showFullButton.setVisibility(View.GONE); msgActionButton.setVisibility(View.VISIBLE); - if (downloadState==DcMsg.DC_DOWNLOAD_IN_PROGRESS) { + if (downloadState == DcMsg.DC_DOWNLOAD_IN_PROGRESS) { msgActionButton.setEnabled(false); msgActionButton.setText(R.string.downloading); - } else if (downloadState==DcMsg.DC_DOWNLOAD_FAILURE) { + } else if (downloadState == DcMsg.DC_DOWNLOAD_FAILURE) { msgActionButton.setEnabled(true); msgActionButton.setText(R.string.download_failed); } else { @@ -443,194 +453,231 @@ public class ConversationItem extends BaseConversationItem msgActionButton.setText(R.string.download); } - msgActionButton.setOnClickListener(view -> { - if (eventListener != null && batchSelected.isEmpty()) { - eventListener.onDownloadClicked(messageRecord); - } else { - passthroughClickListener.onClick(view); - } - }); + msgActionButton.setOnClickListener( + view -> { + if (eventListener != null && batchSelected.isEmpty()) { + eventListener.onDownloadClicked(messageRecord); + } else { + passthroughClickListener.onClick(view); + } + }); } else if (messageRecord.getType() == DcMsg.DC_MSG_WEBXDC) { showFullButton.setVisibility(View.GONE); msgActionButton.setVisibility(View.VISIBLE); msgActionButton.setEnabled(true); msgActionButton.setText(R.string.start_app); - msgActionButton.setOnClickListener(view -> { - if (batchSelected.isEmpty()) { - WebxdcActivity.openWebxdcActivity(getContext(), messageRecord); - } else { - passthroughClickListener.onClick(view); - } - }); - } - else if (messageRecord.hasHtml()) { + msgActionButton.setOnClickListener( + view -> { + if (batchSelected.isEmpty()) { + WebxdcActivity.openWebxdcActivity(getContext(), messageRecord); + } else { + passthroughClickListener.onClick(view); + } + }); + } else if (messageRecord.hasHtml()) { msgActionButton.setVisibility(View.GONE); showFullButton.setVisibility(View.VISIBLE); showFullButton.setEnabled(true); showFullButton.setText(R.string.show_full_message); - showFullButton.setOnClickListener(view -> { - if (eventListener != null && batchSelected.isEmpty()) { - eventListener.onShowFullClicked(messageRecord); - } else { - passthroughClickListener.onClick(view); - } - }); + showFullButton.setOnClickListener( + view -> { + if (eventListener != null && batchSelected.isEmpty()) { + eventListener.onShowFullClicked(messageRecord); + } else { + passthroughClickListener.onClick(view); + } + }); } else { msgActionButton.setVisibility(View.GONE); showFullButton.setVisibility(View.GONE); } } - private void setMediaAttributes(@NonNull DcMsg messageRecord, - boolean showSender, - AudioPlaybackViewModel playbackViewModel, - AudioView.OnActionListener audioPlayPauseListener) - { + private void setMediaAttributes( + @NonNull DcMsg messageRecord, + boolean showSender, + AudioPlaybackViewModel playbackViewModel, + AudioView.OnActionListener audioPlayPauseListener) { if (hasAudio(messageRecord)) { audioViewStub.get().setVisibility(View.VISIBLE); if (mediaThumbnailStub.resolved()) mediaThumbnailStub.get().setVisibility(View.GONE); - if (documentViewStub.resolved()) documentViewStub.get().setVisibility(View.GONE); - if (webxdcViewStub.resolved()) webxdcViewStub.get().setVisibility(View.GONE); - if (stickerStub.resolved()) stickerStub.get().setVisibility(View.GONE); - if (vcardViewStub.resolved()) vcardViewStub.get().setVisibility(View.GONE); - if (callViewStub.resolved()) callViewStub.get().setVisibility(View.GONE); + if (documentViewStub.resolved()) documentViewStub.get().setVisibility(View.GONE); + if (webxdcViewStub.resolved()) webxdcViewStub.get().setVisibility(View.GONE); + if (stickerStub.resolved()) stickerStub.get().setVisibility(View.GONE); + if (vcardViewStub.resolved()) vcardViewStub.get().setVisibility(View.GONE); + if (callViewStub.resolved()) callViewStub.get().setVisibility(View.GONE); audioViewStub.get().setPlaybackViewModel(playbackViewModel); audioViewStub.get().setOnActionListener(audioPlayPauseListener); audioViewStub.get().setAudio(new AudioSlide(context, messageRecord)); audioViewStub.get().setOnClickListener(passthroughClickListener); audioViewStub.get().setOnLongClickListener(passthroughClickListener); - audioViewStub.get().setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); + audioViewStub + .get() + .setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); - ViewUtil.updateLayoutParams(bodyText, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); - ViewUtil.updateLayoutParams(groupSenderHolder, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + ViewUtil.updateLayoutParams( + bodyText, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + ViewUtil.updateLayoutParams( + groupSenderHolder, + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT); footer.setVisibility(VISIBLE); - } - else if (hasDocument(messageRecord)) { + } else if (hasDocument(messageRecord)) { documentViewStub.get().setVisibility(View.VISIBLE); if (mediaThumbnailStub.resolved()) mediaThumbnailStub.get().setVisibility(View.GONE); - if (audioViewStub.resolved()) audioViewStub.get().setVisibility(View.GONE); - if (webxdcViewStub.resolved()) webxdcViewStub.get().setVisibility(View.GONE); - if (stickerStub.resolved()) stickerStub.get().setVisibility(View.GONE); - if (vcardViewStub.resolved()) vcardViewStub.get().setVisibility(View.GONE); - if (callViewStub.resolved()) callViewStub.get().setVisibility(View.GONE); + if (audioViewStub.resolved()) audioViewStub.get().setVisibility(View.GONE); + if (webxdcViewStub.resolved()) webxdcViewStub.get().setVisibility(View.GONE); + if (stickerStub.resolved()) stickerStub.get().setVisibility(View.GONE); + if (vcardViewStub.resolved()) vcardViewStub.get().setVisibility(View.GONE); + if (callViewStub.resolved()) callViewStub.get().setVisibility(View.GONE); //noinspection ConstantConditions documentViewStub.get().setDocument(new DocumentSlide(context, messageRecord)); documentViewStub.get().setDocumentClickListener(new ThumbnailClickListener()); documentViewStub.get().setOnLongClickListener(passthroughClickListener); - documentViewStub.get().setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); + documentViewStub + .get() + .setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); - ViewUtil.updateLayoutParams(bodyText, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); - ViewUtil.updateLayoutParams(groupSenderHolder, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + ViewUtil.updateLayoutParams( + bodyText, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + ViewUtil.updateLayoutParams( + groupSenderHolder, + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT); footer.setVisibility(VISIBLE); - } - else if (hasWebxdc(messageRecord)) { + } else if (hasWebxdc(messageRecord)) { webxdcViewStub.get().setVisibility(View.VISIBLE); if (mediaThumbnailStub.resolved()) mediaThumbnailStub.get().setVisibility(View.GONE); - if (audioViewStub.resolved()) audioViewStub.get().setVisibility(View.GONE); - if (documentViewStub.resolved()) documentViewStub.get().setVisibility(View.GONE); - if (stickerStub.resolved()) stickerStub.get().setVisibility(View.GONE); - if (vcardViewStub.resolved()) vcardViewStub.get().setVisibility(View.GONE); - if (callViewStub.resolved()) callViewStub.get().setVisibility(View.GONE); + if (audioViewStub.resolved()) audioViewStub.get().setVisibility(View.GONE); + if (documentViewStub.resolved()) documentViewStub.get().setVisibility(View.GONE); + if (stickerStub.resolved()) stickerStub.get().setVisibility(View.GONE); + if (vcardViewStub.resolved()) vcardViewStub.get().setVisibility(View.GONE); + if (callViewStub.resolved()) callViewStub.get().setVisibility(View.GONE); webxdcViewStub.get().setWebxdc(messageRecord, context.getString(R.string.webxdc_app)); webxdcViewStub.get().setWebxdcClickListener(new ThumbnailClickListener()); webxdcViewStub.get().setOnLongClickListener(passthroughClickListener); - webxdcViewStub.get().setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); + webxdcViewStub + .get() + .setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); - ViewUtil.updateLayoutParams(bodyText, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); - ViewUtil.updateLayoutParams(groupSenderHolder, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + ViewUtil.updateLayoutParams( + bodyText, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + ViewUtil.updateLayoutParams( + groupSenderHolder, + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT); footer.setVisibility(VISIBLE); - } - else if (hasVcard(messageRecord)) { + } else if (hasVcard(messageRecord)) { vcardViewStub.get().setVisibility(View.VISIBLE); if (mediaThumbnailStub.resolved()) mediaThumbnailStub.get().setVisibility(View.GONE); - if (audioViewStub.resolved()) audioViewStub.get().setVisibility(View.GONE); - if (documentViewStub.resolved()) documentViewStub.get().setVisibility(View.GONE); - if (webxdcViewStub.resolved()) webxdcViewStub.get().setVisibility(View.GONE); - if (stickerStub.resolved()) stickerStub.get().setVisibility(View.GONE); - if (callViewStub.resolved()) callViewStub.get().setVisibility(View.GONE); + if (audioViewStub.resolved()) audioViewStub.get().setVisibility(View.GONE); + if (documentViewStub.resolved()) documentViewStub.get().setVisibility(View.GONE); + if (webxdcViewStub.resolved()) webxdcViewStub.get().setVisibility(View.GONE); + if (stickerStub.resolved()) stickerStub.get().setVisibility(View.GONE); + if (callViewStub.resolved()) callViewStub.get().setVisibility(View.GONE); vcardViewStub.get().setVcard(glideRequests, new VcardSlide(context, messageRecord), rpc); vcardViewStub.get().setVcardClickListener(new ThumbnailClickListener()); vcardViewStub.get().setOnLongClickListener(passthroughClickListener); - vcardViewStub.get().setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); + vcardViewStub + .get() + .setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); - ViewUtil.updateLayoutParams(bodyText, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); - ViewUtil.updateLayoutParams(groupSenderHolder, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + ViewUtil.updateLayoutParams( + bodyText, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + ViewUtil.updateLayoutParams( + groupSenderHolder, + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT); footer.setVisibility(VISIBLE); - } - else if (messageRecord.getType() == DcMsg.DC_MSG_CALL) { + } else if (messageRecord.getType() == DcMsg.DC_MSG_CALL) { callViewStub.get().setVisibility(View.VISIBLE); if (mediaThumbnailStub.resolved()) mediaThumbnailStub.get().setVisibility(View.GONE); - if (audioViewStub.resolved()) audioViewStub.get().setVisibility(View.GONE); - if (documentViewStub.resolved()) documentViewStub.get().setVisibility(View.GONE); - if (webxdcViewStub.resolved()) webxdcViewStub.get().setVisibility(View.GONE); - if (stickerStub.resolved()) stickerStub.get().setVisibility(View.GONE); - if (vcardViewStub.resolved()) vcardViewStub.get().setVisibility(View.GONE); + if (audioViewStub.resolved()) audioViewStub.get().setVisibility(View.GONE); + if (documentViewStub.resolved()) documentViewStub.get().setVisibility(View.GONE); + if (webxdcViewStub.resolved()) webxdcViewStub.get().setVisibility(View.GONE); + if (stickerStub.resolved()) stickerStub.get().setVisibility(View.GONE); + if (vcardViewStub.resolved()) vcardViewStub.get().setVisibility(View.GONE); try { - callViewStub.get().setCallItem(messageRecord.isOutgoing(), rpc.callInfo(dcContext.getAccountId(), messageRecord.getId())); + callViewStub + .get() + .setCallItem( + messageRecord.isOutgoing(), + rpc.callInfo(dcContext.getAccountId(), messageRecord.getId())); } catch (RpcException e) { Log.e(TAG, "Error in Rpc.callInfo", e); } callViewStub.get().setCallClickListener(new CallClickListener()); callViewStub.get().setOnLongClickListener(passthroughClickListener); - callViewStub.get().setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); + callViewStub + .get() + .setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); - ViewUtil.updateLayoutParams(groupSenderHolder, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); - } - else if (hasThumbnail(messageRecord)) { + ViewUtil.updateLayoutParams( + groupSenderHolder, + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT); + } else if (hasThumbnail(messageRecord)) { mediaThumbnailStub.get().setVisibility(View.VISIBLE); - if (audioViewStub.resolved()) audioViewStub.get().setVisibility(View.GONE); + if (audioViewStub.resolved()) audioViewStub.get().setVisibility(View.GONE); if (documentViewStub.resolved()) documentViewStub.get().setVisibility(View.GONE); - if (webxdcViewStub.resolved()) webxdcViewStub.get().setVisibility(View.GONE); - if (stickerStub.resolved()) stickerStub.get().setVisibility(View.GONE); - if (vcardViewStub.resolved()) vcardViewStub.get().setVisibility(View.GONE); - if (callViewStub.resolved()) callViewStub.get().setVisibility(View.GONE); + if (webxdcViewStub.resolved()) webxdcViewStub.get().setVisibility(View.GONE); + if (stickerStub.resolved()) stickerStub.get().setVisibility(View.GONE); + if (vcardViewStub.resolved()) vcardViewStub.get().setVisibility(View.GONE); + if (callViewStub.resolved()) callViewStub.get().setVisibility(View.GONE); Slide slide = MediaUtil.getSlideForMsg(context, messageRecord); - MediaUtil.ThumbnailSize thumbnailSize = new MediaUtil.ThumbnailSize(messageRecord.getWidth(0), messageRecord.getHeight(0)); - if ((thumbnailSize.width<=0||thumbnailSize.height<=0)) { - if(messageRecord.getType()==DcMsg.DC_MSG_VIDEO) { - MediaUtil.createVideoThumbnailIfNeeded(context, slide.getUri(), slide.getThumbnailUri(), thumbnailSize); + MediaUtil.ThumbnailSize thumbnailSize = + new MediaUtil.ThumbnailSize(messageRecord.getWidth(0), messageRecord.getHeight(0)); + if ((thumbnailSize.width <= 0 || thumbnailSize.height <= 0)) { + if (messageRecord.getType() == DcMsg.DC_MSG_VIDEO) { + MediaUtil.createVideoThumbnailIfNeeded( + context, slide.getUri(), slide.getThumbnailUri(), thumbnailSize); } - if (thumbnailSize.width<=0||thumbnailSize.height<=0) { + if (thumbnailSize.width <= 0 || thumbnailSize.height <= 0) { thumbnailSize.width = 180; thumbnailSize.height = 180; } messageRecord.lateFilingMediaSize(thumbnailSize.width, thumbnailSize.height, 0); } - mediaThumbnailStub.get().setImageResource(glideRequests, - slide, - thumbnailSize.width, - thumbnailSize.height); + mediaThumbnailStub + .get() + .setImageResource(glideRequests, slide, thumbnailSize.width, thumbnailSize.height); mediaThumbnailStub.get().setThumbnailClickListener(new ThumbnailClickListener()); mediaThumbnailStub.get().setOnLongClickListener(passthroughClickListener); mediaThumbnailStub.get().setOnClickListener(passthroughClickListener); mediaThumbnailStub.get().showShade(TextUtils.isEmpty(messageRecord.getText())); - mediaThumbnailStub.get().setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); + mediaThumbnailStub + .get() + .setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); setThumbnailOutlineCorners(messageRecord, showSender); - bodyBubble.getLayoutParams().width = ViewUtil.dpToPx(readDimen(R.dimen.media_bubble_max_width)); - ViewUtil.updateLayoutParams(bodyText, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); - ViewUtil.updateLayoutParams(groupSenderHolder, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); + bodyBubble.getLayoutParams().width = + ViewUtil.dpToPx(readDimen(R.dimen.media_bubble_max_width)); + ViewUtil.updateLayoutParams( + bodyText, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); + ViewUtil.updateLayoutParams( + groupSenderHolder, + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT); footer.setVisibility(VISIBLE); - } - else if (hasSticker(messageRecord)) { + } else if (hasSticker(messageRecord)) { stickerStub.get().setVisibility(View.VISIBLE); - if (audioViewStub.resolved()) audioViewStub.get().setVisibility(View.GONE); - if (documentViewStub.resolved()) documentViewStub.get().setVisibility(View.GONE); - if (webxdcViewStub.resolved()) webxdcViewStub.get().setVisibility(View.GONE); + if (audioViewStub.resolved()) audioViewStub.get().setVisibility(View.GONE); + if (documentViewStub.resolved()) documentViewStub.get().setVisibility(View.GONE); + if (webxdcViewStub.resolved()) webxdcViewStub.get().setVisibility(View.GONE); if (mediaThumbnailStub.resolved()) mediaThumbnailStub.get().setVisibility(View.GONE); - if (vcardViewStub.resolved()) vcardViewStub.get().setVisibility(View.GONE); - if (callViewStub.resolved()) callViewStub.get().setVisibility(View.GONE); + if (vcardViewStub.resolved()) vcardViewStub.get().setVisibility(View.GONE); + if (callViewStub.resolved()) callViewStub.get().setVisibility(View.GONE); bodyBubble.setBackgroundColor(Color.TRANSPARENT); @@ -638,54 +685,59 @@ public class ConversationItem extends BaseConversationItem stickerStub.get().setThumbnailClickListener(new StickerClickListener()); stickerStub.get().setOnLongClickListener(passthroughClickListener); stickerStub.get().setOnClickListener(passthroughClickListener); - stickerStub.get().setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); + stickerStub + .get() + .setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); - ViewUtil.updateLayoutParams(bodyText, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); - ViewUtil.updateLayoutParams(groupSenderHolder, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + ViewUtil.updateLayoutParams( + bodyText, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + ViewUtil.updateLayoutParams( + groupSenderHolder, + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT); footer.setVisibility(VISIBLE); - } - else { + } else { if (mediaThumbnailStub.resolved()) mediaThumbnailStub.get().setVisibility(View.GONE); - if (audioViewStub.resolved()) audioViewStub.get().setVisibility(View.GONE); - if (documentViewStub.resolved()) documentViewStub.get().setVisibility(View.GONE); - if (webxdcViewStub.resolved()) webxdcViewStub.get().setVisibility(View.GONE); - if (vcardViewStub.resolved()) vcardViewStub.get().setVisibility(View.GONE); - if (callViewStub.resolved()) callViewStub.get().setVisibility(View.GONE); + if (audioViewStub.resolved()) audioViewStub.get().setVisibility(View.GONE); + if (documentViewStub.resolved()) documentViewStub.get().setVisibility(View.GONE); + if (webxdcViewStub.resolved()) webxdcViewStub.get().setVisibility(View.GONE); + if (vcardViewStub.resolved()) vcardViewStub.get().setVisibility(View.GONE); + if (callViewStub.resolved()) callViewStub.get().setVisibility(View.GONE); - ViewUtil.updateLayoutParams(bodyText, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); - ViewUtil.updateLayoutParams(groupSenderHolder, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + ViewUtil.updateLayoutParams( + bodyText, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + ViewUtil.updateLayoutParams( + groupSenderHolder, + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT); footer.setVisibility(VISIBLE); } } - private void setThumbnailOutlineCorners(@NonNull DcMsg current, - boolean showSender) - { - int defaultRadius = readDimen(R.dimen.message_corner_radius); + private void setThumbnailOutlineCorners(@NonNull DcMsg current, boolean showSender) { + int defaultRadius = readDimen(R.dimen.message_corner_radius); - int topLeft = defaultRadius; - int topRight = defaultRadius; - int bottomLeft = defaultRadius; + int topLeft = defaultRadius; + int topRight = defaultRadius; + int bottomLeft = defaultRadius; int bottomRight = defaultRadius; if (!TextUtils.isEmpty(current.getText())) { - bottomLeft = 0; + bottomLeft = 0; bottomRight = 0; } - if (showSender - || current.isForwarded() - || hasQuote(current)) { - topLeft = 0; + if (showSender || current.isForwarded() || hasQuote(current)) { + topLeft = 0; topRight = 0; } - if(bottomLeft != 0 && bottomRight !=0) { - if((current.isOutgoing() && ViewUtil.isLtr(this)) || (!current.isOutgoing() && ViewUtil.isRtl(this))) { + if (bottomLeft != 0 && bottomRight != 0) { + if ((current.isOutgoing() && ViewUtil.isLtr(this)) + || (!current.isOutgoing() && ViewUtil.isRtl(this))) { bottomRight = 0; - } - else { + } else { bottomLeft = 0; } } @@ -696,7 +748,7 @@ public class ConversationItem extends BaseConversationItem private void setContactPhoto() { if (contactPhoto == null) return; - if (!showSender || dcContact ==null) { + if (!showSender || dcContact == null) { contactPhoto.setVisibility(View.GONE); } else { contactPhoto.setAvatar(glideRequests, new Recipient(context, dcContact), true); @@ -720,7 +772,8 @@ public class ConversationItem extends BaseConversationItem } DcMsg msg = current.getQuotedMsg(); - // If you modify these lines you may also want to modify ConversationActivity.handleReplyMessage(): + // If you modify these lines you may also want to modify + // ConversationActivity.handleReplyMessage(): Recipient author = null; SlideDeck slideDeck = new SlideDeck(); if (msg != null) { @@ -733,29 +786,32 @@ public class ConversationItem extends BaseConversationItem } } - quoteView.setQuote(GlideApp.with(this), - msg, - author, - quoteTxt, - slideDeck, - current.getType() == DcMsg.DC_MSG_STICKER, - false); + quoteView.setQuote( + GlideApp.with(this), + msg, + author, + quoteTxt, + slideDeck, + current.getType() == DcMsg.DC_MSG_STICKER, + false); quoteView.setVisibility(View.VISIBLE); quoteView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT; - quoteView.setOnClickListener(view -> { - if (eventListener != null && batchSelected.isEmpty()) { - eventListener.onQuoteClicked(current); - } else { - passthroughClickListener.onClick(view); - } - }); + quoteView.setOnClickListener( + view -> { + if (eventListener != null && batchSelected.isEmpty()) { + eventListener.onQuoteClicked(current); + } else { + passthroughClickListener.onClick(view); + } + }); quoteView.setOnLongClickListener(passthroughClickListener); if (mediaThumbnailStub.resolved()) { - ViewUtil.setTopMargin(mediaThumbnailStub.get(), readDimen(R.dimen.message_bubble_top_padding)); + ViewUtil.setTopMargin( + mediaThumbnailStub.get(), readDimen(R.dimen.message_bubble_top_padding)); } else if (stickerStub.resolved()) { ViewUtil.setTopMargin(stickerStub.get(), readDimen(R.dimen.message_bubble_top_padding)); } @@ -787,13 +843,14 @@ public class ConversationItem extends BaseConversationItem reactionsView.clear(); } else { reactionsView.setReactions(reactions.reactions); - reactionsView.setOnClickListener(view -> { - if (eventListener != null && batchSelected.isEmpty()) { - eventListener.onReactionClicked(current); - } else { - passthroughClickListener.onClick(view); - } - }); + reactionsView.setOnClickListener( + view -> { + if (eventListener != null && batchSelected.isEmpty()) { + eventListener.onReactionClicked(current); + } else { + passthroughClickListener.onClick(view); + } + }); } } catch (RpcException e) { reactionsView.clear(); @@ -815,7 +872,7 @@ public class ConversationItem extends BaseConversationItem } private void setGroupMessageStatus() { - if (messageRecord.getType()==DcMsg.DC_MSG_STICKER) { + if (messageRecord.getType() == DcMsg.DC_MSG_STICKER) { this.groupSender.setVisibility(GONE); return; } else { @@ -823,14 +880,14 @@ public class ConversationItem extends BaseConversationItem } if (messageRecord.isForwarded()) { - if (showSender && dcContact !=null) { - this.groupSender.setText(context.getString(R.string.forwarded_by, messageRecord.getSenderName(dcContact))); + if (showSender && dcContact != null) { + this.groupSender.setText( + context.getString(R.string.forwarded_by, messageRecord.getSenderName(dcContact))); } else { this.groupSender.setText(context.getString(R.string.forwarded_message)); } this.groupSender.setTextColor(context.getResources().getColor(R.color.unknown_sender)); - } - else if (showSender && dcContact !=null) { + } else if (showSender && dcContact != null) { this.groupSender.setText(messageRecord.getSenderName(dcContact)); this.groupSender.setTextColor(Util.rgbToArgbColor(dcContact.getColor())); } @@ -850,25 +907,30 @@ public class ConversationItem extends BaseConversationItem } } - if(current.isForwarded()) { + if (current.isForwarded()) { groupSenderHolderVisibility = VISIBLE; } groupSenderHolder.setVisibility(groupSenderHolderVisibility); boolean collapse = false; - if(groupSenderHolderVisibility==VISIBLE && current.getType()==DcMsg.DC_MSG_TEXT) { + if (groupSenderHolderVisibility == VISIBLE && current.getType() == DcMsg.DC_MSG_TEXT) { collapse = true; } - int spacingTop = collapse? 0 /*2dp border come from the senderHolder*/ : readDimen(context, R.dimen.message_bubble_top_padding); + int spacingTop = + collapse + ? 0 /*2dp border come from the senderHolder*/ + : readDimen(context, R.dimen.message_bubble_top_padding); ViewUtil.setPaddingTop(bodyText, spacingTop); } private void setMessageShape(@NonNull DcMsg current) { int background; - background = current.isOutgoing() ? R.drawable.message_bubble_background_sent_alone - : R.drawable.message_bubble_background_received_alone; + background = + current.isOutgoing() + ? R.drawable.message_bubble_background_sent_alone + : R.drawable.message_bubble_background_received_alone; bodyBubble.setBackgroundResource(background); } @@ -887,11 +949,17 @@ public class ConversationItem extends BaseConversationItem private int getAvailableMessageBubbleWidth(@NonNull View forView) { int availableWidth; if (hasAudio(messageRecord)) { - availableWidth = audioViewStub.get().getMeasuredWidth() + ViewUtil.getLeftMargin(audioViewStub.get()) + ViewUtil.getRightMargin(audioViewStub.get()); + availableWidth = + audioViewStub.get().getMeasuredWidth() + + ViewUtil.getLeftMargin(audioViewStub.get()) + + ViewUtil.getRightMargin(audioViewStub.get()); } else if (hasThumbnail(messageRecord)) { availableWidth = mediaThumbnailStub.get().getMeasuredWidth(); } else { - availableWidth = bodyBubble.getMeasuredWidth() - bodyBubble.getPaddingLeft() - bodyBubble.getPaddingRight(); + availableWidth = + bodyBubble.getMeasuredWidth() + - bodyBubble.getPaddingLeft() + - bodyBubble.getPaddingRight(); } availableWidth -= ViewUtil.getLeftMargin(forView) + ViewUtil.getRightMargin(forView); @@ -901,12 +969,12 @@ public class ConversationItem extends BaseConversationItem @Override public void onAccessibilityClick() { - if (mediaThumbnailStub.resolved()) mediaThumbnailStub.get().performClick(); - else if (audioViewStub.resolved()) audioViewStub.get().togglePlay(); + if (mediaThumbnailStub.resolved()) mediaThumbnailStub.get().performClick(); + else if (audioViewStub.resolved()) audioViewStub.get().togglePlay(); else if (documentViewStub.resolved()) documentViewStub.get().performClick(); - else if (webxdcViewStub.resolved()) webxdcViewStub.get().performClick(); - else if (vcardViewStub.resolved()) vcardViewStub.get().performClick(); - else if (callViewStub.resolved()) callViewStub.get().performClick(); + else if (webxdcViewStub.resolved()) webxdcViewStub.get().performClick(); + else if (vcardViewStub.resolved()) vcardViewStub.get().performClick(); + else if (callViewStub.resolved()) callViewStub.get().performClick(); } /// Event handlers @@ -922,29 +990,37 @@ public class ConversationItem extends BaseConversationItem String path = slide.asAttachment().getRealPath(context); VcardContact vcardContact = rpc.parseVcard(path).get(0); new AlertDialog.Builder(context) - .setMessage(context.getString(R.string.ask_start_chat_with, vcardContact.displayName)) - .setPositiveButton(android.R.string.ok, (dialog, which) -> { - try { - List contactIds = rpc.importVcard(dcContext.getAccountId(), path); - if (!contactIds.isEmpty()) { - int chatId = dcContext.createChatByContactId(contactIds.get(0)); - if (chatId != 0) { - Intent intent = new Intent(context, ConversationActivity.class); - intent.putExtra(ConversationActivity.CHAT_ID_EXTRA, chatId); - context.startActivity(intent); - return; + .setMessage(context.getString(R.string.ask_start_chat_with, vcardContact.displayName)) + .setPositiveButton( + android.R.string.ok, + (dialog, which) -> { + try { + List contactIds = rpc.importVcard(dcContext.getAccountId(), path); + if (!contactIds.isEmpty()) { + int chatId = dcContext.createChatByContactId(contactIds.get(0)); + if (chatId != 0) { + Intent intent = new Intent(context, ConversationActivity.class); + intent.putExtra(ConversationActivity.CHAT_ID_EXTRA, chatId); + context.startActivity(intent); + return; + } + } + } catch (RpcException e) { + Log.e(TAG, "failed to import vCard", e); } - } - } catch (RpcException e) { - Log.e(TAG, "failed to import vCard", e); - } - Toast.makeText(context, context.getResources().getString(R.string.error), Toast.LENGTH_SHORT).show(); - }) - .setNegativeButton(R.string.cancel, null) - .show(); + Toast.makeText( + context, + context.getResources().getString(R.string.error), + Toast.LENGTH_SHORT) + .show(); + }) + .setNegativeButton(R.string.cancel, null) + .show(); } catch (RpcException e) { Log.e(TAG, "failed to parse vCard", e); - Toast.makeText(context, context.getResources().getString(R.string.error), Toast.LENGTH_SHORT).show(); + Toast.makeText( + context, context.getResources().getString(R.string.error), Toast.LENGTH_SHORT) + .show(); } } else if (MediaPreviewActivity.isTypeSupported(slide) && slide.getUri() != null) { Intent intent = new Intent(context, MediaPreviewActivity.class); @@ -976,7 +1052,7 @@ public class ConversationItem extends BaseConversationItem if (shouldInterceptClicks(messageRecord) || !batchSelected.isEmpty()) { performClick(); } else { - int chatId = messageRecord.getChatId(); + int chatId = messageRecord.getChatId(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (!messageRecord.isOutgoing() && callInfo.state instanceof CallState.Alerting) { int callId = messageRecord.getId(); diff --git a/src/main/java/org/thoughtcrime/securesms/EglUtils.java b/src/main/java/org/thoughtcrime/securesms/EglUtils.java index d8a881960..f9b856143 100644 --- a/src/main/java/org/thoughtcrime/securesms/EglUtils.java +++ b/src/main/java/org/thoughtcrime/securesms/EglUtils.java @@ -1,9 +1,7 @@ package org.thoughtcrime.securesms; import android.os.Build; - import androidx.annotation.RequiresApi; - import org.webrtc.EglBase; @RequiresApi(Build.VERSION_CODES.M) diff --git a/src/main/java/org/thoughtcrime/securesms/calls/AudioDevicePickerDialog.java b/src/main/java/org/thoughtcrime/securesms/calls/AudioDevicePickerDialog.java index 7d9aff9d4..f675b1c87 100644 --- a/src/main/java/org/thoughtcrime/securesms/calls/AudioDevicePickerDialog.java +++ b/src/main/java/org/thoughtcrime/securesms/calls/AudioDevicePickerDialog.java @@ -8,22 +8,16 @@ import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; - import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.core.telecom.CallEndpointCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; - import com.google.android.material.bottomsheet.BottomSheetDialog; - +import java.util.List; import org.thoughtcrime.securesms.R; -import java.util.List; - -/** - * Bottom sheet dialog for selecting audio output device - */ +/** Bottom sheet dialog for selecting audio output device */ @RequiresApi(Build.VERSION_CODES.O) public class AudioDevicePickerDialog extends BottomSheetDialog { private static final String TAG = AudioDevicePickerDialog.class.getSimpleName(); @@ -32,10 +26,11 @@ public class AudioDevicePickerDialog extends BottomSheetDialog { void onDeviceSelected(CallEndpointCompat endpoint); } - public AudioDevicePickerDialog(@NonNull Context context, - @NonNull List endpoints, - CallEndpointCompat currentEndpoint, - @NonNull OnDeviceSelectedListener listener) { + public AudioDevicePickerDialog( + @NonNull Context context, + @NonNull List endpoints, + CallEndpointCompat currentEndpoint, + @NonNull OnDeviceSelectedListener listener) { super(context); setContentView(R.layout.dialog_audio_device_picker); @@ -48,30 +43,30 @@ public class AudioDevicePickerDialog extends BottomSheetDialog { recyclerView.setLayoutManager(new LinearLayoutManager(context)); - AudioDeviceAdapter adapter = new AudioDeviceAdapter( - endpoints, - currentEndpoint, - endpoint -> { - listener.onDeviceSelected(endpoint); - dismiss(); - } - ); + AudioDeviceAdapter adapter = + new AudioDeviceAdapter( + endpoints, + currentEndpoint, + endpoint -> { + listener.onDeviceSelected(endpoint); + dismiss(); + }); recyclerView.setAdapter(adapter); } - /** - * RecyclerView adapter for audio devices - */ - private static class AudioDeviceAdapter extends RecyclerView.Adapter { + /** RecyclerView adapter for audio devices */ + private static class AudioDeviceAdapter + extends RecyclerView.Adapter { private final List endpoints; private final CallEndpointCompat currentEndpoint; private final OnDeviceSelectedListener listener; - AudioDeviceAdapter(List endpoints, - CallEndpointCompat currentEndpoint, - OnDeviceSelectedListener listener) { + AudioDeviceAdapter( + List endpoints, + CallEndpointCompat currentEndpoint, + OnDeviceSelectedListener listener) { this.endpoints = endpoints; this.currentEndpoint = currentEndpoint; this.listener = listener; @@ -80,19 +75,18 @@ public class AudioDevicePickerDialog extends BottomSheetDialog { @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { - View view = LayoutInflater.from(parent.getContext()).inflate( - R.layout.item_audio_device, - parent, - false - ); + View view = + LayoutInflater.from(parent.getContext()) + .inflate(R.layout.item_audio_device, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { CallEndpointCompat endpoint = endpoints.get(position); - boolean isCurrent = currentEndpoint != null && - endpoint.getIdentifier().equals(currentEndpoint.getIdentifier()); + boolean isCurrent = + currentEndpoint != null + && endpoint.getIdentifier().equals(currentEndpoint.getIdentifier()); holder.bind(endpoint, isCurrent, listener); } diff --git a/src/main/java/org/thoughtcrime/securesms/calls/CallActivity.java b/src/main/java/org/thoughtcrime/securesms/calls/CallActivity.java index 51cf4c284..9b3de3e34 100644 --- a/src/main/java/org/thoughtcrime/securesms/calls/CallActivity.java +++ b/src/main/java/org/thoughtcrime/securesms/calls/CallActivity.java @@ -20,7 +20,6 @@ import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; - import androidx.activity.OnBackPressedCallback; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; @@ -37,10 +36,10 @@ import androidx.core.view.WindowInsetsCompat; import androidx.core.view.WindowInsetsControllerCompat; import androidx.lifecycle.MediatorLiveData; import androidx.lifecycle.ViewModelProvider; - import com.google.android.material.button.MaterialButton; import com.google.android.material.button.MaterialButtonToggleGroup; - +import java.util.ArrayList; +import java.util.List; import org.thoughtcrime.securesms.BuildConfig; import org.thoughtcrime.securesms.EglUtils; import org.thoughtcrime.securesms.R; @@ -48,12 +47,7 @@ import org.webrtc.RendererCommon; import org.webrtc.SurfaceViewRenderer; import org.webrtc.VideoTrack; -import java.util.ArrayList; -import java.util.List; - -/** - * Full-screen call activity for VoIP calls - */ +/** Full-screen call activity for VoIP calls */ @RequiresApi(api = Build.VERSION_CODES.O) public class CallActivity extends AppCompatActivity { @@ -120,28 +114,29 @@ public class CallActivity extends AppCompatActivity { } // PiP listener - addOnPictureInPictureModeChangedListener(pipModeInfo -> { - boolean isInPipMode = pipModeInfo.isInPictureInPictureMode(); + addOnPictureInPictureModeChangedListener( + pipModeInfo -> { + boolean isInPipMode = pipModeInfo.isInPictureInPictureMode(); - if (isInPipMode) { - topBar.setVisibility(View.GONE); - bottomLayoutContainer.setVisibility(View.GONE); - localVideoContainer.setVisibility(View.GONE); - incomingCallPrompt.setVisibility(View.GONE); - } else { - topBar.setVisibility(View.VISIBLE); - bottomLayoutContainer.setVisibility(View.VISIBLE); - if (viewModel != null) { - CallViewModel.CallState state = viewModel.getCallState().getValue(); - if (state != null) { - updateUIForState(state); + if (isInPipMode) { + topBar.setVisibility(View.GONE); + bottomLayoutContainer.setVisibility(View.GONE); + localVideoContainer.setVisibility(View.GONE); + incomingCallPrompt.setVisibility(View.GONE); + } else { + topBar.setVisibility(View.VISIBLE); + bottomLayoutContainer.setVisibility(View.VISIBLE); + if (viewModel != null) { + CallViewModel.CallState state = viewModel.getCallState().getValue(); + if (state != null) { + updateUIForState(state); + } + } + layoutVideos(); } - } - layoutVideos(); - } - updateProximityWakeLock(); - }); + updateProximityWakeLock(); + }); initializeViewModel(); @@ -197,20 +192,15 @@ public class CallActivity extends AppCompatActivity { private void setupInsets() { View rootView = findViewById(R.id.call_root_view); - ViewCompat.setOnApplyWindowInsetsListener(rootView, (v, windowInsets) -> { - Insets systemBars = windowInsets.getInsets( - WindowInsetsCompat.Type.systemBars() - ); + ViewCompat.setOnApplyWindowInsetsListener( + rootView, + (v, windowInsets) -> { + Insets systemBars = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()); - v.setPadding( - systemBars.left, - systemBars.top, - systemBars.right, - systemBars.bottom - ); + v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom); - return windowInsets; - }); + return windowInsets; + }); } private void setupWindowFlags() { @@ -221,23 +211,24 @@ public class CallActivity extends AppCompatActivity { setShowWhenLocked(true); setTurnScreenOn(true); - KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); + KeyguardManager keyguardManager = + (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); if (keyguardManager != null) { keyguardManager.requestDismissKeyguard(this, null); } } else { - getWindow().addFlags( - WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | - WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | - WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON - ); + getWindow() + .addFlags( + WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED + | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD + | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); } getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // Control status bar icon colors WindowInsetsControllerCompat controller = - WindowCompat.getInsetsController(getWindow(), getWindow().getDecorView()); + WindowCompat.getInsetsController(getWindow(), getWindow().getDecorView()); controller.setAppearanceLightStatusBars(false); controller.setAppearanceLightNavigationBars(false); } @@ -251,10 +242,9 @@ public class CallActivity extends AppCompatActivity { } if (powerManager.isWakeLockLevelSupported(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)) { - proximityWakeLock = powerManager.newWakeLock( - PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, - "DeltaChat:ProximityLock" - ); + proximityWakeLock = + powerManager.newWakeLock( + PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "DeltaChat:ProximityLock"); proximityWakeLock.setReferenceCounted(false); Log.d(TAG, "Proximity wake lock initialized"); } else { @@ -309,78 +299,88 @@ public class CallActivity extends AppCompatActivity { } private void setupButtonListeners() { - answerButton.setOnClickListener(v -> { - if (viewModel != null) { - viewModel.answerCall(); - } - }); + answerButton.setOnClickListener( + v -> { + if (viewModel != null) { + viewModel.answerCall(); + } + }); - declineButton.setOnClickListener(v -> { - if (viewModel != null) { - viewModel.declineCall(); - } - finish(); - }); - - endCallButton.setOnClickListener(v -> { - if (viewModel != null) { - viewModel.hangUp(); - } - finish(); - }); - - muteButton.setOnClickListener(v -> { - if (viewModel != null) { - viewModel.toggleAudio(); - } - }); - - videoButton.setOnClickListener(v -> { - if (viewModel != null) { - viewModel.toggleVideo(); - } - }); - - speakerButton.setOnClickListener(v -> { - if (viewModel != null) { - showAudioDevicePicker(); - } - }); - - switchCameraButton.setOnClickListener(v -> { - if (viewModel != null) { - viewModel.switchCamera(); - } - }); - - getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) { - @Override - public void handleOnBackPressed() { - CallViewModel.CallState state = viewModel.getCallState().getValue(); - - if (isDeviceLocked() || state == null) { + declineButton.setOnClickListener( + v -> { + if (viewModel != null) { + viewModel.declineCall(); + } finish(); - return; - } + }); - switch (state) { - case RINGING: - case CONNECTING: - case CONNECTED: - case RECONNECTING: - enterPictureInPictureMode(createPipParams()); - break; + endCallButton.setOnClickListener( + v -> { + if (viewModel != null) { + viewModel.hangUp(); + } + finish(); + }); - case INITIALIZING: - case PROMPTING_USER_ACCEPT: - case ENDED: - case ERROR: - default: - finish(); - break; - } - } - }); + muteButton.setOnClickListener( + v -> { + if (viewModel != null) { + viewModel.toggleAudio(); + } + }); + + videoButton.setOnClickListener( + v -> { + if (viewModel != null) { + viewModel.toggleVideo(); + } + }); + + speakerButton.setOnClickListener( + v -> { + if (viewModel != null) { + showAudioDevicePicker(); + } + }); + + switchCameraButton.setOnClickListener( + v -> { + if (viewModel != null) { + viewModel.switchCamera(); + } + }); + + getOnBackPressedDispatcher() + .addCallback( + this, + new OnBackPressedCallback(true) { + @Override + public void handleOnBackPressed() { + CallViewModel.CallState state = viewModel.getCallState().getValue(); + + if (isDeviceLocked() || state == null) { + finish(); + return; + } + + switch (state) { + case RINGING: + case CONNECTING: + case CONNECTED: + case RECONNECTING: + enterPictureInPictureMode(createPipParams()); + break; + + case INITIALIZING: + case PROMPTING_USER_ACCEPT: + case ENDED: + case ERROR: + default: + finish(); + break; + } + } + }); } private void initializeViewModel() { @@ -398,79 +398,118 @@ public class CallActivity extends AppCompatActivity { viewModel.getCallState().observe(this, this::updateUIForState); // Display info - viewModel.getDisplayName().observe(this, name -> { - displayNameText.setText(name != null ? name : "Unknown"); - }); + viewModel + .getDisplayName() + .observe( + this, + name -> { + displayNameText.setText(name != null ? name : "Unknown"); + }); - viewModel.getDisplayIcon().observe(this, icon -> { - if (callerIconView != null) { - if (icon != null) { - callerIconView.setImageIcon(icon); - } else { - callerIconView.setImageResource(R.drawable.ic_person); - } - } + viewModel + .getDisplayIcon() + .observe( + this, + icon -> { + if (callerIconView != null) { + if (icon != null) { + callerIconView.setImageIcon(icon); + } else { + callerIconView.setImageResource(R.drawable.ic_person); + } + } - if (remoteAvatarView != null) { - if (icon != null) { - remoteAvatarView.setImageIcon(icon); - } else { - remoteAvatarView.setImageResource(R.drawable.ic_person); - } - } - }); + if (remoteAvatarView != null) { + if (icon != null) { + remoteAvatarView.setImageIcon(icon); + } else { + remoteAvatarView.setImageResource(R.drawable.ic_person); + } + } + }); // Audio/video state - viewModel.getAudioEnabled().observe(this, enabled -> { - muteButton.setSelected(!enabled); - muteButton.setImageResource(enabled ? - R.drawable.ic_mic_on : R.drawable.ic_mic_off); - }); + viewModel + .getAudioEnabled() + .observe( + this, + enabled -> { + muteButton.setSelected(!enabled); + muteButton.setImageResource(enabled ? R.drawable.ic_mic_on : R.drawable.ic_mic_off); + }); - viewModel.getVideoEnabled().observe(this, enabled -> { - videoButton.setSelected(!enabled); - videoButton.setImageResource(enabled ? - R.drawable.ic_videocam_on : R.drawable.ic_videocam_off); - }); + viewModel + .getVideoEnabled() + .observe( + this, + enabled -> { + videoButton.setSelected(!enabled); + videoButton.setImageResource( + enabled ? R.drawable.ic_videocam_on : R.drawable.ic_videocam_off); + }); - viewModel.getCurrentAudioEndpoint().observe(this, endpoint -> { - updateSpeakerButton(endpoint); - updateProximityWakeLock(); - }); + viewModel + .getCurrentAudioEndpoint() + .observe( + this, + endpoint -> { + updateSpeakerButton(endpoint); + updateProximityWakeLock(); + }); - viewModel.getAvailableAudioEndpoints().observe(this, endpoints -> { - // Need observe to trigger flow emit - Log.d(TAG, "Available endpoints updated, count: " + - (endpoints != null ? endpoints.size() : 0)); - }); + viewModel + .getAvailableAudioEndpoints() + .observe( + this, + endpoints -> { + // Need observe to trigger flow emit + Log.d( + TAG, + "Available endpoints updated, count: " + + (endpoints != null ? endpoints.size() : 0)); + }); // Errors - viewModel.getErrorMessage().observe(this, error -> { - if (error != null && !error.isEmpty()) { - Toast.makeText(this, error, Toast.LENGTH_LONG).show(); - } - }); + viewModel + .getErrorMessage() + .observe( + this, + error -> { + if (error != null && !error.isEmpty()) { + Toast.makeText(this, error, Toast.LENGTH_LONG).show(); + } + }); // Relay usage - viewModel.getIsRelayUsed().observe(this, isRelayUsed -> { - if (isRelayUsed != null) { - Log.d(TAG, "TURN relay is " + (isRelayUsed ? "being used" : "NOT being used")); - } - }); + viewModel + .getIsRelayUsed() + .observe( + this, + isRelayUsed -> { + if (isRelayUsed != null) { + Log.d(TAG, "TURN relay is " + (isRelayUsed ? "being used" : "NOT being used")); + } + }); // Set up LiveData sources videoConfigChanged.addSource(viewModel.getCallState(), v -> videoConfigChanged.setValue(true)); - videoConfigChanged.addSource(viewModel.getLocalVideoTrack(), v -> videoConfigChanged.setValue(true)); - videoConfigChanged.addSource(viewModel.getRemoteVideoTrack(), v -> videoConfigChanged.setValue(true)); - videoConfigChanged.addSource(viewModel.getVideoEnabled(), v -> videoConfigChanged.setValue(true)); - videoConfigChanged.addSource(viewModel.getRemoteVideoEnabled(), v -> videoConfigChanged.setValue(true)); + videoConfigChanged.addSource( + viewModel.getLocalVideoTrack(), v -> videoConfigChanged.setValue(true)); + videoConfigChanged.addSource( + viewModel.getRemoteVideoTrack(), v -> videoConfigChanged.setValue(true)); + videoConfigChanged.addSource( + viewModel.getVideoEnabled(), v -> videoConfigChanged.setValue(true)); + videoConfigChanged.addSource( + viewModel.getRemoteVideoEnabled(), v -> videoConfigChanged.setValue(true)); // Video layout - videoConfigChanged.observe(this, changed -> { - if (!isFinishing() && !isDestroyed()) { - layoutVideos(); - } - }); + videoConfigChanged.observe( + this, + changed -> { + if (!isFinishing() && !isDestroyed()) { + layoutVideos(); + } + }); } @Override @@ -485,9 +524,9 @@ public class CallActivity extends AppCompatActivity { private void updateUIForState(CallViewModel.CallState state) { Log.d(TAG, "Call state: " + state); - if (isInPictureInPictureMode() && - state != CallViewModel.CallState.ENDED && - state != CallViewModel.CallState.ERROR) { + if (isInPictureInPictureMode() + && state != CallViewModel.CallState.ENDED + && state != CallViewModel.CallState.ERROR) { return; } @@ -556,11 +595,14 @@ public class CallActivity extends AppCompatActivity { answerModeSelector.setVisibility(View.GONE); remoteAvatarView.setVisibility(View.VISIBLE); - new Handler(Looper.getMainLooper()).postDelayed(() -> { - if (!isFinishing()) { - finish(); - } - }, 2500); + new Handler(Looper.getMainLooper()) + .postDelayed( + () -> { + if (!isFinishing()) { + finish(); + } + }, + 2500); break; } @@ -590,14 +632,14 @@ public class CallActivity extends AppCompatActivity { } // Create and show BottomSheetDialog - AudioDevicePickerDialog dialog = new AudioDevicePickerDialog( - this, - endpoints, - currentEndpoint, - selectedEndpoint -> { - viewModel.selectAudioDevice(selectedEndpoint); - } - ); + AudioDevicePickerDialog dialog = + new AudioDevicePickerDialog( + this, + endpoints, + currentEndpoint, + selectedEndpoint -> { + viewModel.selectAudioDevice(selectedEndpoint); + }); dialog.show(); } @@ -624,13 +666,13 @@ public class CallActivity extends AppCompatActivity { CallViewModel.CallState state = viewModel.getCallState().getValue(); CallEndpointCompat endpoint = viewModel.getCurrentAudioEndpoint().getValue(); - return (state == CallViewModel.CallState.CONNECTED || - state == CallViewModel.CallState.RINGING || - state == CallViewModel.CallState.CONNECTING || - state == CallViewModel.CallState.RECONNECTING) && - endpoint != null && - endpoint.getType() == CallEndpointCompat.TYPE_EARPIECE && - !isInPictureInPictureMode(); + return (state == CallViewModel.CallState.CONNECTED + || state == CallViewModel.CallState.RINGING + || state == CallViewModel.CallState.CONNECTING + || state == CallViewModel.CallState.RECONNECTING) + && endpoint != null + && endpoint.getType() == CallEndpointCompat.TYPE_EARPIECE + && !isInPictureInPictureMode(); } private void initializeAnswerModeSelector() { @@ -638,18 +680,19 @@ public class CallActivity extends AppCompatActivity { // Set initial selection without triggering listener answerModeSelector.clearOnButtonCheckedListeners(); - answerModeSelector.check(coordinator.isStartsWithVideo() ? - R.id.answer_video_button : R.id.answer_audio_only_button); + answerModeSelector.check( + coordinator.isStartsWithVideo() ? R.id.answer_video_button : R.id.answer_audio_only_button); // Set listener - answerModeSelector.addOnButtonCheckedListener((group, checkedId, isChecked) -> { - if (isChecked && viewModel != null) { - boolean startsWithVideo = (checkedId == R.id.answer_video_button); - viewModel.setStartsWithVideo(startsWithVideo); - viewModel.switchToEarpiece(!startsWithVideo); - Log.d(TAG, "Answer mode changed to: " + (startsWithVideo ? "Video" : "Audio")); - } - }); + answerModeSelector.addOnButtonCheckedListener( + (group, checkedId, isChecked) -> { + if (isChecked && viewModel != null) { + boolean startsWithVideo = (checkedId == R.id.answer_video_button); + viewModel.setStartsWithVideo(startsWithVideo); + viewModel.switchToEarpiece(!startsWithVideo); + Log.d(TAG, "Answer mode changed to: " + (startsWithVideo ? "Video" : "Audio")); + } + }); } private void layoutVideos() { @@ -657,8 +700,7 @@ public class CallActivity extends AppCompatActivity { if (viewModel == null) return; CallViewModel.CallState state = viewModel.getCallState().getValue(); - if (state == CallViewModel.CallState.ENDED || - state == CallViewModel.CallState.ERROR) return; + if (state == CallViewModel.CallState.ENDED || state == CallViewModel.CallState.ERROR) return; detachAllTracks(); @@ -687,19 +729,19 @@ public class CallActivity extends AppCompatActivity { Log.d(TAG, "Video layout: Connected (local corner, remote full-screen)"); - } else if (!coordinator.isIncomingCall() && - (state == CallViewModel.CallState.RINGING || - state == CallViewModel.CallState.CONNECTING)) { - if (localTrack != null && Boolean.TRUE.equals(videoEnabled)) { - // Outgoing call before connected: local preview in center, hide corner - localTrack.addSink(remoteVideoView); - shouldShowRemoteVideoView = true; - localVideoContainer.setVisibility(View.GONE); - Log.d(TAG, "Video layout: Outgoing preview (local full-screen)"); - } else { - localVideoContainer.setVisibility(View.GONE); - Log.d(TAG, "Video layout: Outgoing audio-only"); - } + } else if (!coordinator.isIncomingCall() + && (state == CallViewModel.CallState.RINGING + || state == CallViewModel.CallState.CONNECTING)) { + if (localTrack != null && Boolean.TRUE.equals(videoEnabled)) { + // Outgoing call before connected: local preview in center, hide corner + localTrack.addSink(remoteVideoView); + shouldShowRemoteVideoView = true; + localVideoContainer.setVisibility(View.GONE); + Log.d(TAG, "Video layout: Outgoing preview (local full-screen)"); + } else { + localVideoContainer.setVisibility(View.GONE); + Log.d(TAG, "Video layout: Outgoing audio-only"); + } } else { // All other cases: just show avatar @@ -728,25 +770,21 @@ public class CallActivity extends AppCompatActivity { private boolean hasRequiredPermissions() { return ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) - == PackageManager.PERMISSION_GRANTED && - ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) - == PackageManager.PERMISSION_GRANTED; + == PackageManager.PERMISSION_GRANTED + && ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) + == PackageManager.PERMISSION_GRANTED; } private void requestRequiredPermissions() { ActivityCompat.requestPermissions( - this, - new String[] { - Manifest.permission.CAMERA, - Manifest.permission.RECORD_AUDIO - }, - PERMISSION_REQUEST_CODE - ); + this, + new String[] {Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO}, + PERMISSION_REQUEST_CODE); } @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, - @NonNull int[] grantResults) { + public void onRequestPermissionsResult( + int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == PERMISSION_REQUEST_CODE) { @@ -762,9 +800,8 @@ public class CallActivity extends AppCompatActivity { } if (!microphoneGranted) { - Toast.makeText(this, - "Microphone permission is required for calls", - Toast.LENGTH_LONG).show(); + Toast.makeText(this, "Microphone permission is required for calls", Toast.LENGTH_LONG) + .show(); finish(); return; } @@ -773,9 +810,9 @@ public class CallActivity extends AppCompatActivity { if (!cameraGranted && coordinator.isStartsWithVideo()) { Log.w(TAG, "Camera permission denied, switching to audio-only"); - Toast.makeText(this, - "Starting audio-only call (camera permission denied)", - Toast.LENGTH_SHORT).show(); + Toast.makeText( + this, "Starting audio-only call (camera permission denied)", Toast.LENGTH_SHORT) + .show(); coordinator.setStartsWithVideo(false); } @@ -817,17 +854,18 @@ public class CallActivity extends AppCompatActivity { } } - private PictureInPictureParams createPipParams() { - Rational aspectRatio = new Rational(9, 16); - PictureInPictureParams.Builder builder = new PictureInPictureParams.Builder() - .setAspectRatio(aspectRatio) - .setActions(new ArrayList<>()); + private PictureInPictureParams createPipParams() { + Rational aspectRatio = new Rational(9, 16); + PictureInPictureParams.Builder builder = + new PictureInPictureParams.Builder() + .setAspectRatio(aspectRatio) + .setActions(new ArrayList<>()); - // FIXME: PiP currently shows media controls. - // Will fix later: to fix this, we may need changes to audio playback implementation. + // FIXME: PiP currently shows media controls. + // Will fix later: to fix this, we may need changes to audio playback implementation. - return builder.build(); - } + return builder.build(); + } // Helper @@ -849,7 +887,6 @@ public class CallActivity extends AppCompatActivity { proximityWakeLock.release(); Log.d(TAG, "Proximity wake lock released in onDestroy"); } - } @Override diff --git a/src/main/java/org/thoughtcrime/securesms/calls/CallCoordinator.java b/src/main/java/org/thoughtcrime/securesms/calls/CallCoordinator.java index 504df1b05..7bd7057f6 100644 --- a/src/main/java/org/thoughtcrime/securesms/calls/CallCoordinator.java +++ b/src/main/java/org/thoughtcrime/securesms/calls/CallCoordinator.java @@ -22,7 +22,6 @@ import android.os.IBinder; import android.os.Looper; import android.telecom.DisconnectCause; import android.util.Log; - import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.core.app.NotificationManagerCompat; @@ -37,22 +36,12 @@ import androidx.lifecycle.FlowLiveDataConversions; import androidx.lifecycle.LiveData; import androidx.lifecycle.MediatorLiveData; import androidx.lifecycle.MutableLiveData; - +import chat.delta.rpc.Rpc; +import chat.delta.rpc.RpcException; import com.b44t.messenger.DcChat; import com.b44t.messenger.DcContext; import com.b44t.messenger.DcEvent; - -import org.thoughtcrime.securesms.ApplicationContext; -import org.thoughtcrime.securesms.R; -import org.thoughtcrime.securesms.connect.DcEventCenter; -import org.thoughtcrime.securesms.connect.DcHelper; -import org.webrtc.PeerConnection; -import org.webrtc.VideoTrack; - import java.util.List; - -import chat.delta.rpc.Rpc; -import chat.delta.rpc.RpcException; import kotlin.Unit; import kotlin.coroutines.Continuation; import kotlin.coroutines.CoroutineContext; @@ -63,6 +52,12 @@ import kotlinx.coroutines.CoroutineScopeKt; import kotlinx.coroutines.Dispatchers; import kotlinx.coroutines.flow.Flow; import kotlinx.coroutines.flow.FlowKt; +import org.thoughtcrime.securesms.ApplicationContext; +import org.thoughtcrime.securesms.R; +import org.thoughtcrime.securesms.connect.DcEventCenter; +import org.thoughtcrime.securesms.connect.DcHelper; +import org.webrtc.PeerConnection; +import org.webrtc.VideoTrack; @RequiresApi(api = Build.VERSION_CODES.O) public class CallCoordinator implements DcEventCenter.DcEventDelegate { @@ -85,7 +80,7 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { // LiveData for Observable State private final MutableLiveData connectionState = - new MutableLiveData<>(PeerConnection.PeerConnectionState.NEW); + new MutableLiveData<>(PeerConnection.PeerConnectionState.NEW); private final MutableLiveData localVideoTrack = new MutableLiveData<>(); private final MutableLiveData remoteVideoTrack = new MutableLiveData<>(); private final MutableLiveData localAudioEnabled = new MutableLiveData<>(true); @@ -98,8 +93,10 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { private final MutableLiveData displayIcon = new MutableLiveData<>(); // Audio Routing Support - private final MediatorLiveData currentAudioEndpoint = new MediatorLiveData<>(); - private final MediatorLiveData> availableAudioEndpoints = new MediatorLiveData<>(); + private final MediatorLiveData currentAudioEndpoint = + new MediatorLiveData<>(); + private final MediatorLiveData> availableAudioEndpoints = + new MediatorLiveData<>(); private LiveData currentAudioEndpointSource; private LiveData> availableAudioEndpointsSource; @@ -121,13 +118,14 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { private CallViewModel activeCallViewModel; private CallEndpointCompat preferredStartingEndpoint; - private final Runnable outgoingRingtoneRunnable = () -> { - synchronized (CallCoordinator.this) { - if (callService != null && activeCallId != null) { - callService.startOutgoingRingtone(); - } - } - }; + private final Runnable outgoingRingtoneRunnable = + () -> { + synchronized (CallCoordinator.this) { + if (callService != null && activeCallId != null) { + callService.startOutgoingRingtone(); + } + } + }; private CallCoordinator(Context context) { this.appContext = context.getApplicationContext(); @@ -149,19 +147,15 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { } private void createNotificationChannels() { - NotificationChannel incomingChannel = new NotificationChannel( - CHANNEL_ID_INCOMING, - "Incoming Calls", - NotificationManager.IMPORTANCE_HIGH - ); + NotificationChannel incomingChannel = + new NotificationChannel( + CHANNEL_ID_INCOMING, "Incoming Calls", NotificationManager.IMPORTANCE_HIGH); incomingChannel.setDescription("Notifications for incoming DeltaChat calls"); incomingChannel.setSound(null, null); - NotificationChannel ongoingChannel = new NotificationChannel( - CHANNEL_ID_ONGOING, - "Active Calls", - NotificationManager.IMPORTANCE_DEFAULT - ); + NotificationChannel ongoingChannel = + new NotificationChannel( + CHANNEL_ID_ONGOING, "Active Calls", NotificationManager.IMPORTANCE_DEFAULT); ongoingChannel.setDescription("Notifications for active DeltaChat calls"); ongoingChannel.setSound(null, null); @@ -171,8 +165,8 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { private void registerTelecom() { try { - int capabilities = CallsManager.CAPABILITY_BASELINE - | CallsManager.CAPABILITY_SUPPORTS_VIDEO_CALLING; + int capabilities = + CallsManager.CAPABILITY_BASELINE | CallsManager.CAPABILITY_SUPPORTS_VIDEO_CALLING; callsManager.registerAppWithTelecom(capabilities); Log.d(TAG, "Successfully registered through Telecom"); } catch (Exception e) { @@ -191,53 +185,54 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { } private void createServiceConnection() { - serviceConnection = new ServiceConnection() { - @Override - public void onServiceConnected(ComponentName name, IBinder service) { - synchronized (CallCoordinator.this) { - CallService.LocalBinder binder = (CallService.LocalBinder) service; - callService = binder.getService(); - Log.d(TAG, "Bound to CallService"); + serviceConnection = + new ServiceConnection() { + @Override + public void onServiceConnected(ComponentName name, IBinder service) { + synchronized (CallCoordinator.this) { + CallService.LocalBinder binder = (CallService.LocalBinder) service; + callService = binder.getService(); + Log.d(TAG, "Bound to CallService"); - if (activeAccId == null || activeCallId == null) { - Log.d(TAG, "Call already ended, not initializing service"); - stopAndUnbindService(); - notificationManager.cancel(NOTIFICATION_ID_CALL); - return; - } + if (activeAccId == null || activeCallId == null) { + Log.d(TAG, "Call already ended, not initializing service"); + stopAndUnbindService(); + notificationManager.cancel(NOTIFICATION_ID_CALL); + return; + } - if (!isIncomingCall) { + if (!isIncomingCall) { - // For outgoing call, show notification immediately - String calleeName = displayName.getValue(); - if (calleeName == null) { - calleeName = "Unknown"; + // For outgoing call, show notification immediately + String calleeName = displayName.getValue(); + if (calleeName == null) { + calleeName = "Unknown"; + } + + showOrUpdateOngoingNotification("Calling " + calleeName + "..."); + } + + // Initialize call + callService.initializeCall(); + + if (isIncomingCall) { + callService.startIncomingRingtone(); + } else { + mainHandler.removeCallbacks(outgoingRingtoneRunnable); + mainHandler.postDelayed(outgoingRingtoneRunnable, 1500); + } } - - showOrUpdateOngoingNotification("Calling " + calleeName + "..."); } - // Initialize call - callService.initializeCall(); - - if (isIncomingCall) { - callService.startIncomingRingtone(); - } else { - mainHandler.removeCallbacks(outgoingRingtoneRunnable); - mainHandler.postDelayed(outgoingRingtoneRunnable, 1500); + @Override + public void onServiceDisconnected(ComponentName name) { + synchronized (CallCoordinator.this) { + callService = null; + isServiceBound = false; + } + Log.d(TAG, "Unbound from CallService"); } - } - } - - @Override - public void onServiceDisconnected(ComponentName name) { - synchronized (CallCoordinator.this) { - callService = null; - isServiceBound = false; - } - Log.d(TAG, "Unbound from CallService"); - } - }; + }; } private synchronized void startAndBindService() { @@ -245,11 +240,8 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { this.appContext.startService(serviceIntent); // Set isServiceBound based on bindService return value - isServiceBound = this.appContext.bindService( - serviceIntent, - serviceConnection, - Context.BIND_AUTO_CREATE - ); + isServiceBound = + this.appContext.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE); Log.d(TAG, "Bind service result: " + isServiceBound); } @@ -332,8 +324,8 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { connectionState.postValue(state); // Handle connection failures - if (state == PeerConnection.PeerConnectionState.FAILED || - state == PeerConnection.PeerConnectionState.CLOSED) { + if (state == PeerConnection.PeerConnectionState.FAILED + || state == PeerConnection.PeerConnectionState.CLOSED) { handleConnectionEnded(state); } } @@ -391,26 +383,24 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { CallControlScope scope = activeCallControlScope; if (scope != null) { scope.answer( - CallAttributesCompat.CALL_TYPE_VIDEO_CALL, - new Continuation() { - @NonNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NonNull Object result) { - if (result instanceof CallControlResult) { - Log.d(TAG, "Answer succeeded with CallControlScope"); - } else if (result instanceof kotlin.Result.Failure) { - Log.e(TAG, "Answer failed", - ((kotlin.Result.Failure) result).exception); - reportError("Failed to answer call"); + CallAttributesCompat.CALL_TYPE_VIDEO_CALL, + new Continuation() { + @NonNull + @Override + public CoroutineContext getContext() { + return EmptyCoroutineContext.INSTANCE; } - } - } - ); + + @Override + public void resumeWith(@NonNull Object result) { + if (result instanceof CallControlResult) { + Log.d(TAG, "Answer succeeded with CallControlScope"); + } else if (result instanceof kotlin.Result.Failure) { + Log.e(TAG, "Answer failed", ((kotlin.Result.Failure) result).exception); + reportError("Failed to answer call"); + } + } + }); } notificationManager.cancel(NOTIFICATION_ID_CALL); @@ -457,38 +447,43 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { return; } - new Thread(() -> { - try { - // RPC returns the final callId - int callId = rpc.placeOutgoingCall(activeAccId, activeChatId, offerSdp, startsWithVideo); + new Thread( + () -> { + try { + // RPC returns the final callId + int callId = + rpc.placeOutgoingCall(activeAccId, activeChatId, offerSdp, startsWithVideo); - Log.d(TAG, "Outgoing call initiated, final callId: " + callId); + Log.d(TAG, "Outgoing call initiated, final callId: " + callId); - // Update our stored callId - this.activeCallId = callId; + // Update our stored callId + this.activeCallId = callId; - completeOutgoingCall(activeAccId, callId, activeChatId); + completeOutgoingCall(activeAccId, callId, activeChatId); - } catch (RpcException e) { - Log.e(TAG, "Failed to send offer with RPC", e); - reportError("Failed to initiate call: " + e.getMessage()); - } - }).start(); + } catch (RpcException e) { + Log.e(TAG, "Failed to send offer with RPC", e); + reportError("Failed to initiate call: " + e.getMessage()); + } + }) + .start(); } public void handleAnswerReady(String answerSdp) { Log.d(TAG, "handleAnswerReady, sending via RPC"); - new Thread(() -> { - try { - rpc.acceptIncomingCall(activeAccId, activeCallId, answerSdp); - Log.d(TAG, "Answer sent successfully"); + new Thread( + () -> { + try { + rpc.acceptIncomingCall(activeAccId, activeCallId, answerSdp); + Log.d(TAG, "Answer sent successfully"); - } catch (RpcException e) { - Log.e(TAG, "Failed to send answer with RPC", e); - reportError("Failed to answer call: " + e.getMessage()); - } - }).start(); + } catch (RpcException e) { + Log.e(TAG, "Failed to send answer with RPC", e); + reportError("Failed to answer call: " + e.getMessage()); + } + }) + .start(); } // Call Control Methods (CallViewModel) @@ -500,8 +495,7 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { } if (activeCallId == null || !activeCallId.equals(callId)) { - Log.d(TAG, "Call ID mismatch (active: " + - activeCallId + ", requested: " + callId + ")"); + Log.d(TAG, "Call ID mismatch (active: " + activeCallId + ", requested: " + callId + ")"); return; } @@ -556,25 +550,23 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { CallControlScope scope = activeCallControlScope; if (scope != null) { scope.disconnect( - new DisconnectCause(DisconnectCause.REJECTED), - new Continuation() { - @NonNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NonNull Object result) { - if (result instanceof CallControlResult) { - Log.d(TAG, "Decline succeeded with CallControlScope"); - } else if (result instanceof kotlin.Result.Failure) { - Log.e(TAG, "Decline failed", - ((kotlin.Result.Failure) result).exception); + new DisconnectCause(DisconnectCause.REJECTED), + new Continuation() { + @NonNull + @Override + public CoroutineContext getContext() { + return EmptyCoroutineContext.INSTANCE; } - } - } - ); + + @Override + public void resumeWith(@NonNull Object result) { + if (result instanceof CallControlResult) { + Log.d(TAG, "Decline succeeded with CallControlScope"); + } else if (result instanceof kotlin.Result.Failure) { + Log.e(TAG, "Decline failed", ((kotlin.Result.Failure) result).exception); + } + } + }); } // End call on service @@ -600,25 +592,23 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { CallControlScope scope = activeCallControlScope; if (scope != null) { scope.disconnect( - new DisconnectCause(DisconnectCause.LOCAL), - new Continuation() { - @NonNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NonNull Object result) { - if (result instanceof CallControlResult) { - Log.d(TAG, "Hang up succeeded with CallControlScope"); - } else if (result instanceof kotlin.Result.Failure) { - Log.e(TAG, "Hang up failed", - ((kotlin.Result.Failure) result).exception); + new DisconnectCause(DisconnectCause.LOCAL), + new Continuation() { + @NonNull + @Override + public CoroutineContext getContext() { + return EmptyCoroutineContext.INSTANCE; } - } - } - ); + + @Override + public void resumeWith(@NonNull Object result) { + if (result instanceof CallControlResult) { + Log.d(TAG, "Hang up succeeded with CallControlScope"); + } else if (result instanceof kotlin.Result.Failure) { + Log.e(TAG, "Hang up failed", ((kotlin.Result.Failure) result).exception); + } + } + }); } // End call on service @@ -638,10 +628,7 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { if (callService != null) { callService.setAudioEnabled(enabled); - callService.sendMutedState( - enabled, - Boolean.TRUE.equals(localVideoEnabled.getValue()) - ); + callService.sendMutedState(enabled, Boolean.TRUE.equals(localVideoEnabled.getValue())); } } @@ -653,10 +640,7 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { if (callService != null) { callService.setVideoEnabled(enabled); - callService.sendMutedState( - Boolean.TRUE.equals(localAudioEnabled.getValue()), - enabled - ); + callService.sendMutedState(Boolean.TRUE.equals(localAudioEnabled.getValue()), enabled); } } @@ -679,14 +663,13 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { private CallEndpointCompat getPreferredStartingEndpoint(boolean startsWithVideo) { try { Flow> endpointsFlow = - callsManager.getAvailableStartingCallEndpoints(); + callsManager.getAvailableStartingCallEndpoints(); // Block and get first emission from Flow List endpoints = - BuildersKt.runBlocking( - EmptyCoroutineContext.INSTANCE, - (scope, continuation) -> FlowKt.first(endpointsFlow, continuation) - ); + BuildersKt.runBlocking( + EmptyCoroutineContext.INSTANCE, + (scope, continuation) -> FlowKt.first(endpointsFlow, continuation)); // For audio-only calls, prefer earpiece if (!startsWithVideo && !endpoints.isEmpty()) { @@ -710,58 +693,62 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { Log.d(TAG, "Setting up audio endpoint flow collection"); // Create CoroutineScope for Flow collection - audioFlowScope = CoroutineScopeKt.CoroutineScope( - Dispatchers.getMain() - ); + audioFlowScope = CoroutineScopeKt.CoroutineScope(Dispatchers.getMain()); - availableAudioEndpointsSource = FlowLiveDataConversions.asLiveData( - scope.getAvailableEndpoints(), - audioFlowScope.getCoroutineContext(), - 5000L - ); + availableAudioEndpointsSource = + FlowLiveDataConversions.asLiveData( + scope.getAvailableEndpoints(), audioFlowScope.getCoroutineContext(), 5000L); - availableAudioEndpoints.addSource(availableAudioEndpointsSource, value -> { - Log.d(TAG, "Available audio endpoints changed, count: " + - (value != null ? value.size() : 0)); - availableAudioEndpoints.setValue(value); + availableAudioEndpoints.addSource( + availableAudioEndpointsSource, + value -> { + Log.d( + TAG, + "Available audio endpoints changed, count: " + (value != null ? value.size() : 0)); + availableAudioEndpoints.setValue(value); - // Turns out the system Bluetooth/AudioService will trigger a second audio change - // And Telecom tries to prevent it but doesn't always success, so a delayed - // switch is still needed as a backup - if (!hasAutoSelectedEarpiece && !startsWithVideo) { - hasAutoSelectedEarpiece = true; + // Turns out the system Bluetooth/AudioService will trigger a second audio change + // And Telecom tries to prevent it but doesn't always success, so a delayed + // switch is still needed as a backup + if (!hasAutoSelectedEarpiece && !startsWithVideo) { + hasAutoSelectedEarpiece = true; - if (value != null && !value.isEmpty()) { - // Find earpiece endpoint - CallEndpointCompat earpieceEndpoint = null; - for (CallEndpointCompat endpoint : value) { - if (endpoint.getType() == CallEndpointCompat.TYPE_EARPIECE) { - earpieceEndpoint = endpoint; - break; + if (value != null && !value.isEmpty()) { + // Find earpiece endpoint + CallEndpointCompat earpieceEndpoint = null; + for (CallEndpointCompat endpoint : value) { + if (endpoint.getType() == CallEndpointCompat.TYPE_EARPIECE) { + earpieceEndpoint = endpoint; + break; + } + } + + final CallEndpointCompat finalEarpieceEndpoint = earpieceEndpoint; + + mainHandler.postDelayed( + () -> { + if (finalEarpieceEndpoint != null) { + Log.d(TAG, "Auto-selecting earpiece for audio-only outgoing call"); + requestAudioEndpointChange(finalEarpieceEndpoint); + } else { + Log.d(TAG, "No earpiece endpoint available on this device"); + } + + // Only start collecting current audio endpoint after we made the selection + // The delay is to avoid a Telecom problem where at the beginning it will switch + // endpoints rapidly + startCurrentEndpointCollection(scope); + }, + 1000); } - } - - final CallEndpointCompat finalEarpieceEndpoint = earpieceEndpoint; - - mainHandler.postDelayed(() -> { - if (finalEarpieceEndpoint != null) { - Log.d(TAG, "Auto-selecting earpiece for audio-only outgoing call"); - requestAudioEndpointChange(finalEarpieceEndpoint); } else { - Log.d(TAG, "No earpiece endpoint available on this device"); + mainHandler.postDelayed( + () -> { + startCurrentEndpointCollection(scope); + }, + 500); } - - // Only start collecting current audio endpoint after we made the selection - // The delay is to avoid a Telecom problem where at the beginning it will switch endpoints rapidly - startCurrentEndpointCollection(scope); - }, 1000); - } - } else { - mainHandler.postDelayed(() -> { - startCurrentEndpointCollection(scope); - }, 500); - } - }); + }); } private synchronized void startCurrentEndpointCollection(CallControlScope scope) { @@ -777,17 +764,18 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { Log.d(TAG, "Starting current endpoint flow collection"); // Only add source if not already started - currentAudioEndpointSource = FlowLiveDataConversions.asLiveData( - scope.getCurrentCallEndpoint(), - audioFlowScope.getCoroutineContext(), - 5000L - ); + currentAudioEndpointSource = + FlowLiveDataConversions.asLiveData( + scope.getCurrentCallEndpoint(), audioFlowScope.getCoroutineContext(), 5000L); - currentAudioEndpoint.addSource(currentAudioEndpointSource, value1 -> { - Log.d(TAG, "Current audio endpoint changed: " + - (value1 != null ? value1.getName() : "null")); - currentAudioEndpoint.setValue(value1); - }); + currentAudioEndpoint.addSource( + currentAudioEndpointSource, + value1 -> { + Log.d( + TAG, + "Current audio endpoint changed: " + (value1 != null ? value1.getName() : "null")); + currentAudioEndpoint.setValue(value1); + }); } // Request Audio Endpoint Change @@ -800,26 +788,25 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { } activeCallControlScope.requestEndpointChange( - endpoint, - new Continuation() { - @NonNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NonNull Object result) { - if (result instanceof CallControlResult.Success) { - Log.d(TAG, "Audio endpoint change succeeded"); - } else if (result instanceof CallControlResult.Error) { - int errorCode = ((CallControlResult.Error) result).getErrorCode(); - Log.e(TAG, "Audio endpoint change failed with error code: " + errorCode); - reportError("Failed to change audio device"); + endpoint, + new Continuation() { + @NonNull + @Override + public CoroutineContext getContext() { + return EmptyCoroutineContext.INSTANCE; } - } - } - ); + + @Override + public void resumeWith(@NonNull Object result) { + if (result instanceof CallControlResult.Success) { + Log.d(TAG, "Audio endpoint change succeeded"); + } else if (result instanceof CallControlResult.Error) { + int errorCode = ((CallControlResult.Error) result).getErrorCode(); + Log.e(TAG, "Audio endpoint change failed with error code: " + errorCode); + reportError("Failed to change audio device"); + } + } + }); } // Helper (CallService) @@ -828,46 +815,48 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { return rpc.iceServers(activeAccId); } - @Override public void handleEvent(@NonNull DcEvent event) { int eventId = event.getId(); int accId = event.getAccountId(); - int callId = event.getData1Int(); // This is not semantically correct but shall work fine + int callId = event.getData1Int(); // This is not semantically correct but shall work fine // It seems this observer can fire on either main or background thread // Always move to background - new Thread(() -> { - boolean hasVideo; + new Thread( + () -> { + boolean hasVideo; - switch (eventId) { - case DcContext.DC_EVENT_INCOMING_CALL: - try { - hasVideo = this.rpc.callInfo(accId, callId).hasVideo; - } catch (RpcException e) { - Log.e(TAG, "Rpc.callInfo() failed", e); - hasVideo = false; - } - onIncomingCall(accId, callId, event.getData2Str(), hasVideo); - break; - case DcContext.DC_EVENT_INCOMING_CALL_ACCEPTED: - onIncomingCallAccepted(callId); - break; - case DcContext.DC_EVENT_OUTGOING_CALL_ACCEPTED: - String answerSDP = event.getData2Str(); - onOutgoingCallAccepted(callId, answerSDP); - break; - case DcContext.DC_EVENT_CALL_ENDED: - // This event is problematic because it can trigger in both directions, - // in addition to multiple other scenarios which cannot easily be distinguished - // May cause problems in edge cases - onCallEnded(accId, callId); - break; - } - }).start(); + switch (eventId) { + case DcContext.DC_EVENT_INCOMING_CALL: + try { + hasVideo = this.rpc.callInfo(accId, callId).hasVideo; + } catch (RpcException e) { + Log.e(TAG, "Rpc.callInfo() failed", e); + hasVideo = false; + } + onIncomingCall(accId, callId, event.getData2Str(), hasVideo); + break; + case DcContext.DC_EVENT_INCOMING_CALL_ACCEPTED: + onIncomingCallAccepted(callId); + break; + case DcContext.DC_EVENT_OUTGOING_CALL_ACCEPTED: + String answerSDP = event.getData2Str(); + onOutgoingCallAccepted(callId, answerSDP); + break; + case DcContext.DC_EVENT_CALL_ENDED: + // This event is problematic because it can trigger in both directions, + // in addition to multiple other scenarios which cannot easily be distinguished + // May cause problems in edge cases + onCallEnded(accId, callId); + break; + } + }) + .start(); } - private synchronized void onIncomingCall(int accId, int callId, String offerSdp, boolean startsWithVideo) { + private synchronized void onIncomingCall( + int accId, int callId, String offerSdp, boolean startsWithVideo) { Log.d(TAG, "onIncomingCall: accId=" + accId + ", callId=" + callId); if (activeCallId != null) { @@ -897,8 +886,7 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { this.preferredStartingEndpoint = getPreferredStartingEndpoint(startsWithVideo); // Add to CallsManager - CallAttributesCompat callAttributes = createCallAttributes( - callerName, callId, true); + CallAttributesCompat callAttributes = createCallAttributes(callerName, callId, true); addCallToTelecom(callAttributes, callerName, callerIcon); // Show CallStyle notification @@ -938,22 +926,23 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { // Call control scope should transition to ACTIVE if (activeCallControlScope != null) { - activeCallControlScope.setActive(new Continuation() { - @NonNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } + activeCallControlScope.setActive( + new Continuation() { + @NonNull + @Override + public CoroutineContext getContext() { + return EmptyCoroutineContext.INSTANCE; + } - @Override - public void resumeWith(@NonNull Object result) { - if (result instanceof CallControlResult) { - Log.d(TAG, "Outgoing call set to active: " + result); - } else if (result instanceof kotlin.Result.Failure) { - Log.e(TAG, "Failed to set active", ((kotlin.Result.Failure) result).exception); - } - } - }); + @Override + public void resumeWith(@NonNull Object result) { + if (result instanceof CallControlResult) { + Log.d(TAG, "Outgoing call set to active: " + result); + } else if (result instanceof kotlin.Result.Failure) { + Log.e(TAG, "Failed to set active", ((kotlin.Result.Failure) result).exception); + } + } + }); } String calleeName = displayName.getValue(); @@ -973,22 +962,21 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { // Disconnect from CallControlScope if (activeCallControlScope != null) { activeCallControlScope.disconnect( - // We actually don't know if this is incoming or outgoing - // But we have to provide one of LOCAL, REMOTE, MISSED, REJECTED - new DisconnectCause(DisconnectCause.REMOTE), - new Continuation() { - @NonNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } + // We actually don't know if this is incoming or outgoing + // But we have to provide one of LOCAL, REMOTE, MISSED, REJECTED + new DisconnectCause(DisconnectCause.REMOTE), + new Continuation() { + @NonNull + @Override + public CoroutineContext getContext() { + return EmptyCoroutineContext.INSTANCE; + } - @Override - public void resumeWith(@NonNull Object result) { - Log.d(TAG, "Disconnect completed"); - } - } - ); + @Override + public void resumeWith(@NonNull Object result) { + Log.d(TAG, "Disconnect completed"); + } + }); } if (callService != null) { @@ -1019,14 +1007,12 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { } } - /** - * Cleanup call state, used for clean up not initialized from backend events - */ + /** Cleanup call state, used for clean up not initialized from backend events */ public synchronized void cleanupCall(int accId, int callId) { Log.d(TAG, "cleanupCall: accId=" + accId + ", callId=" + callId); - if (activeCallId != null && !activeCallId.equals(callId) || - activeAccId != null && !activeAccId.equals(accId)) { + if (activeCallId != null && !activeCallId.equals(callId) + || activeAccId != null && !activeAccId.equals(accId)) { Log.w(TAG, "Cleanup accountId or callId doesn't match active call"); // Clean up anyway. Otherwise, no new calls can happen. } @@ -1046,19 +1032,20 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { mainHandler.removeCallbacks(outgoingRingtoneRunnable); - mainHandler.post(() -> { - if (currentAudioEndpointSource != null) { - currentAudioEndpoint.removeSource(currentAudioEndpointSource); - currentAudioEndpointSource = null; - Log.d(TAG, "Removed current audio endpoint source"); - } + mainHandler.post( + () -> { + if (currentAudioEndpointSource != null) { + currentAudioEndpoint.removeSource(currentAudioEndpointSource); + currentAudioEndpointSource = null; + Log.d(TAG, "Removed current audio endpoint source"); + } - if (availableAudioEndpointsSource != null) { - availableAudioEndpoints.removeSource(availableAudioEndpointsSource); - availableAudioEndpointsSource = null; - Log.d(TAG, "Removed available audio endpoints source"); - } - }); + if (availableAudioEndpointsSource != null) { + availableAudioEndpoints.removeSource(availableAudioEndpointsSource); + availableAudioEndpointsSource = null; + Log.d(TAG, "Removed available audio endpoints source"); + } + }); // Clear LiveData connectionState.postValue(PeerConnection.PeerConnectionState.CLOSED); @@ -1092,14 +1079,16 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { hasNotifiedBackend = true; - new Thread(() -> { - try { - rpc.endCall(activeAccId, activeCallId); - Log.d(TAG, "Backend notified: call ended"); - } catch (RpcException e) { - Log.e(TAG, "Failed to notify backend of call end", e); - } - }).start(); + new Thread( + () -> { + try { + rpc.endCall(activeAccId, activeCallId); + Log.d(TAG, "Backend notified: call ended"); + } catch (RpcException e) { + Log.e(TAG, "Failed to notify backend of call end", e); + } + }) + .start(); } private void resetLiveDataForNewCall() { @@ -1145,7 +1134,7 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { resetLiveDataForNewCall(); - this.activeCallId = -1; // Placeholder call ID for Intent + this.activeCallId = -1; // Placeholder call ID for Intent this.activeAccId = accId; this.activeChatId = chatId; this.isIncomingCall = false; @@ -1159,10 +1148,12 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { displayName.postValue(calleeName); // This is fine because icon is UI only and not used elsewhere - new Thread(() -> { - Icon calleeIcon = getIconFromChat(this.appContext, dcChat); - displayIcon.postValue(calleeIcon); - }).start(); + new Thread( + () -> { + Icon calleeIcon = getIconFromChat(this.appContext, dcChat); + displayIcon.postValue(calleeIcon); + }) + .start(); this.preferredStartingEndpoint = getPreferredStartingEndpoint(startsWithVideo); @@ -1191,95 +1182,91 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { Icon calleeIcon = displayIcon.getValue(); // Create call attributes - CallAttributesCompat callAttributes = createCallAttributes( - calleeName, activeCallId, false - ); + CallAttributesCompat callAttributes = createCallAttributes(calleeName, activeCallId, false); // Add call to CallsManager addCallToTelecom(callAttributes, calleeName, calleeIcon); } - private void addCallToTelecom(CallAttributesCompat callAttributes, - String displayName, Icon icon) { + private void addCallToTelecom( + CallAttributesCompat callAttributes, String displayName, Icon icon) { try { callsManager.addCall( - callAttributes, - // onAnswer - (callType, continuation) -> { - Log.d(TAG, "CallControlScope: onAnswer with type: " + callType); - if (activeCallViewModel != null && isIncomingCall) { - activeCallViewModel.onCallAnswered(); - } - return Unit.INSTANCE; - }, - // onDisconnect - (disconnectCause, continuation) -> { - Log.d(TAG, "CallControlScope: onDisconnect, cause: " + disconnectCause); - if (activeCallViewModel != null) { - activeCallViewModel.onCallDisconnected(disconnectCause); - } - return Unit.INSTANCE; - }, - // onSetActive - continuation -> { - Log.d(TAG, "CallControlScope: onSetActive"); - if (activeCallViewModel != null) { - activeCallViewModel.onCallActive(); - } - return Unit.INSTANCE; - }, - // onSetInactive - continuation -> { - Log.d(TAG, "CallControlScope: onSetInactive"); - if (activeCallViewModel != null) { - activeCallViewModel.onCallInactive(); - } - return Unit.INSTANCE; - }, - // CallControlScope lambda - scope -> { - Log.d(TAG, "CallControlScope initialized"); - activeCallControlScope = scope; + callAttributes, + // onAnswer + (callType, continuation) -> { + Log.d(TAG, "CallControlScope: onAnswer with type: " + callType); + if (activeCallViewModel != null && isIncomingCall) { + activeCallViewModel.onCallAnswered(); + } + return Unit.INSTANCE; + }, + // onDisconnect + (disconnectCause, continuation) -> { + Log.d(TAG, "CallControlScope: onDisconnect, cause: " + disconnectCause); + if (activeCallViewModel != null) { + activeCallViewModel.onCallDisconnected(disconnectCause); + } + return Unit.INSTANCE; + }, + // onSetActive + continuation -> { + Log.d(TAG, "CallControlScope: onSetActive"); + if (activeCallViewModel != null) { + activeCallViewModel.onCallActive(); + } + return Unit.INSTANCE; + }, + // onSetInactive + continuation -> { + Log.d(TAG, "CallControlScope: onSetInactive"); + if (activeCallViewModel != null) { + activeCallViewModel.onCallInactive(); + } + return Unit.INSTANCE; + }, + // CallControlScope lambda + scope -> { + Log.d(TAG, "CallControlScope initialized"); + activeCallControlScope = scope; - mainHandler.post(() -> { - setupAudioEndpointCollection(scope); + mainHandler.post( + () -> { + setupAudioEndpointCollection(scope); + }); + + return Unit.INSTANCE; + }, + new Continuation() { + @NonNull + @Override + public CoroutineContext getContext() { + return EmptyCoroutineContext.INSTANCE; + } + + @Override + public void resumeWith(@NonNull Object result) { + Log.d(TAG, "addCall completed"); + } }); - - return Unit.INSTANCE; - }, - new Continuation() { - @NonNull - @Override - public CoroutineContext getContext() { - return EmptyCoroutineContext.INSTANCE; - } - - @Override - public void resumeWith(@NonNull Object result) { - Log.d(TAG, "addCall completed"); - } - } - ); } catch (CallException e) { Log.e(TAG, "Failed to add call to Telecom", e); } } - private CallAttributesCompat createCallAttributes(String callerName, - int callId, - boolean isIncomingCall) { + private CallAttributesCompat createCallAttributes( + String callerName, int callId, boolean isIncomingCall) { Uri addressUri = Uri.parse(CALL_IDENTIFIER_SCHEME + callId); return new CallAttributesCompat( - callerName, - addressUri, - isIncomingCall ? - CallAttributesCompat.DIRECTION_INCOMING : - CallAttributesCompat.DIRECTION_OUTGOING, - CallAttributesCompat.CALL_TYPE_VIDEO_CALL, - CallAttributesCompat.SUPPORTS_SET_INACTIVE, - this.preferredStartingEndpoint - ); + callerName, + addressUri, + isIncomingCall + ? CallAttributesCompat.DIRECTION_INCOMING + : CallAttributesCompat.DIRECTION_OUTGOING, + CallAttributesCompat.CALL_TYPE_VIDEO_CALL, + CallAttributesCompat.SUPPORTS_SET_INACTIVE, + this.preferredStartingEndpoint); } private void showIncomingCallNotification(String callerName, Icon callerIcon) { @@ -1305,72 +1292,85 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { answerIntent.setAction(CallActivity.ACTION_ANSWER_CALL); answerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); - PendingIntent answerPendingIntent = PendingIntent.getActivity( - this.appContext, 0, answerIntent, - PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE - ); + PendingIntent answerPendingIntent = + PendingIntent.getActivity( + this.appContext, + 0, + answerIntent, + PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); // Decline intent Intent declineIntent = new Intent(this.appContext, CallActivity.class); declineIntent.setAction(CallActivity.ACTION_DECLINE_CALL); declineIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); - PendingIntent declinePendingIntent = PendingIntent.getActivity( - this.appContext, 1, declineIntent, - PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE - ); + PendingIntent declinePendingIntent = + PendingIntent.getActivity( + this.appContext, + 1, + declineIntent, + PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); // Full screen intent Intent fullScreenIntent = new Intent(this.appContext, CallActivity.class); fullScreenIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); - PendingIntent fullScreenPendingIntent = PendingIntent.getActivity( - this.appContext, 2, fullScreenIntent, - PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE - ); + PendingIntent fullScreenPendingIntent = + PendingIntent.getActivity( + this.appContext, + 2, + fullScreenIntent, + PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); Notification.Builder builder; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { // Android 12+, CallStyle - Person caller = new Person.Builder() - .setName(callerName) - .setIcon(callerIcon) - .setImportant(true) - .build(); + Person caller = + new Person.Builder().setName(callerName).setIcon(callerIcon).setImportant(true).build(); - builder = new Notification.Builder(this.appContext, CHANNEL_ID_INCOMING) - .setSmallIcon(R.drawable.icon_notification) - .setContentTitle("Incoming call") - .setContentText("Incoming call from " + callerName) - .setStyle(Notification.CallStyle.forIncomingCall( - caller, declinePendingIntent, answerPendingIntent) - .setIsVideo(startsWithVideo)) - .addPerson(caller) - .setFullScreenIntent(fullScreenPendingIntent, true) - .setOngoing(true) - .setCategory(Notification.CATEGORY_CALL); + builder = + new Notification.Builder(this.appContext, CHANNEL_ID_INCOMING) + .setSmallIcon(R.drawable.icon_notification) + .setContentTitle("Incoming call") + .setContentText("Incoming call from " + callerName) + .setStyle( + Notification.CallStyle.forIncomingCall( + caller, declinePendingIntent, answerPendingIntent) + .setIsVideo(startsWithVideo)) + .addPerson(caller) + .setFullScreenIntent(fullScreenPendingIntent, true) + .setOngoing(true) + .setCategory(Notification.CATEGORY_CALL); } else { // Android 8-12: Notification with actions - builder = new Notification.Builder(this.appContext, CHANNEL_ID_INCOMING) - .setSmallIcon(R.drawable.icon_notification) - .setContentTitle("Incoming call") - .setContentText("Incoming call from " + callerName) - .setFullScreenIntent(fullScreenPendingIntent, true) - .setOngoing(true) - .setColorized(true) - .setCategory(Notification.CATEGORY_CALL) - .addAction(new Notification.Action.Builder( - Icon.createWithResource(this.appContext, R.drawable.baseline_call_end_24), - "Decline", declinePendingIntent).build()) - .addAction(new Notification.Action.Builder( - Icon.createWithResource(this.appContext, R.drawable.baseline_call_24), - "Answer", answerPendingIntent).build()); + builder = + new Notification.Builder(this.appContext, CHANNEL_ID_INCOMING) + .setSmallIcon(R.drawable.icon_notification) + .setContentTitle("Incoming call") + .setContentText("Incoming call from " + callerName) + .setFullScreenIntent(fullScreenPendingIntent, true) + .setOngoing(true) + .setColorized(true) + .setCategory(Notification.CATEGORY_CALL) + .addAction( + new Notification.Action.Builder( + Icon.createWithResource(this.appContext, R.drawable.baseline_call_end_24), + "Decline", + declinePendingIntent) + .build()) + .addAction( + new Notification.Action.Builder( + Icon.createWithResource(this.appContext, R.drawable.baseline_call_24), + "Answer", + answerPendingIntent) + .build()); } notificationManager.notify(NOTIFICATION_ID_CALL, builder.build()); } - private Notification buildOngoingCallNotification(String statusText, String displayName, Icon icon) { + private Notification buildOngoingCallNotification( + String statusText, String displayName, Icon icon) { Intent activityIntent = new Intent(this.appContext, CallActivity.class); activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); @@ -1378,45 +1378,51 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { hangupIntent.setAction(CallActivity.ACTION_HANGUP_CALL); hangupIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); - PendingIntent hangupPendingIntent = PendingIntent.getActivity( - this.appContext, 3, hangupIntent, - PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE - ); + PendingIntent hangupPendingIntent = + PendingIntent.getActivity( + this.appContext, + 3, + hangupIntent, + PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); - PendingIntent contentIntent = PendingIntent.getActivity( - this.appContext, 4, activityIntent, - PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE - ); + PendingIntent contentIntent = + PendingIntent.getActivity( + this.appContext, + 4, + activityIntent, + PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); Notification.Builder builder; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { - Person person = new Person.Builder() - .setName(displayName) - .setIcon(icon) - .setImportant(true) - .build(); + Person person = + new Person.Builder().setName(displayName).setIcon(icon).setImportant(true).build(); - builder = new Notification.Builder(this.appContext, CHANNEL_ID_ONGOING) - .setSmallIcon(R.drawable.icon_notification) - .setContentTitle("Ongoing call") - .setContentText(statusText) - .setContentIntent(contentIntent) - .setStyle(Notification.CallStyle.forOngoingCall(person, hangupPendingIntent)) - .addPerson(person) - .setOngoing(true) - .setCategory(Notification.CATEGORY_CALL); + builder = + new Notification.Builder(this.appContext, CHANNEL_ID_ONGOING) + .setSmallIcon(R.drawable.icon_notification) + .setContentTitle("Ongoing call") + .setContentText(statusText) + .setContentIntent(contentIntent) + .setStyle(Notification.CallStyle.forOngoingCall(person, hangupPendingIntent)) + .addPerson(person) + .setOngoing(true) + .setCategory(Notification.CATEGORY_CALL); } else { - builder = new Notification.Builder(this.appContext, CHANNEL_ID_ONGOING) - .setSmallIcon(R.drawable.icon_notification) - .setContentTitle("Ongoing call") - .setContentText(statusText) - .setContentIntent(contentIntent) - .setOngoing(true) - .setColorized(true) - .setCategory(Notification.CATEGORY_CALL) - .addAction(new Notification.Action.Builder( - Icon.createWithResource(this.appContext, R.drawable.baseline_call_end_24), - "Hang up", hangupPendingIntent).build()); + builder = + new Notification.Builder(this.appContext, CHANNEL_ID_ONGOING) + .setSmallIcon(R.drawable.icon_notification) + .setContentTitle("Ongoing call") + .setContentText(statusText) + .setContentIntent(contentIntent) + .setOngoing(true) + .setColorized(true) + .setCategory(Notification.CATEGORY_CALL) + .addAction( + new Notification.Action.Builder( + Icon.createWithResource(this.appContext, R.drawable.baseline_call_end_24), + "Hang up", + hangupPendingIntent) + .build()); } return builder.build(); @@ -1451,8 +1457,7 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { private void launchCallActivity() { Intent intent = new Intent(this.appContext, CallActivity.class); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | - Intent.FLAG_ACTIVITY_SINGLE_TOP); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); this.appContext.startActivity(intent); Log.d(TAG, "Launching CallActivity, hasActiveViewModel: " + (activeCallViewModel != null)); @@ -1493,12 +1498,12 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { public boolean hasMicrophonePermission() { return ContextCompat.checkSelfPermission(appContext, Manifest.permission.RECORD_AUDIO) - == PackageManager.PERMISSION_GRANTED; + == PackageManager.PERMISSION_GRANTED; } public boolean hasCameraPermission() { return ContextCompat.checkSelfPermission(appContext, Manifest.permission.CAMERA) - == PackageManager.PERMISSION_GRANTED; + == PackageManager.PERMISSION_GRANTED; } public boolean hasMediaPermissions() { @@ -1508,13 +1513,13 @@ public class CallCoordinator implements DcEventCenter.DcEventDelegate { @RequiresApi(api = Build.VERSION_CODES.TIRAMISU) public boolean hasNotificationPermission() { return ContextCompat.checkSelfPermission(appContext, Manifest.permission.POST_NOTIFICATIONS) - == PackageManager.PERMISSION_GRANTED; + == PackageManager.PERMISSION_GRANTED; } @RequiresApi(api = Build.VERSION_CODES.UPSIDE_DOWN_CAKE) public boolean canUseFullScreenIntent() { NotificationManager notificationManager = - (NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE); + (NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE); return notificationManager != null && notificationManager.canUseFullScreenIntent(); } } diff --git a/src/main/java/org/thoughtcrime/securesms/calls/CallService.java b/src/main/java/org/thoughtcrime/securesms/calls/CallService.java index de31f99bf..1250e2412 100644 --- a/src/main/java/org/thoughtcrime/securesms/calls/CallService.java +++ b/src/main/java/org/thoughtcrime/securesms/calls/CallService.java @@ -15,22 +15,18 @@ import android.os.Binder; import android.os.Build; import android.os.IBinder; import android.util.Log; - import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; - +import chat.delta.rpc.RpcException; import org.thoughtcrime.securesms.webrtc.WebRTCClient; import org.webrtc.AudioTrack; import org.webrtc.MediaStream; import org.webrtc.PeerConnection; import org.webrtc.VideoTrack; -import chat.delta.rpc.RpcException; - /** - * Foreground service for VoIP calls - * Required to post CallStyle notifications on Android 12+ - * Owns WebRTC resources and keeps call alive + * Foreground service for VoIP calls Required to post CallStyle notifications on Android 12+ Owns + * WebRTC resources and keeps call alive */ @RequiresApi(api = Build.VERSION_CODES.O) public class CallService extends Service implements WebRTCClient.Callbacks { @@ -84,10 +80,7 @@ public class CallService extends Service implements WebRTCClient.Callbacks { // Initialization - /** - * Initialize call infrastructure - * Does NOT start camera/microphone - */ + /** Initialize call infrastructure Does NOT start camera/microphone */ public void initializeCall() { Log.d(TAG, "initializeCall (Infrastructure only)"); @@ -98,35 +91,34 @@ public class CallService extends Service implements WebRTCClient.Callbacks { webRTCClient = new WebRTCClient(getApplicationContext(), this); - mediaStreamManager = new MediaStreamManager( - getApplicationContext(), - webRTCClient.getPeerConnectionFactory() - ); + mediaStreamManager = + new MediaStreamManager(getApplicationContext(), webRTCClient.getPeerConnectionFactory()); fetchIceServersAndSetup(); } private void fetchIceServersAndSetup() { - new Thread(() -> { - try { - String iceServersJson = callCoordinator.fetchIceServers(); - Log.d(TAG, "ICE servers fetched: " + iceServersJson); + new Thread( + () -> { + try { + String iceServersJson = callCoordinator.fetchIceServers(); + Log.d(TAG, "ICE servers fetched: " + iceServersJson); - webRTCClient.configure(iceServersJson); + webRTCClient.configure(iceServersJson); - Log.d(TAG, "Infrastructure initialized, waiting for media capture"); + Log.d(TAG, "Infrastructure initialized, waiting for media capture"); - } catch (RpcException e) { - Log.e(TAG, "Failed to fetch ICE servers", e); - callCoordinator.reportError("Failed to connect: " + e.getMessage()); - } - }).start(); + } catch (RpcException e) { + Log.e(TAG, "Failed to fetch ICE servers", e); + callCoordinator.reportError("Failed to connect: " + e.getMessage()); + } + }) + .start(); } /** - * Start camera/microphone capture - * Must be called when app is in foreground - * Called by coordinator when ViewModel/Activity is ready + * Start camera/microphone capture Must be called when app is in foreground Called by coordinator + * when ViewModel/Activity is ready */ public void startMediaCapture() { Log.d(TAG, "startMediaCapture (Camera/Microphone)"); @@ -156,35 +148,35 @@ public class CallService extends Service implements WebRTCClient.Callbacks { Log.d(TAG, "Creating media stream with video: " + startsWithVideo); - mediaStreamManager.createMediaStream(new MediaStreamManager.Callback() { - @Override - public void onMediaStreamReady(MediaStream stream) { - Log.d(TAG, "Media stream ready"); + mediaStreamManager.createMediaStream( + new MediaStreamManager.Callback() { + @Override + public void onMediaStreamReady(MediaStream stream) { + Log.d(TAG, "Media stream ready"); - webRTCClient.setLocalMediaStream(stream); + webRTCClient.setLocalMediaStream(stream); - callCoordinator.setVideoEnabled(startsWithVideo); + callCoordinator.setVideoEnabled(startsWithVideo); - if (!stream.videoTracks.isEmpty()) { - VideoTrack localTrack = stream.videoTracks.get(0); - callCoordinator.updateLocalVideoTrack(localTrack); - } else { - Log.w(TAG, "Camera unavailable, call will be audio-only"); - callCoordinator.reportError("Camera unavailable, using audio only"); - callCoordinator.setVideoEnabled(false); - } + if (!stream.videoTracks.isEmpty()) { + VideoTrack localTrack = stream.videoTracks.get(0); + callCoordinator.updateLocalVideoTrack(localTrack); + } else { + Log.w(TAG, "Camera unavailable, call will be audio-only"); + callCoordinator.reportError("Camera unavailable, using audio only"); + callCoordinator.setVideoEnabled(false); + } - Log.d(TAG, "Media capture complete, ready for call"); + Log.d(TAG, "Media capture complete, ready for call"); + } - } - - @Override - public void onError(String error) { - Log.e(TAG, "Failed to setup media: " + error); - callCoordinator.reportError("Camera/microphone error: " + error); - callCoordinator.setVideoEnabled(false); - } - }); + @Override + public void onError(String error) { + Log.e(TAG, "Failed to setup media: " + error); + callCoordinator.reportError("Camera/microphone error: " + error); + callCoordinator.setVideoEnabled(false); + } + }); } // Ringtone Management @@ -213,21 +205,21 @@ public class CallService extends Service implements WebRTCClient.Callbacks { return; } - AudioAttributes audioAttributes = new AudioAttributes.Builder() - .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) - .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE) - .setLegacyStreamType(AudioManager.STREAM_RING) - .build(); + AudioAttributes audioAttributes = + new AudioAttributes.Builder() + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) + .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE) + .setLegacyStreamType(AudioManager.STREAM_RING) + .build(); ringtone.setAudioAttributes(audioAttributes); // Request audio focus - audioFocusRequest = new AudioFocusRequest.Builder( - AudioManager.AUDIOFOCUS_GAIN_TRANSIENT - ) - .setAudioAttributes(audioAttributes) - .setWillPauseWhenDucked(false) - .build(); + audioFocusRequest = + new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT) + .setAudioAttributes(audioAttributes) + .setWillPauseWhenDucked(false) + .build(); int result = audioManager.requestAudioFocus(audioFocusRequest); if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { @@ -253,18 +245,18 @@ public class CallService extends Service implements WebRTCClient.Callbacks { } try { - AudioAttributes audioAttributes = new AudioAttributes.Builder() - .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) - .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION) - .setLegacyStreamType(AudioManager.STREAM_VOICE_CALL) - .build(); + AudioAttributes audioAttributes = + new AudioAttributes.Builder() + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) + .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION) + .setLegacyStreamType(AudioManager.STREAM_VOICE_CALL) + .build(); - audioFocusRequest = new AudioFocusRequest.Builder( - AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK - ) - .setAudioAttributes(audioAttributes) - .setWillPauseWhenDucked(false) - .build(); + audioFocusRequest = + new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK) + .setAudioAttributes(audioAttributes) + .setWillPauseWhenDucked(false) + .build(); int result = audioManager.requestAudioFocus(audioFocusRequest); if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { @@ -289,9 +281,7 @@ public class CallService extends Service implements WebRTCClient.Callbacks { } } - /** - * Stop playing ringtone - */ + /** Stop playing ringtone */ public void stopRingtone() { Log.d(TAG, "stopRingtone"); diff --git a/src/main/java/org/thoughtcrime/securesms/calls/CallUtil.java b/src/main/java/org/thoughtcrime/securesms/calls/CallUtil.java index 68b61e55d..2eba3a682 100644 --- a/src/main/java/org/thoughtcrime/securesms/calls/CallUtil.java +++ b/src/main/java/org/thoughtcrime/securesms/calls/CallUtil.java @@ -6,14 +6,11 @@ import android.graphics.drawable.Drawable; import android.graphics.drawable.Icon; import android.os.Build; import android.util.Log; - import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.core.telecom.CallEndpointCompat; - import com.b44t.messenger.DcChat; import com.bumptech.glide.load.engine.DiskCacheStrategy; - import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.connect.DcHelper; import org.thoughtcrime.securesms.contacts.avatars.ContactPhoto; @@ -58,27 +55,37 @@ public class CallUtil { Recipient recipient = new Recipient(context, dcChat); ContactPhoto contactPhoto = recipient.getContactPhoto(context); - int wh = context.getResources() - .getDimensionPixelSize(R.dimen.contact_photo_target_size); + int wh = context.getResources().getDimensionPixelSize(R.dimen.contact_photo_target_size); Bitmap bitmap; if (contactPhoto != null) { - bitmap = GlideApp.with(context) - .asBitmap() - .load(contactPhoto) - .diskCacheStrategy(DiskCacheStrategy.ALL) - .circleCrop() - .submit(wh, wh) - .get(); + bitmap = + GlideApp.with(context) + .asBitmap() + .load(contactPhoto) + .diskCacheStrategy(DiskCacheStrategy.ALL) + .circleCrop() + .submit(wh, wh) + .get(); } else { - Drawable drawable = recipient.getFallbackContactPhoto() - .asDrawable(context, recipient.getFallbackAvatarColor()); + Drawable drawable = + recipient + .getFallbackContactPhoto() + .asDrawable(context, recipient.getFallbackAvatarColor()); bitmap = BitmapUtil.createFromDrawable(drawable, wh, wh); } if (bitmap != null) { - Log.d(TAG, "Bitmap loaded: " + bitmap.getWidth() + "x" + bitmap.getHeight() - + ", config=" + bitmap.getConfig() + ", recycled=" + bitmap.isRecycled()); + Log.d( + TAG, + "Bitmap loaded: " + + bitmap.getWidth() + + "x" + + bitmap.getHeight() + + ", config=" + + bitmap.getConfig() + + ", recycled=" + + bitmap.isRecycled()); Icon icon = Icon.createWithBitmap(bitmap); Log.d(TAG, "Icon created successfully"); return icon; diff --git a/src/main/java/org/thoughtcrime/securesms/calls/CallViewModel.java b/src/main/java/org/thoughtcrime/securesms/calls/CallViewModel.java index 5c7d12a3e..3522c6366 100644 --- a/src/main/java/org/thoughtcrime/securesms/calls/CallViewModel.java +++ b/src/main/java/org/thoughtcrime/securesms/calls/CallViewModel.java @@ -5,7 +5,6 @@ import android.graphics.drawable.Icon; import android.os.Build; import android.telecom.DisconnectCause; import android.util.Log; - import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.core.telecom.CallEndpointCompat; @@ -13,12 +12,10 @@ import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.LiveData; import androidx.lifecycle.MediatorLiveData; import androidx.lifecycle.Observer; - +import java.util.List; import org.webrtc.PeerConnection; import org.webrtc.VideoTrack; -import java.util.List; - @RequiresApi(api = Build.VERSION_CODES.O) public class CallViewModel extends AndroidViewModel { @@ -103,20 +100,22 @@ public class CallViewModel extends AndroidViewModel { } private void setupConnectionStateObserver() { - callState.addSource(callCoordinator.getConnectionState(), state -> { - CallState newState = translateConnectionState(state); + callState.addSource( + callCoordinator.getConnectionState(), + state -> { + CallState newState = translateConnectionState(state); - if (callState.getValue() != newState) { - callState.setValue(newState); - } + if (callState.getValue() != newState) { + callState.setValue(newState); + } - if (state == PeerConnection.PeerConnectionState.FAILED || - state == PeerConnection.PeerConnectionState.CLOSED) { - if (!hasCallEnded) { - hasCallEnded = true; - } - } - }); + if (state == PeerConnection.PeerConnectionState.FAILED + || state == PeerConnection.PeerConnectionState.CLOSED) { + if (!hasCallEnded) { + hasCallEnded = true; + } + } + }); } private CallState translateConnectionState(PeerConnection.PeerConnectionState state) { @@ -132,7 +131,7 @@ public class CallViewModel extends AndroidViewModel { if (callCoordinator.isIncomingCall()) { return CallState.CONNECTING; } else { - return CallState.RINGING; // Mirror TypeScript + return CallState.RINGING; // Mirror TypeScript } case CONNECTED: @@ -168,10 +167,7 @@ public class CallViewModel extends AndroidViewModel { answerCallWhenReady(); } - /** - * Answer incoming call (WebRTC only) - * Used when system answer already happened - */ + /** Answer incoming call (WebRTC only) Used when system answer already happened */ public void answerCallWhenReady() { Log.d(TAG, "answerCallWhenReady"); @@ -186,28 +182,26 @@ public class CallViewModel extends AndroidViewModel { // Create one-time observer LiveData localTrack = callCoordinator.getLocalVideoTrack(); - answerCallObserver = new Observer() { - @Override - public void onChanged(VideoTrack videoTrack) { - if (videoTrack != null) { - // Media is ready, remove observer - localTrack.removeObserver(this); - answerCallObserver = null; + answerCallObserver = + new Observer() { + @Override + public void onChanged(VideoTrack videoTrack) { + if (videoTrack != null) { + // Media is ready, remove observer + localTrack.removeObserver(this); + answerCallObserver = null; - Log.d(TAG, "Local video ready, answering call (WebRTC)"); + Log.d(TAG, "Local video ready, answering call (WebRTC)"); - callCoordinator.answerWebRTC(); - } - } - }; + callCoordinator.answerWebRTC(); + } + } + }; localTrack.observeForever(answerCallObserver); } - /** - * Start outgoing call with media capture - * Called by Activity for outgoing calls - */ + /** Start outgoing call with media capture Called by Activity for outgoing calls */ public void startOutgoingCallWhenReady() { Log.d(TAG, "startOutgoingCallWhenReady"); @@ -226,20 +220,21 @@ public class CallViewModel extends AndroidViewModel { Log.d(TAG, "Media already ready, starting call immediately"); callCoordinator.startOutgoingCall(); } else { - startOutgoingCallObserver = new Observer() { - @Override - public void onChanged(VideoTrack videoTrack) { - if (videoTrack != null) { - // Media is ready, remove observer - localTrack.removeObserver(this); - startOutgoingCallObserver = null; + startOutgoingCallObserver = + new Observer() { + @Override + public void onChanged(VideoTrack videoTrack) { + if (videoTrack != null) { + // Media is ready, remove observer + localTrack.removeObserver(this); + startOutgoingCallObserver = null; - Log.d(TAG, "Local video ready, starting outgoing call"); + Log.d(TAG, "Local video ready, starting outgoing call"); - callCoordinator.startOutgoingCall(); - } - } - }; + callCoordinator.startOutgoingCall(); + } + } + }; localTrack.observeForever(startOutgoingCallObserver); } @@ -405,7 +400,6 @@ public class CallViewModel extends AndroidViewModel { return availableAudioEndpoints; } - // Notification Action Handlers public void handleNotificationAnswer() { diff --git a/src/main/java/org/thoughtcrime/securesms/calls/MediaStreamManager.java b/src/main/java/org/thoughtcrime/securesms/calls/MediaStreamManager.java index dbc965aa1..4ec94252d 100644 --- a/src/main/java/org/thoughtcrime/securesms/calls/MediaStreamManager.java +++ b/src/main/java/org/thoughtcrime/securesms/calls/MediaStreamManager.java @@ -2,10 +2,8 @@ package org.thoughtcrime.securesms.calls; import android.content.Context; import android.util.Log; - import androidx.annotation.NonNull; import androidx.annotation.Nullable; - import org.thoughtcrime.securesms.EglUtils; import org.webrtc.AudioSource; import org.webrtc.AudioTrack; @@ -19,7 +17,6 @@ import org.webrtc.VideoCapturer; import org.webrtc.VideoSource; import org.webrtc.VideoTrack; - public class MediaStreamManager { private static final String TAG = CallUtil.class.getSimpleName(); @@ -37,6 +34,7 @@ public class MediaStreamManager { public interface Callback { void onMediaStreamReady(MediaStream stream); + void onError(String error); } @@ -46,9 +44,7 @@ public class MediaStreamManager { this.peerConnectionFactory = peerConnectionFactory; } - /** - * Create media stream with audio and optionally video - */ + /** Create media stream with audio and optionally video */ public void createMediaStream(Callback callback) { try { MediaStream mediaStream = peerConnectionFactory.createLocalMediaStream(STREAM_ID); @@ -72,10 +68,8 @@ public class MediaStreamManager { mediaStream.addTrack(videoTrack); // Start capturing - surfaceTextureHelper = SurfaceTextureHelper.create( - "CaptureThread", - EglUtils.getEglBase().getEglBaseContext() - ); + surfaceTextureHelper = + SurfaceTextureHelper.create("CaptureThread", EglUtils.getEglBase().getEglBaseContext()); videoCapturer.initialize(surfaceTextureHelper, context, videoSource.getCapturerObserver()); videoCapturer.startCapture(1280, 720, 30); @@ -121,9 +115,7 @@ public class MediaStreamManager { } } - /** - * Cleanup resources - */ + /** Cleanup resources */ public void dispose() { if (videoCapturer != null) { try { diff --git a/src/main/java/org/thoughtcrime/securesms/connect/DcEventCenter.java b/src/main/java/org/thoughtcrime/securesms/connect/DcEventCenter.java index b02adf2ad..04dcda054 100644 --- a/src/main/java/org/thoughtcrime/securesms/connect/DcEventCenter.java +++ b/src/main/java/org/thoughtcrime/securesms/connect/DcEventCenter.java @@ -3,125 +3,128 @@ package org.thoughtcrime.securesms.connect; import android.content.Context; import android.util.Log; import android.widget.Toast; - import androidx.annotation.NonNull; - import com.b44t.messenger.DcContext; import com.b44t.messenger.DcEvent; - +import java.util.ArrayList; +import java.util.Hashtable; import org.thoughtcrime.securesms.ApplicationContext; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.service.FetchForegroundService; import org.thoughtcrime.securesms.util.Util; -import java.util.ArrayList; -import java.util.Hashtable; - public class DcEventCenter { - private static final String TAG = DcEventCenter.class.getSimpleName(); - private @NonNull final Hashtable> currentAccountObservers = new Hashtable<>(); - private @NonNull final Hashtable> multiAccountObservers = new Hashtable<>(); - private final Object LOCK = new Object(); - private final @NonNull ApplicationContext context; + private static final String TAG = DcEventCenter.class.getSimpleName(); + private @NonNull final Hashtable> currentAccountObservers = + new Hashtable<>(); + private @NonNull final Hashtable> multiAccountObservers = + new Hashtable<>(); + private final Object LOCK = new Object(); + private final @NonNull ApplicationContext context; - public interface DcEventDelegate { - void handleEvent(@NonNull DcEvent event); - default boolean runOnMain() { - return true; + public interface DcEventDelegate { + void handleEvent(@NonNull DcEvent event); + + default boolean runOnMain() { + return true; + } + } + + public DcEventCenter(@NonNull Context context) { + this.context = ApplicationContext.getInstance(context); + } + + public void addObserver(int eventId, @NonNull DcEventDelegate observer) { + addObserver(currentAccountObservers, eventId, observer); + } + + public void addMultiAccountObserver(int eventId, @NonNull DcEventDelegate observer) { + addObserver(multiAccountObservers, eventId, observer); + } + + private void addObserver( + Hashtable> observers, + int eventId, + @NonNull DcEventDelegate observer) { + synchronized (LOCK) { + ArrayList idObservers = observers.get(eventId); + if (idObservers == null) { + observers.put(eventId, (idObservers = new ArrayList<>())); + } + idObservers.add(observer); + } + } + + public void removeObserver(int eventId, DcEventDelegate observer) { + synchronized (LOCK) { + ArrayList idObservers = currentAccountObservers.get(eventId); + if (idObservers != null) { + idObservers.remove(observer); + } + idObservers = multiAccountObservers.get(eventId); + if (idObservers != null) { + idObservers.remove(observer); + } + } + } + + public void removeObservers(DcEventDelegate observer) { + synchronized (LOCK) { + for (Integer eventId : currentAccountObservers.keySet()) { + ArrayList idObservers = currentAccountObservers.get(eventId); + if (idObservers != null) { + idObservers.remove(observer); } - } - - public DcEventCenter(@NonNull Context context) { - this.context = ApplicationContext.getInstance(context); - } - - public void addObserver(int eventId, @NonNull DcEventDelegate observer) { - addObserver(currentAccountObservers, eventId, observer); - } - - public void addMultiAccountObserver(int eventId, @NonNull DcEventDelegate observer) { - addObserver(multiAccountObservers, eventId, observer); - } - - private void addObserver(Hashtable> observers, int eventId, @NonNull DcEventDelegate observer) { - synchronized (LOCK) { - ArrayList idObservers = observers.get(eventId); - if (idObservers == null) { - observers.put(eventId, (idObservers = new ArrayList<>())); - } - idObservers.add(observer); + } + for (Integer eventId : multiAccountObservers.keySet()) { + ArrayList idObservers = multiAccountObservers.get(eventId); + if (idObservers != null) { + idObservers.remove(observer); } + } } + } - public void removeObserver(int eventId, DcEventDelegate observer) { - synchronized (LOCK) { - ArrayList idObservers = currentAccountObservers.get(eventId); - if (idObservers != null) { - idObservers.remove(observer); - } - idObservers = multiAccountObservers.get(eventId); - if (idObservers != null) { - idObservers.remove(observer); - } - } - } - - public void removeObservers(DcEventDelegate observer) { - synchronized (LOCK) { - for(Integer eventId : currentAccountObservers.keySet()) { - ArrayList idObservers = currentAccountObservers.get(eventId); - if (idObservers != null) { - idObservers.remove(observer); - } - } - for(Integer eventId : multiAccountObservers.keySet()) { - ArrayList idObservers = multiAccountObservers.get(eventId); - if (idObservers != null) { - idObservers.remove(observer); - } - } - } - } - - private void sendToMultiAccountObservers(@NonNull DcEvent event) { - sendToObservers(multiAccountObservers, event); - } - - private void sendToCurrentAccountObservers(@NonNull DcEvent event) { - sendToObservers(currentAccountObservers, event); - } - - private void sendToObservers(Hashtable> observers, @NonNull DcEvent event) { - synchronized (LOCK) { - ArrayList idObservers = observers.get(event.getId()); - if (idObservers != null) { - for (DcEventDelegate observer : idObservers) { - // using try/catch blocks as under some circumstances eg. getContext() may return NULL - - // and as this function is used virtually everywhere, also in libs, - // it's not feasible to check all single occurrences. - if(observer.runOnMain()) { - Util.runOnMain(() -> { - try { - observer.handleEvent(event); - } - catch(Exception e) { - Log.e(TAG, "Error calling observer.handleEvent()", e); - } - }); - } else { - Util.runOnBackground(() -> { - try { - observer.handleEvent(event); - } - catch (Exception e) { - Log.e(TAG, "Error calling observer.handleEvent()", e); - } - }); - } - } - } + private void sendToMultiAccountObservers(@NonNull DcEvent event) { + sendToObservers(multiAccountObservers, event); + } + + private void sendToCurrentAccountObservers(@NonNull DcEvent event) { + sendToObservers(currentAccountObservers, event); + } + + private void sendToObservers( + Hashtable> observers, @NonNull DcEvent event) { + synchronized (LOCK) { + ArrayList idObservers = observers.get(event.getId()); + if (idObservers != null) { + for (DcEventDelegate observer : idObservers) { + // using try/catch blocks as under some circumstances eg. getContext() may return NULL - + // and as this function is used virtually everywhere, also in libs, + // it's not feasible to check all single occurrences. + if (observer.runOnMain()) { + Util.runOnMain( + () -> { + try { + observer.handleEvent(event); + } catch (Exception e) { + Log.e(TAG, "Error calling observer.handleEvent()", e); + } + }); + } else { + Util.runOnBackground( + () -> { + try { + observer.handleEvent(event); + } catch (Exception e) { + Log.e(TAG, "Error calling observer.handleEvent()", e); + } + }); + } } + } } + } private final Object lastErrorLock = new Object(); private boolean showNextErrorAsToast = true; @@ -148,24 +151,26 @@ public class DcEventCenter { } // show error to user - Util.runOnMain(() -> { - if (showAsToast) { - String toastString = null; + Util.runOnMain( + () -> { + if (showAsToast) { + String toastString = null; - if (event == DcContext.DC_EVENT_ERROR_SELF_NOT_IN_GROUP) { - toastString = context.getString(R.string.group_self_not_in_group); - } + if (event == DcContext.DC_EVENT_ERROR_SELF_NOT_IN_GROUP) { + toastString = context.getString(R.string.group_self_not_in_group); + } - ForegroundDetector foregroundDetector = ForegroundDetector.getInstance(); - if (toastString != null && (foregroundDetector == null || foregroundDetector.isForeground())) { - Toast.makeText(context, toastString, Toast.LENGTH_LONG).show(); - } - } - }); + ForegroundDetector foregroundDetector = ForegroundDetector.getInstance(); + if (toastString != null + && (foregroundDetector == null || foregroundDetector.isForeground())) { + Toast.makeText(context, toastString, Toast.LENGTH_LONG).show(); + } + } + }); } public void handleLogging(@NonNull DcEvent event) { - final String logPrefix = "[accId="+event.getAccountId()+ "] "; + final String logPrefix = "[accId=" + event.getAccountId() + "] "; switch (event.getId()) { case DcContext.DC_EVENT_INFO: Log.i("DeltaChat", logPrefix + event.getData2Str()); @@ -189,15 +194,19 @@ public class DcEventCenter { switch (id) { case DcContext.DC_EVENT_INCOMING_MSG: - DcHelper.getNotificationCenter(context).notifyMessage(accountId, event.getData1Int(), event.getData2Int()); + DcHelper.getNotificationCenter(context) + .notifyMessage(accountId, event.getData1Int(), event.getData2Int()); break; case DcContext.DC_EVENT_INCOMING_REACTION: - DcHelper.getNotificationCenter(context).notifyReaction(accountId, event.getData1Int(), event.getData2Int(), event.getData2Str()); + DcHelper.getNotificationCenter(context) + .notifyReaction( + accountId, event.getData1Int(), event.getData2Int(), event.getData2Str()); break; case DcContext.DC_EVENT_INCOMING_WEBXDC_NOTIFY: - DcHelper.getNotificationCenter(context).notifyWebxdc(accountId, event.getData1Int(), event.getData2Int(), event.getData2Str()); + DcHelper.getNotificationCenter(context) + .notifyWebxdc(accountId, event.getData1Int(), event.getData2Int(), event.getData2Str()); break; case DcContext.DC_EVENT_MSGS_NOTICED: @@ -205,7 +214,8 @@ public class DcEventCenter { break; case DcContext.DC_EVENT_MSG_DELETED: - DcHelper.getNotificationCenter(context).removeNotification(accountId, event.getData1Int(), event.getData2Int()); + DcHelper.getNotificationCenter(context) + .removeNotification(accountId, event.getData1Int(), event.getData2Int()); break; case DcContext.DC_EVENT_ACCOUNTS_BACKGROUND_FETCH_DONE: diff --git a/src/main/java/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/main/java/org/thoughtcrime/securesms/notifications/NotificationCenter.java index 9fddf6b46..be07fe84d 100644 --- a/src/main/java/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/main/java/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -17,9 +17,7 @@ import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.text.TextUtils; -import android.util.Base64; import android.util.Log; - import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.WorkerThread; @@ -27,19 +25,23 @@ import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import androidx.core.app.RemoteInput; import androidx.core.app.TaskStackBuilder; - import com.b44t.messenger.DcChat; import com.b44t.messenger.DcContact; import com.b44t.messenger.DcContext; import com.b44t.messenger.DcMsg; import com.bumptech.glide.load.engine.DiskCacheStrategy; - +import java.math.BigInteger; +import java.security.MessageDigest; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; import org.json.JSONObject; import org.thoughtcrime.securesms.ApplicationContext; import org.thoughtcrime.securesms.ConversationActivity; import org.thoughtcrime.securesms.ConversationListActivity; import org.thoughtcrime.securesms.R; -import org.thoughtcrime.securesms.calls.CallActivity; import org.thoughtcrime.securesms.contacts.avatars.ContactPhoto; import org.thoughtcrime.securesms.mms.GlideApp; import org.thoughtcrime.securesms.preferences.widgets.NotificationPrivacyPreference; @@ -51,818 +53,906 @@ import org.thoughtcrime.securesms.util.Pair; import org.thoughtcrime.securesms.util.Prefs; import org.thoughtcrime.securesms.util.Util; -import java.io.UnsupportedEncodingException; -import java.math.BigInteger; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import chat.delta.rpc.RpcException; - public class NotificationCenter { - private static final String TAG = NotificationCenter.class.getSimpleName(); - @NonNull private final ApplicationContext context; - private volatile ChatData visibleChat = null; - private volatile Pair visibleWebxdc = null; - private volatile long lastAudibleNotification = 0; - private static final long MIN_AUDIBLE_PERIOD_MILLIS = TimeUnit.SECONDS.toMillis(2); + private static final String TAG = NotificationCenter.class.getSimpleName(); + @NonNull private final ApplicationContext context; + private volatile ChatData visibleChat = null; + private volatile Pair visibleWebxdc = null; + private volatile long lastAudibleNotification = 0; + private static final long MIN_AUDIBLE_PERIOD_MILLIS = TimeUnit.SECONDS.toMillis(2); - // Map, contains the last lines of each chat for each account - private final HashMap>> inboxes = new HashMap<>(); + // Map, contains the last lines of each chat for each account + private final HashMap>> inboxes = + new HashMap<>(); - public NotificationCenter(Context context) { - this.context = ApplicationContext.getInstance(context); + public NotificationCenter(Context context) { + this.context = ApplicationContext.getInstance(context); + } + + private @Nullable Uri effectiveSound( + ChatData chatData) { // chatData=null: return app-global setting + if (chatData == null) { + chatData = new ChatData(0, 0); } + @Nullable + Uri chatRingtone = Prefs.getChatRingtone(context, chatData.accountId, chatData.chatId); + if (chatRingtone != null) { + return chatRingtone; + } else { + @NonNull Uri appDefaultRingtone = Prefs.getNotificationRingtone(context); + if (!TextUtils.isEmpty(appDefaultRingtone.toString())) { + return appDefaultRingtone; + } + } + return null; + } - private @Nullable Uri effectiveSound(ChatData chatData) { // chatData=null: return app-global setting - if (chatData == null) { - chatData = new ChatData(0, 0); + private boolean effectiveVibrate(ChatData chatData) { // chatData=null: return app-global setting + if (chatData == null) { + chatData = new ChatData(0, 0); + } + Prefs.VibrateState vibrate = Prefs.getChatVibrate(context, chatData.accountId, chatData.chatId); + if (vibrate == Prefs.VibrateState.ENABLED) { + return true; + } else if (vibrate == Prefs.VibrateState.DISABLED) { + return false; + } + return Prefs.isNotificationVibrateEnabled(context); + } + + private boolean requiresIndependentChannel(ChatData chatData) { + if (chatData == null) { + chatData = new ChatData(0, 0); + } + return Prefs.getChatRingtone(context, chatData.accountId, chatData.chatId) != null + || Prefs.getChatVibrate(context, chatData.accountId, chatData.chatId) + != Prefs.VibrateState.DEFAULT; + } + + private int getLedArgb(String ledColor) { + int argb; + try { + argb = Color.parseColor(ledColor); + } catch (Exception e) { + argb = Color.rgb(0xFF, 0xFF, 0xFF); + } + return argb; + } + + private PendingIntent getOpenChatlistIntent(int accountId) { + Intent intent = new Intent(context, ConversationListActivity.class); + intent.putExtra(ConversationListActivity.ACCOUNT_ID_EXTRA, accountId); + intent.putExtra(ConversationListActivity.CLEAR_NOTIFICATIONS, true); + intent.setData(Uri.parse("custom://" + accountId)); + return PendingIntent.getActivity( + context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | IntentUtils.FLAG_MUTABLE()); + } + + private PendingIntent getOpenChatIntent(ChatData chatData) { + Intent intent = new Intent(context, ConversationActivity.class); + intent.putExtra(ConversationActivity.ACCOUNT_ID_EXTRA, chatData.accountId); + intent.putExtra(ConversationActivity.CHAT_ID_EXTRA, chatData.chatId); + intent.setData(Uri.parse("custom://" + chatData.accountId + "." + chatData.chatId)); + return TaskStackBuilder.create(context) + .addNextIntentWithParentStack(intent) + .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT | IntentUtils.FLAG_MUTABLE()); + } + + private PendingIntent getRemoteReplyIntent(ChatData chatData, int msgId) { + Intent intent = new Intent(RemoteReplyReceiver.REPLY_ACTION); + intent.setClass(context, RemoteReplyReceiver.class); + intent.setData(Uri.parse("custom://" + chatData.accountId + "." + chatData.chatId)); + intent.putExtra(RemoteReplyReceiver.ACCOUNT_ID_EXTRA, chatData.accountId); + intent.putExtra(RemoteReplyReceiver.CHAT_ID_EXTRA, chatData.chatId); + intent.putExtra(RemoteReplyReceiver.MSG_ID_EXTRA, msgId); + intent.setPackage(context.getPackageName()); + return PendingIntent.getBroadcast( + context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | IntentUtils.FLAG_MUTABLE()); + } + + private PendingIntent getMarkAsReadIntent(ChatData chatData, int msgId, boolean markNoticed) { + Intent intent = + new Intent( + markNoticed ? MarkReadReceiver.MARK_NOTICED_ACTION : MarkReadReceiver.CANCEL_ACTION); + intent.setClass(context, MarkReadReceiver.class); + intent.setData(Uri.parse("custom://" + chatData.accountId + "." + chatData.chatId)); + intent.putExtra(MarkReadReceiver.ACCOUNT_ID_EXTRA, chatData.accountId); + intent.putExtra(MarkReadReceiver.CHAT_ID_EXTRA, chatData.chatId); + intent.putExtra(MarkReadReceiver.MSG_ID_EXTRA, msgId); + intent.setPackage(context.getPackageName()); + return PendingIntent.getBroadcast( + context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | IntentUtils.FLAG_MUTABLE()); + } + + // Groups and Notification channel groups + // -------------------------------------------------------------------------------------------- + + // this is just to further organize the appearance of channels in the settings UI + private static final String CH_GRP_MSG = "chgrp_msg"; + + // this is to group together notifications as such, maybe including a summary, + // see https://developer.android.com/training/notify-user/group.html + private static final String GRP_MSG = "grp_msg"; + + // Notification IDs + // -------------------------------------------------------------------------------------------- + + public static final int ID_PERMANENT = 1; + public static final int ID_MSG_SUMMARY = 2; + public static final int ID_GENERIC = 3; + public static final int ID_FETCH = 4; + public static final int ID_MSG_OFFSET = + 0; // msgId is added - as msgId start at 10, there are no conflicts with lower numbers + + // Notification channels + // -------------------------------------------------------------------------------------------- + + // Overview: + // - since SDK 26 (Oreo), a NotificationChannel is a MUST for notifications + // - NotificationChannels are defined by a channelId + // and its user-editable settings have a higher precedence as the Notification.Builder setting + // - once created, NotificationChannels cannot be modified programmatically + // - NotificationChannels can be deleted, however, on re-creation with the same id, + // it becomes un-deleted with the old user-defined settings + // + // How we use Notification channel: + // - We include the delta-chat-notifications settings into the name of the channelId + // - The chatId is included only, if there are separate sound- or vibration-settings for a chat + // - This way, we have stable and few channelIds and the user + // can edit the notifications in Delta Chat as well as in the system + + // channelIds: CH_MSG_* are used here, the other ones from outside (defined here to have some + // overview) + public static final String CH_MSG_PREFIX = "ch_msg"; + public static final String CH_MSG_VERSION = "5"; + public static final String CH_PERMANENT = "dc_fg_notification_ch"; + public static final String CH_GENERIC = "ch_generic"; + public static final String CH_CALLS_PREFIX = "call_chan"; + + private boolean notificationChannelsSupported() { + return Build.VERSION.SDK_INT >= 26; + } + + // full name is "ch_msgV_HASH" or "ch_msgV_HASH.ACCOUNTID.CHATID" + private String computeChannelId( + String ledColor, boolean vibrate, @Nullable Uri ringtone, ChatData chatData) { + String channelId = CH_MSG_PREFIX; + try { + MessageDigest md = MessageDigest.getInstance("SHA-256"); + md.update(ledColor.getBytes()); + md.update(vibrate ? (byte) 1 : (byte) 0); + md.update((ringtone != null ? ringtone.toString() : "").getBytes()); + String hash = String.format("%X", new BigInteger(1, md.digest())).substring(0, 16); + + channelId = CH_MSG_PREFIX + CH_MSG_VERSION + "_" + hash; + if (chatData != null) { + channelId += String.format(".%d.%d", chatData.accountId, chatData.chatId); + } + + } catch (Exception e) { + Log.e(TAG, e.toString()); + } + return channelId; + } + + // return ChatData(ACCOUNTID, CHATID) from "ch_msgV_HASH.ACCOUNTID.CHATID" or null + private ChatData parseNotificationChannelChat(String channelId) { + try { + int point = channelId.lastIndexOf("."); + if (point > 0) { + int chatId = Integer.parseInt(channelId.substring(point + 1)); + channelId = channelId.substring(0, point); + point = channelId.lastIndexOf("."); + if (point > 0) { + int accountId = Integer.parseInt(channelId.substring(point + 1)); + return new ChatData(accountId, chatId); } - @Nullable Uri chatRingtone = Prefs.getChatRingtone(context, chatData.accountId, chatData.chatId); - if (chatRingtone!=null) { - return chatRingtone; - } else { - @NonNull Uri appDefaultRingtone = Prefs.getNotificationRingtone(context); - if (!TextUtils.isEmpty(appDefaultRingtone.toString())) { - return appDefaultRingtone; + } + } catch (Exception ignored) { + } + return null; + } + + private String getNotificationChannelGroup(NotificationManagerCompat notificationManager) { + if (notificationChannelsSupported() + && notificationManager.getNotificationChannelGroup(CH_GRP_MSG) == null) { + NotificationChannelGroup chGrp = + new NotificationChannelGroup(CH_GRP_MSG, context.getString(R.string.pref_chats)); + notificationManager.createNotificationChannelGroup(chGrp); + } + return CH_GRP_MSG; + } + + private String getNotificationChannel( + NotificationManagerCompat notificationManager, ChatData chatData, DcChat dcChat) { + String channelId = CH_MSG_PREFIX; + + if (notificationChannelsSupported()) { + try { + // get all values we'll use as settings for the NotificationChannel + String ledColor = Prefs.getNotificationLedColor(context); + boolean defaultVibrate = effectiveVibrate(chatData); + @Nullable Uri ringtone = effectiveSound(chatData); + boolean isIndependent = requiresIndependentChannel(chatData); + + // get channel id from these settings + channelId = + computeChannelId(ledColor, defaultVibrate, ringtone, isIndependent ? chatData : null); + + // user-visible name of the channel - + // we just use the name of the chat or "Default" + // (the name is shown in the context of the group "Chats" - that should be enough context) + String name = context.getString(R.string.def); + if (isIndependent) { + name = dcChat.getName(); + } + + // check if there is already a channel with the given name + List channels = notificationManager.getNotificationChannels(); + boolean channelExists = false; + for (int i = 0; i < channels.size(); i++) { + String currChannelId = channels.get(i).getId(); + if (currChannelId.startsWith(CH_MSG_PREFIX)) { + // this is one of the message channels handled here ... + if (currChannelId.equals(channelId)) { + // ... this is the actually required channel, fine :) + // update the name to reflect localize changes and chat renames + channelExists = true; + channels.get(i).setName(name); + } else { + // ... another message channel, delete if it is not in use. + ChatData currChat = parseNotificationChannelChat(currChannelId); + if (!currChannelId.equals( + computeChannelId( + ledColor, effectiveVibrate(currChat), effectiveSound(currChat), currChat))) { + notificationManager.deleteNotificationChannel(currChannelId); + } } - } - return null; - } - - private boolean effectiveVibrate(ChatData chatData) { // chatData=null: return app-global setting - if (chatData == null) { - chatData = new ChatData(0, 0); - } - Prefs.VibrateState vibrate = Prefs.getChatVibrate(context, chatData.accountId, chatData.chatId); - if (vibrate == Prefs.VibrateState.ENABLED) { - return true; - } else if (vibrate == Prefs.VibrateState.DISABLED) { - return false; - } - return Prefs.isNotificationVibrateEnabled(context); - } - - private boolean requiresIndependentChannel(ChatData chatData) { - if (chatData == null) { - chatData = new ChatData(0, 0); - } - return Prefs.getChatRingtone(context, chatData.accountId, chatData.chatId) != null - || Prefs.getChatVibrate(context, chatData.accountId, chatData.chatId) != Prefs.VibrateState.DEFAULT; - } - - private int getLedArgb(String ledColor) { - int argb; - try { - argb = Color.parseColor(ledColor); - } - catch (Exception e) { - argb = Color.rgb(0xFF, 0xFF, 0xFF); - } - return argb; - } - - private PendingIntent getOpenChatlistIntent(int accountId) { - Intent intent = new Intent(context, ConversationListActivity.class); - intent.putExtra(ConversationListActivity.ACCOUNT_ID_EXTRA, accountId); - intent.putExtra(ConversationListActivity.CLEAR_NOTIFICATIONS, true); - intent.setData(Uri.parse("custom://"+accountId)); - return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | IntentUtils.FLAG_MUTABLE()); - } - - private PendingIntent getOpenChatIntent(ChatData chatData) { - Intent intent = new Intent(context, ConversationActivity.class); - intent.putExtra(ConversationActivity.ACCOUNT_ID_EXTRA, chatData.accountId); - intent.putExtra(ConversationActivity.CHAT_ID_EXTRA, chatData.chatId); - intent.setData(Uri.parse("custom://"+chatData.accountId+"."+chatData.chatId)); - return TaskStackBuilder.create(context) - .addNextIntentWithParentStack(intent) - .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT | IntentUtils.FLAG_MUTABLE()); - } - - private PendingIntent getRemoteReplyIntent(ChatData chatData, int msgId) { - Intent intent = new Intent(RemoteReplyReceiver.REPLY_ACTION); - intent.setClass(context, RemoteReplyReceiver.class); - intent.setData(Uri.parse("custom://"+chatData.accountId+"."+chatData.chatId)); - intent.putExtra(RemoteReplyReceiver.ACCOUNT_ID_EXTRA, chatData.accountId); - intent.putExtra(RemoteReplyReceiver.CHAT_ID_EXTRA, chatData.chatId); - intent.putExtra(RemoteReplyReceiver.MSG_ID_EXTRA, msgId); - intent.setPackage(context.getPackageName()); - return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | IntentUtils.FLAG_MUTABLE()); - } - - private PendingIntent getMarkAsReadIntent(ChatData chatData, int msgId, boolean markNoticed) { - Intent intent = new Intent(markNoticed? MarkReadReceiver.MARK_NOTICED_ACTION : MarkReadReceiver.CANCEL_ACTION); - intent.setClass(context, MarkReadReceiver.class); - intent.setData(Uri.parse("custom://"+chatData.accountId+"."+chatData.chatId)); - intent.putExtra(MarkReadReceiver.ACCOUNT_ID_EXTRA, chatData.accountId); - intent.putExtra(MarkReadReceiver.CHAT_ID_EXTRA, chatData.chatId); - intent.putExtra(MarkReadReceiver.MSG_ID_EXTRA, msgId); - intent.setPackage(context.getPackageName()); - return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | IntentUtils.FLAG_MUTABLE()); - } - - // Groups and Notification channel groups - // -------------------------------------------------------------------------------------------- - - // this is just to further organize the appearance of channels in the settings UI - private static final String CH_GRP_MSG = "chgrp_msg"; - - // this is to group together notifications as such, maybe including a summary, - // see https://developer.android.com/training/notify-user/group.html - private static final String GRP_MSG = "grp_msg"; - - - // Notification IDs - // -------------------------------------------------------------------------------------------- - - public static final int ID_PERMANENT = 1; - public static final int ID_MSG_SUMMARY = 2; - public static final int ID_GENERIC = 3; - public static final int ID_FETCH = 4; - public static final int ID_MSG_OFFSET = 0; // msgId is added - as msgId start at 10, there are no conflicts with lower numbers - - - // Notification channels - // -------------------------------------------------------------------------------------------- - - // Overview: - // - since SDK 26 (Oreo), a NotificationChannel is a MUST for notifications - // - NotificationChannels are defined by a channelId - // and its user-editable settings have a higher precedence as the Notification.Builder setting - // - once created, NotificationChannels cannot be modified programmatically - // - NotificationChannels can be deleted, however, on re-creation with the same id, - // it becomes un-deleted with the old user-defined settings - // - // How we use Notification channel: - // - We include the delta-chat-notifications settings into the name of the channelId - // - The chatId is included only, if there are separate sound- or vibration-settings for a chat - // - This way, we have stable and few channelIds and the user - // can edit the notifications in Delta Chat as well as in the system - - // channelIds: CH_MSG_* are used here, the other ones from outside (defined here to have some overview) - public static final String CH_MSG_PREFIX = "ch_msg"; - public static final String CH_MSG_VERSION = "5"; - public static final String CH_PERMANENT = "dc_fg_notification_ch"; - public static final String CH_GENERIC = "ch_generic"; - public static final String CH_CALLS_PREFIX = "call_chan"; - - private boolean notificationChannelsSupported() { - return Build.VERSION.SDK_INT >= 26; - } - - // full name is "ch_msgV_HASH" or "ch_msgV_HASH.ACCOUNTID.CHATID" - private String computeChannelId(String ledColor, boolean vibrate, @Nullable Uri ringtone, ChatData chatData) { - String channelId = CH_MSG_PREFIX; - try { - MessageDigest md = MessageDigest.getInstance("SHA-256"); - md.update(ledColor.getBytes()); - md.update(vibrate ? (byte) 1 : (byte) 0); - md.update((ringtone != null ? ringtone.toString() : "").getBytes()); - String hash = String.format("%X", new BigInteger(1, md.digest())).substring(0, 16); - - channelId = CH_MSG_PREFIX + CH_MSG_VERSION + "_" + hash; - if (chatData != null) { - channelId += String.format(".%d.%d", chatData.accountId, chatData.chatId); - } - - } catch(Exception e) { - Log.e(TAG, e.toString()); - } - return channelId; - } - - // return ChatData(ACCOUNTID, CHATID) from "ch_msgV_HASH.ACCOUNTID.CHATID" or null - private ChatData parseNotificationChannelChat(String channelId) { - try { - int point = channelId.lastIndexOf("."); - if (point>0) { - int chatId = Integer.parseInt(channelId.substring(point + 1)); - channelId = channelId.substring(0, point); - point = channelId.lastIndexOf("."); - if (point>0) { - int accountId = Integer.parseInt(channelId.substring(point + 1)); - return new ChatData(accountId, chatId); - } - } - } catch(Exception ignored) { } - return null; - } - - private String getNotificationChannelGroup(NotificationManagerCompat notificationManager) { - if (notificationChannelsSupported() && notificationManager.getNotificationChannelGroup(CH_GRP_MSG) == null) { - NotificationChannelGroup chGrp = new NotificationChannelGroup(CH_GRP_MSG, context.getString(R.string.pref_chats)); - notificationManager.createNotificationChannelGroup(chGrp); - } - return CH_GRP_MSG; - } - - private String getNotificationChannel(NotificationManagerCompat notificationManager, ChatData chatData, DcChat dcChat) { - String channelId = CH_MSG_PREFIX; - - if (notificationChannelsSupported()) { - try { - // get all values we'll use as settings for the NotificationChannel - String ledColor = Prefs.getNotificationLedColor(context); - boolean defaultVibrate = effectiveVibrate(chatData); - @Nullable Uri ringtone = effectiveSound(chatData); - boolean isIndependent = requiresIndependentChannel(chatData); - - // get channel id from these settings - channelId = computeChannelId(ledColor, defaultVibrate, ringtone, isIndependent? chatData : null); - - // user-visible name of the channel - - // we just use the name of the chat or "Default" - // (the name is shown in the context of the group "Chats" - that should be enough context) - String name = context.getString(R.string.def); - if (isIndependent) { - name = dcChat.getName(); - } - - // check if there is already a channel with the given name - List channels = notificationManager.getNotificationChannels(); - boolean channelExists = false; - for (int i = 0; i < channels.size(); i++) { - String currChannelId = channels.get(i).getId(); - if (currChannelId.startsWith(CH_MSG_PREFIX)) { - // this is one of the message channels handled here ... - if (currChannelId.equals(channelId)) { - // ... this is the actually required channel, fine :) - // update the name to reflect localize changes and chat renames - channelExists = true; - channels.get(i).setName(name); - } else { - // ... another message channel, delete if it is not in use. - ChatData currChat = parseNotificationChannelChat(currChannelId); - if (!currChannelId.equals(computeChannelId(ledColor, effectiveVibrate(currChat), effectiveSound(currChat), currChat))) { - notificationManager.deleteNotificationChannel(currChannelId); - } - } - } - } - - // create a channel with the given settings; - // we cannot change the settings, however, this is handled by using different values for chId - if(!channelExists) { - NotificationChannel channel = new NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_HIGH); - channel.setDescription("Informs about new messages."); - channel.setGroup(getNotificationChannelGroup(notificationManager)); - channel.enableVibration(defaultVibrate); - channel.setShowBadge(true); - - if (!ledColor.equals("none")) { - channel.enableLights(true); - channel.setLightColor(getLedArgb(ledColor)); - } else { - channel.enableLights(false); - } - - if (ringtone != null && !TextUtils.isEmpty(ringtone.toString())) { - channel.setSound(ringtone, - new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN) - .setUsage(AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT) - .build()); - } else { - channel.setSound(null, null); - } - - notificationManager.createNotificationChannel(channel); - } - } - catch(Exception e) { - Log.e(TAG, "Error in getNotificationChannel()", e); - } - } - - return channelId; - } - - public String getCallNotificationChannel(NotificationManagerCompat notificationManager, ChatData chatData, String name) { - String channelId = CH_CALLS_PREFIX + "-" + chatData.accountId + "-"+ chatData.chatId; - - if (notificationChannelsSupported()) { - try { - name = "(calls) " + name; - - // check if there is already a channel with the given name - List channels = notificationManager.getNotificationChannels(); - boolean channelExists = false; - for (int i = 0; i < channels.size(); i++) { - String currChannelId = channels.get(i).getId(); - if (currChannelId.startsWith(CH_CALLS_PREFIX)) { - // this is one of the calls channels handled here ... - if (currChannelId.equals(channelId)) { - // ... this is the actually required channel, fine :) - // update the name to reflect localize changes and chat renames - channelExists = true; - channels.get(i).setName(name); - } - } - } - - // create the channel - if(!channelExists) { - NotificationChannel channel = new NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_MAX); - channel.setDescription("Informs about incoming calls."); - channel.setShowBadge(true); - - Uri ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); - channel.setSound(ringtone, new AudioAttributes.Builder() - .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE) - .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) - .build()); - notificationManager.createNotificationChannel(channel); - } - } catch(Exception e) { - Log.e(TAG, "Error in getCallNotificationChannel()", e); - } - } - - return channelId; - } - - - // add notifications & co. - // -------------------------------------------------------------------------------------------- - - public void notifyMessage(int accountId, int chatId, int msgId) { - Util.runOnAnyBackgroundThread(() -> { - DcContext dcContext = context.getDcAccounts().getAccount(accountId); - DcChat dcChat = dcContext.getChat(chatId); - - DcMsg dcMsg = dcContext.getMsg(msgId); - NotificationPrivacyPreference privacy = Prefs.getNotificationPrivacy(context); - - String shortLine = privacy.isDisplayMessage()? dcMsg.getSummarytext(2000) : context.getString(R.string.notify_new_message); - if (dcChat.isMultiUser() && privacy.isDisplayContact()) { - shortLine = dcMsg.getSenderName(dcContext.getContact(dcMsg.getFromId())) + ": " + shortLine; - } - String tickerLine = shortLine; - if (!dcChat.isMultiUser() && privacy.isDisplayContact()) { - tickerLine = dcMsg.getSenderName(dcContext.getContact(dcMsg.getFromId())) + ": " + tickerLine; - - if (dcMsg.getOverrideSenderName() != null) { - // There is an "overridden" display name on the message, so, we need to prepend the display name to the message, - // i.e. set the shortLine to be the same as the tickerLine. - shortLine = tickerLine; } } - DcMsg quotedMsg = dcMsg.getQuotedMsg(); - boolean isMention = dcChat.isMultiUser() && quotedMsg != null && quotedMsg.isOutgoing(); + // create a channel with the given settings; + // we cannot change the settings, however, this is handled by using different values for + // chId + if (!channelExists) { + NotificationChannel channel = + new NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_HIGH); + channel.setDescription("Informs about new messages."); + channel.setGroup(getNotificationChannelGroup(notificationManager)); + channel.enableVibration(defaultVibrate); + channel.setShowBadge(true); - maybeAddNotification(accountId, dcChat, msgId, shortLine, tickerLine, true, isMention); - }); + if (!ledColor.equals("none")) { + channel.enableLights(true); + channel.setLightColor(getLedArgb(ledColor)); + } else { + channel.enableLights(false); + } + + if (ringtone != null && !TextUtils.isEmpty(ringtone.toString())) { + channel.setSound( + ringtone, + new AudioAttributes.Builder() + .setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN) + .setUsage(AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT) + .build()); + } else { + channel.setSound(null, null); + } + + notificationManager.createNotificationChannel(channel); + } + } catch (Exception e) { + Log.e(TAG, "Error in getNotificationChannel()", e); + } } - public void notifyReaction(int accountId, int contactId, int msgId, String reaction) { - Util.runOnAnyBackgroundThread(() -> { - DcContext dcContext = context.getDcAccounts().getAccount(accountId); - DcMsg dcMsg = dcContext.getMsg(msgId); + return channelId; + } - NotificationPrivacyPreference privacy = Prefs.getNotificationPrivacy(context); - if (!privacy.isDisplayContact() || !privacy.isDisplayMessage()) { - return; // showing "New Message" is wrong and showing "New Reaction" is already content. just do nothing. - } + public String getCallNotificationChannel( + NotificationManagerCompat notificationManager, ChatData chatData, String name) { + String channelId = CH_CALLS_PREFIX + "-" + chatData.accountId + "-" + chatData.chatId; - DcContact sender = dcContext.getContact(contactId); - String shortLine = context.getString(R.string.reaction_by_other, sender.getDisplayName(), reaction, dcMsg.getSummarytext(2000)); - DcChat dcChat = dcContext.getChat(dcMsg.getChatId()); - maybeAddNotification(accountId, dcChat, msgId, shortLine, shortLine, false, dcChat.isMultiUser()); - }); - } - - public void notifyWebxdc(int accountId, int contactId, int msgId, String text) { - Util.runOnAnyBackgroundThread(() -> { - NotificationPrivacyPreference privacy = Prefs.getNotificationPrivacy(context); - if (!privacy.isDisplayContact() || !privacy.isDisplayMessage()) { - return; // showing "New Message" is wrong, just do nothing. - } - - DcContext dcContext = context.getDcAccounts().getAccount(accountId); - DcMsg dcMsg = dcContext.getMsg(msgId); - DcMsg parentMsg; - if(dcMsg.getType() == DcMsg.DC_MSG_WEBXDC) { - parentMsg = dcMsg; - } else { // info message, get parent xdc - parentMsg = dcMsg.getParent() != null? dcMsg.getParent() : dcMsg; - } - - if (Util.equals(visibleWebxdc, new Pair<>(accountId, parentMsg.getId()))) { - return; // do not notify if the app is already open - } - - JSONObject info = parentMsg.getWebxdcInfo(); - final String name = JsonUtils.optString(info, "name"); - String shortLine = name.isEmpty()? text : (name + ": " + text); - DcChat dcChat = dcContext.getChat(dcMsg.getChatId()); - maybeAddNotification(accountId, dcChat, msgId, shortLine, shortLine, false, dcChat.isMultiUser()); - }); - } - - @WorkerThread - private void maybeAddNotification(int accountId, DcChat dcChat, int msgId, String shortLine, String tickerLine, boolean playInChatSound, boolean isMention) { - DcContext dcContext = ApplicationContext.getDcAccounts().getAccount(accountId); - int chatId = dcChat.getId(); - ChatData chatData = new ChatData(accountId, chatId); - isMention = isMention && dcContext.isMentionsEnabled(); - - if (dcContext.isMuted() || (!isMention && dcChat.isMuted())) { - return; - } - - NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && !notificationManager.areNotificationsEnabled()) { - return; - } - - if (Util.equals(visibleChat, chatData)) { - if (playInChatSound && Prefs.isInChatNotifications(context)) { - InChatSounds.getInstance(context).playIncomingSound(); - } - return; - } - - NotificationPrivacyPreference privacy = Prefs.getNotificationPrivacy(context); - long now = System.currentTimeMillis(); - boolean signal = (now - lastAudibleNotification) > MIN_AUDIBLE_PERIOD_MILLIS; - if (signal) { - lastAudibleNotification = now; - } - - - // create a basic notification - // even without a name or message displayed, - // it makes sense to use separate notification channels and to open the respective chat directly - - // the user may eg. have chosen a different sound - String notificationChannel = getNotificationChannel(notificationManager, chatData, dcChat); - - LinkedHashMap messagesForInbox = null; - if (privacy.isDisplayContact() && privacy.isDisplayMessage()) { - synchronized (inboxes) { - HashMap> accountInbox = inboxes.get(accountId); - if (accountInbox == null) { - accountInbox = new HashMap<>(); - inboxes.put(accountId, accountInbox); - } - LinkedHashMap messages = accountInbox.get(chatId); - if (messages == null) { - messages = new LinkedHashMap<>(); - accountInbox.put(chatId, messages); - } - messages.put(msgId, shortLine); - messagesForInbox = new LinkedHashMap<>(messages); - } - } - - int cnt = dcContext.getFreshMsgCount(chatId); - buildAndShowChatNotification(accountId, chatId, msgId, dcContext, dcChat, - notificationChannel, shortLine, tickerLine, signal, messagesForInbox, cnt, true); - } - - @WorkerThread - private void buildAndShowChatNotification( - int accountId, - int chatId, - int msgId, - DcContext dcContext, - DcChat dcChat, - String notificationChannel, - String contentText, - String ticker, - boolean signal, - LinkedHashMap messagesForInbox, - int messageCount, - boolean includeSummary) { - try { - NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); - NotificationPrivacyPreference privacy = Prefs.getNotificationPrivacy(context); - ChatData chatData = new ChatData(accountId, chatId); - - // Create basic notification - NotificationCompat.Builder builder = new NotificationCompat.Builder(context, notificationChannel) - .setSmallIcon(R.drawable.icon_notification) - .setColor(context.getResources().getColor(R.color.delta_primary)) - .setPriority(Prefs.getNotificationPriority(context)) - .setCategory(NotificationCompat.CATEGORY_MESSAGE) - .setOnlyAlertOnce(!signal) - .setContentText(contentText) - .setDeleteIntent(getMarkAsReadIntent(chatData, msgId, false)) - .setContentIntent(getOpenChatIntent(chatData)); - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - builder.setGroup(GRP_MSG + "." + accountId); - } - - String accountTag = dcContext.getConfig(CONFIG_PRIVATE_TAG); - if (accountTag.isEmpty() && ApplicationContext.getDcAccounts().getAll().length > 1) { - accountTag = dcContext.getName(); - } - - if (privacy.isDisplayContact()) { - builder.setContentTitle(dcChat.getName()); - if (!TextUtils.isEmpty(accountTag)) { - builder.setSubText(accountTag); - } - } - - if (ticker != null) { - builder.setTicker(ticker); - } - - // Set sound, vibrate, led for systems that do not have notification channels - if (!notificationChannelsSupported()) { - if (signal) { - Uri sound = effectiveSound(chatData); - if (sound != null && !TextUtils.isEmpty(sound.toString())) { - builder.setSound(sound); - } - boolean vibrate = effectiveVibrate(chatData); - if (vibrate) { - builder.setDefaults(Notification.DEFAULT_VIBRATE); - } - } - String ledColor = Prefs.getNotificationLedColor(context); - if (!ledColor.equals("none")) { - builder.setLights(getLedArgb(ledColor), 500, 2000); - } - } - - // Set avatar - if (privacy.isDisplayContact()) { - Bitmap bitmap = getAvatar(dcChat); - if (bitmap != null) { - builder.setLargeIcon(bitmap); - } - } - - // Add buttons that allow some actions without opening Delta Chat. - // If privacy options are enabled, the buttons are not added. - if (privacy.isDisplayContact() && privacy.isDisplayMessage()) { - try { - PendingIntent inNotificationReplyIntent = getRemoteReplyIntent(chatData, msgId); - PendingIntent markReadIntent = getMarkAsReadIntent(chatData, msgId, true); - - NotificationCompat.Action markAsReadAction = new NotificationCompat.Action(R.drawable.check, - context.getString(R.string.mark_as_read_short), - markReadIntent); - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(R.drawable.ic_reply_white_36dp, - context.getString(R.string.notify_reply_button), - inNotificationReplyIntent) - .addRemoteInput(new RemoteInput.Builder(RemoteReplyReceiver.EXTRA_REMOTE_REPLY) - .setLabel(context.getString(R.string.notify_reply_button)).build()) - .build(); - builder.addAction(replyAction); - } - - NotificationCompat.Action wearableReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_reply, - context.getString(R.string.notify_reply_button), - inNotificationReplyIntent) - .addRemoteInput(new RemoteInput.Builder(RemoteReplyReceiver.EXTRA_REMOTE_REPLY) - .setLabel(context.getString(R.string.notify_reply_button)).build()) - .build(); - builder.addAction(markAsReadAction); - builder.extend(new NotificationCompat.WearableExtender().addAction(markAsReadAction).addAction(wearableReplyAction)); - } catch(Exception e) { Log.w(TAG, e); } - } - - // Create inbox style (gets visible if the notification is expanded) - if (privacy.isDisplayContact() && privacy.isDisplayMessage() && messagesForInbox != null) { - try { - NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); - for (String line : messagesForInbox.values()) { - inboxStyle.addLine(line); - } - builder.setStyle(inboxStyle); - } catch(Exception e) { Log.w(TAG, e); } - } - - // Messages count - builder.setContentInfo(String.valueOf(messageCount)); - builder.setNumber(messageCount); - - // Show notification - // try..catch potentially needed for very specific devices - try { - notificationManager.notify(String.valueOf(accountId), ID_MSG_OFFSET + chatId, builder.build()); - } catch (Exception e) { - Log.e(TAG, "cannot add notification", e); - } - - // Group notifications in a summary (Android 7+) - if (includeSummary && Build.VERSION.SDK_INT >= 24) { - try { - NotificationCompat.Builder summary = new NotificationCompat.Builder(context, notificationChannel) - .setGroup(GRP_MSG + "." + accountId) - .setGroupSummary(true) - .setSmallIcon(R.drawable.icon_notification) - .setColor(context.getResources().getColor(R.color.delta_primary, null)) - .setCategory(NotificationCompat.CATEGORY_MESSAGE) - .setContentTitle("Delta Chat") - .setContentText("New messages") - .setContentIntent(getOpenChatlistIntent(accountId)); - if (privacy.isDisplayContact() && !TextUtils.isEmpty(accountTag)) { - summary.setSubText(accountTag); - } - notificationManager.notify(String.valueOf(accountId), ID_MSG_SUMMARY, summary.build()); - } catch (Exception e) { - Log.e(TAG, "cannot add notification summary", e); - } - } - } catch (Exception e) { - Log.e(TAG, "cannot show notification", e); - } - } - - @WorkerThread - private void rebuildNotification(int accountId, int chatId, LinkedHashMap messages) { - try { - DcContext dcContext = ApplicationContext.getDcAccounts().getAccount(accountId); - DcChat dcChat = dcContext.getChat(chatId); - - if (dcContext.isMuted() || dcChat.isMuted()) { - return; - } - - NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && !notificationManager.areNotificationsEnabled()) { - return; - } - - // Get the latest message ID (last entry in LinkedHashMap) - Integer latestMsgId = null; - String lastLine = null; - for (Map.Entry entry : messages.entrySet()) { - latestMsgId = entry.getKey(); - lastLine = entry.getValue(); - } - if (latestMsgId == null || lastLine == null) { - return; - } - - ChatData chatData = new ChatData(accountId, chatId); - String notificationChannel = getNotificationChannel(notificationManager, chatData, dcChat); - - int cnt = dcContext.getFreshMsgCount(chatId); - buildAndShowChatNotification(accountId, chatId, latestMsgId, dcContext, dcChat, - notificationChannel, lastLine, null, false, messages, cnt, false); - - } catch (Exception e) { - Log.e(TAG, "cannot rebuild notification", e); - } - } - - public Bitmap getAvatar(DcChat dcChat) { - Recipient recipient = new Recipient(context, dcChat); + if (notificationChannelsSupported()) { try { - Drawable drawable; - ContactPhoto contactPhoto = recipient.getContactPhoto(context); - if (contactPhoto != null) { - drawable = GlideApp.with(context.getApplicationContext()) - .load(contactPhoto) - .diskCacheStrategy(DiskCacheStrategy.NONE) - .circleCrop() - .submit(context.getResources().getDimensionPixelSize(android.R.dimen.notification_large_icon_width), - context.getResources().getDimensionPixelSize(android.R.dimen.notification_large_icon_height)) - .get(); + name = "(calls) " + name; - } else { - drawable = recipient.getFallbackContactPhoto().asDrawable(context, recipient.getFallbackAvatarColor()); + // check if there is already a channel with the given name + List channels = notificationManager.getNotificationChannels(); + boolean channelExists = false; + for (int i = 0; i < channels.size(); i++) { + String currChannelId = channels.get(i).getId(); + if (currChannelId.startsWith(CH_CALLS_PREFIX)) { + // this is one of the calls channels handled here ... + if (currChannelId.equals(channelId)) { + // ... this is the actually required channel, fine :) + // update the name to reflect localize changes and chat renames + channelExists = true; + channels.get(i).setName(name); + } + } } - if (drawable != null) { - int wh = context.getResources().getDimensionPixelSize(R.dimen.contact_photo_target_size); - return BitmapUtil.createFromDrawable(drawable, wh, wh); - } - } catch (Exception e) { Log.w(TAG, e); } - return null; + // create the channel + if (!channelExists) { + NotificationChannel channel = + new NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_MAX); + channel.setDescription("Informs about incoming calls."); + channel.setShowBadge(true); + + Uri ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); + channel.setSound( + ringtone, + new AudioAttributes.Builder() + .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE) + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) + .build()); + notificationManager.createNotificationChannel(channel); + } + } catch (Exception e) { + Log.e(TAG, "Error in getCallNotificationChannel()", e); + } } - public void removeNotification(int accountId, int chatId, int msgId) { - boolean shouldCancelNotification = false; - boolean removeSummary = false; - LinkedHashMap remainingMessages = null; + return channelId; + } - synchronized (inboxes) { - HashMap> accountInbox = inboxes.get(accountId); - if (accountInbox != null) { - LinkedHashMap messages = accountInbox.get(chatId); - if (messages != null) { - messages.remove(msgId); + // add notifications & co. + // -------------------------------------------------------------------------------------------- - if (messages.isEmpty()) { - // No more messages for this chat - accountInbox.remove(chatId); - shouldCancelNotification = true; - removeSummary = accountInbox.isEmpty(); - } else { - // Keep a copy of remaining messages for rebuilding - remainingMessages = new LinkedHashMap<>(messages); - } - } + public void notifyMessage(int accountId, int chatId, int msgId) { + Util.runOnAnyBackgroundThread( + () -> { + DcContext dcContext = context.getDcAccounts().getAccount(accountId); + DcChat dcChat = dcContext.getChat(chatId); + + DcMsg dcMsg = dcContext.getMsg(msgId); + NotificationPrivacyPreference privacy = Prefs.getNotificationPrivacy(context); + + String shortLine = + privacy.isDisplayMessage() + ? dcMsg.getSummarytext(2000) + : context.getString(R.string.notify_new_message); + if (dcChat.isMultiUser() && privacy.isDisplayContact()) { + shortLine = + dcMsg.getSenderName(dcContext.getContact(dcMsg.getFromId())) + ": " + shortLine; + } + String tickerLine = shortLine; + if (!dcChat.isMultiUser() && privacy.isDisplayContact()) { + tickerLine = + dcMsg.getSenderName(dcContext.getContact(dcMsg.getFromId())) + ": " + tickerLine; + + if (dcMsg.getOverrideSenderName() != null) { + // There is an "overridden" display name on the message, so, we need to prepend the + // display name to the message, + // i.e. set the shortLine to be the same as the tickerLine. + shortLine = tickerLine; } - } + } - if (shouldCancelNotification) { - // Cancel the notification entirely - NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); - String tag = String.valueOf(accountId); - notificationManager.cancel(tag, ID_MSG_OFFSET + chatId); - if (removeSummary) { - notificationManager.cancel(tag, ID_MSG_SUMMARY); - } - } else if (remainingMessages != null && !remainingMessages.isEmpty()) { - rebuildNotification(accountId, chatId, remainingMessages); - } - } - - public void removeNotifications(int accountId, int chatId) { - boolean removeSummary; - synchronized (inboxes) { - HashMap> accountInbox = inboxes.get(accountId); - if (accountInbox == null) { - accountInbox = new HashMap<>(); - } - accountInbox.remove(chatId); - removeSummary = accountInbox.isEmpty(); - } - - // cancel notification independently of inboxes array, - // due to restarts, the app may have notification even when inboxes is empty. - try { - NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); - String tag = String.valueOf(accountId); - notificationManager.cancel(tag, ID_MSG_OFFSET + chatId); - if (removeSummary) { - notificationManager.cancel(tag, ID_MSG_SUMMARY); - } - } catch (Exception e) { Log.w(TAG, e); } - } - - public void removeAllNotifications(int accountId) { - NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); - String tag = String.valueOf(accountId); - synchronized (inboxes) { - HashMap> accountInbox = inboxes.get(accountId); - notificationManager.cancel(tag, ID_MSG_SUMMARY); - if (accountInbox != null) { - for (Integer chatId : accountInbox.keySet()) { - notificationManager.cancel(tag, ID_MSG_OFFSET + chatId); - } - accountInbox.clear(); - } - } - } - - public void updateVisibleChat(int accountId, int chatId) { - Util.runOnAnyBackgroundThread(() -> { - - if (accountId != 0 && chatId != 0) { - visibleChat = new ChatData(accountId, chatId); - removeNotifications(accountId, chatId); - } else { - visibleChat = null; - } + DcMsg quotedMsg = dcMsg.getQuotedMsg(); + boolean isMention = dcChat.isMultiUser() && quotedMsg != null && quotedMsg.isOutgoing(); + maybeAddNotification(accountId, dcChat, msgId, shortLine, tickerLine, true, isMention); }); + } + + public void notifyReaction(int accountId, int contactId, int msgId, String reaction) { + Util.runOnAnyBackgroundThread( + () -> { + DcContext dcContext = context.getDcAccounts().getAccount(accountId); + DcMsg dcMsg = dcContext.getMsg(msgId); + + NotificationPrivacyPreference privacy = Prefs.getNotificationPrivacy(context); + if (!privacy.isDisplayContact() || !privacy.isDisplayMessage()) { + return; // showing "New Message" is wrong and showing "New Reaction" is already content. + // just do nothing. + } + + DcContact sender = dcContext.getContact(contactId); + String shortLine = + context.getString( + R.string.reaction_by_other, + sender.getDisplayName(), + reaction, + dcMsg.getSummarytext(2000)); + DcChat dcChat = dcContext.getChat(dcMsg.getChatId()); + maybeAddNotification( + accountId, dcChat, msgId, shortLine, shortLine, false, dcChat.isMultiUser()); + }); + } + + public void notifyWebxdc(int accountId, int contactId, int msgId, String text) { + Util.runOnAnyBackgroundThread( + () -> { + NotificationPrivacyPreference privacy = Prefs.getNotificationPrivacy(context); + if (!privacy.isDisplayContact() || !privacy.isDisplayMessage()) { + return; // showing "New Message" is wrong, just do nothing. + } + + DcContext dcContext = context.getDcAccounts().getAccount(accountId); + DcMsg dcMsg = dcContext.getMsg(msgId); + DcMsg parentMsg; + if (dcMsg.getType() == DcMsg.DC_MSG_WEBXDC) { + parentMsg = dcMsg; + } else { // info message, get parent xdc + parentMsg = dcMsg.getParent() != null ? dcMsg.getParent() : dcMsg; + } + + if (Util.equals(visibleWebxdc, new Pair<>(accountId, parentMsg.getId()))) { + return; // do not notify if the app is already open + } + + JSONObject info = parentMsg.getWebxdcInfo(); + final String name = JsonUtils.optString(info, "name"); + String shortLine = name.isEmpty() ? text : (name + ": " + text); + DcChat dcChat = dcContext.getChat(dcMsg.getChatId()); + maybeAddNotification( + accountId, dcChat, msgId, shortLine, shortLine, false, dcChat.isMultiUser()); + }); + } + + @WorkerThread + private void maybeAddNotification( + int accountId, + DcChat dcChat, + int msgId, + String shortLine, + String tickerLine, + boolean playInChatSound, + boolean isMention) { + DcContext dcContext = ApplicationContext.getDcAccounts().getAccount(accountId); + int chatId = dcChat.getId(); + ChatData chatData = new ChatData(accountId, chatId); + isMention = isMention && dcContext.isMentionsEnabled(); + + if (dcContext.isMuted() || (!isMention && dcChat.isMuted())) { + return; } - public void clearVisibleChat() { - visibleChat = null; + NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU + && !notificationManager.areNotificationsEnabled()) { + return; } - public void updateVisibleWebxdc(int accountId, int msgId) { - if (accountId != 0 && msgId != 0) { - visibleWebxdc = new Pair<>(accountId, msgId); - } else { - visibleWebxdc = null; + if (Util.equals(visibleChat, chatData)) { + if (playInChatSound && Prefs.isInChatNotifications(context)) { + InChatSounds.getInstance(context).playIncomingSound(); + } + return; + } + + NotificationPrivacyPreference privacy = Prefs.getNotificationPrivacy(context); + long now = System.currentTimeMillis(); + boolean signal = (now - lastAudibleNotification) > MIN_AUDIBLE_PERIOD_MILLIS; + if (signal) { + lastAudibleNotification = now; + } + + // create a basic notification + // even without a name or message displayed, + // it makes sense to use separate notification channels and to open the respective chat directly + // - + // the user may eg. have chosen a different sound + String notificationChannel = getNotificationChannel(notificationManager, chatData, dcChat); + + LinkedHashMap messagesForInbox = null; + if (privacy.isDisplayContact() && privacy.isDisplayMessage()) { + synchronized (inboxes) { + HashMap> accountInbox = inboxes.get(accountId); + if (accountInbox == null) { + accountInbox = new HashMap<>(); + inboxes.put(accountId, accountInbox); } - } - - public void clearVisibleWebxdc() { - visibleWebxdc = null; - } - - public void maybePlaySendSound(DcChat dcChat) { - if (Prefs.isInChatNotifications(context) && !dcChat.isMuted()) { - InChatSounds.getInstance(context).playSendSound(); + LinkedHashMap messages = accountInbox.get(chatId); + if (messages == null) { + messages = new LinkedHashMap<>(); + accountInbox.put(chatId, messages); } + messages.put(msgId, shortLine); + messagesForInbox = new LinkedHashMap<>(messages); + } } + int cnt = dcContext.getFreshMsgCount(chatId); + buildAndShowChatNotification( + accountId, + chatId, + msgId, + dcContext, + dcChat, + notificationChannel, + shortLine, + tickerLine, + signal, + messagesForInbox, + cnt, + true); + } + + @WorkerThread + private void buildAndShowChatNotification( + int accountId, + int chatId, + int msgId, + DcContext dcContext, + DcChat dcChat, + String notificationChannel, + String contentText, + String ticker, + boolean signal, + LinkedHashMap messagesForInbox, + int messageCount, + boolean includeSummary) { + try { + NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); + NotificationPrivacyPreference privacy = Prefs.getNotificationPrivacy(context); + ChatData chatData = new ChatData(accountId, chatId); + + // Create basic notification + NotificationCompat.Builder builder = + new NotificationCompat.Builder(context, notificationChannel) + .setSmallIcon(R.drawable.icon_notification) + .setColor(context.getResources().getColor(R.color.delta_primary)) + .setPriority(Prefs.getNotificationPriority(context)) + .setCategory(NotificationCompat.CATEGORY_MESSAGE) + .setOnlyAlertOnce(!signal) + .setContentText(contentText) + .setDeleteIntent(getMarkAsReadIntent(chatData, msgId, false)) + .setContentIntent(getOpenChatIntent(chatData)); + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + builder.setGroup(GRP_MSG + "." + accountId); + } + + String accountTag = dcContext.getConfig(CONFIG_PRIVATE_TAG); + if (accountTag.isEmpty() && ApplicationContext.getDcAccounts().getAll().length > 1) { + accountTag = dcContext.getName(); + } + + if (privacy.isDisplayContact()) { + builder.setContentTitle(dcChat.getName()); + if (!TextUtils.isEmpty(accountTag)) { + builder.setSubText(accountTag); + } + } + + if (ticker != null) { + builder.setTicker(ticker); + } + + // Set sound, vibrate, led for systems that do not have notification channels + if (!notificationChannelsSupported()) { + if (signal) { + Uri sound = effectiveSound(chatData); + if (sound != null && !TextUtils.isEmpty(sound.toString())) { + builder.setSound(sound); + } + boolean vibrate = effectiveVibrate(chatData); + if (vibrate) { + builder.setDefaults(Notification.DEFAULT_VIBRATE); + } + } + String ledColor = Prefs.getNotificationLedColor(context); + if (!ledColor.equals("none")) { + builder.setLights(getLedArgb(ledColor), 500, 2000); + } + } + + // Set avatar + if (privacy.isDisplayContact()) { + Bitmap bitmap = getAvatar(dcChat); + if (bitmap != null) { + builder.setLargeIcon(bitmap); + } + } + + // Add buttons that allow some actions without opening Delta Chat. + // If privacy options are enabled, the buttons are not added. + if (privacy.isDisplayContact() && privacy.isDisplayMessage()) { + try { + PendingIntent inNotificationReplyIntent = getRemoteReplyIntent(chatData, msgId); + PendingIntent markReadIntent = getMarkAsReadIntent(chatData, msgId, true); + + NotificationCompat.Action markAsReadAction = + new NotificationCompat.Action( + R.drawable.check, context.getString(R.string.mark_as_read_short), markReadIntent); + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + NotificationCompat.Action replyAction = + new NotificationCompat.Action.Builder( + R.drawable.ic_reply_white_36dp, + context.getString(R.string.notify_reply_button), + inNotificationReplyIntent) + .addRemoteInput( + new RemoteInput.Builder(RemoteReplyReceiver.EXTRA_REMOTE_REPLY) + .setLabel(context.getString(R.string.notify_reply_button)) + .build()) + .build(); + builder.addAction(replyAction); + } + + NotificationCompat.Action wearableReplyAction = + new NotificationCompat.Action.Builder( + R.drawable.ic_reply, + context.getString(R.string.notify_reply_button), + inNotificationReplyIntent) + .addRemoteInput( + new RemoteInput.Builder(RemoteReplyReceiver.EXTRA_REMOTE_REPLY) + .setLabel(context.getString(R.string.notify_reply_button)) + .build()) + .build(); + builder.addAction(markAsReadAction); + builder.extend( + new NotificationCompat.WearableExtender() + .addAction(markAsReadAction) + .addAction(wearableReplyAction)); + } catch (Exception e) { + Log.w(TAG, e); + } + } + + // Create inbox style (gets visible if the notification is expanded) + if (privacy.isDisplayContact() && privacy.isDisplayMessage() && messagesForInbox != null) { + try { + NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); + for (String line : messagesForInbox.values()) { + inboxStyle.addLine(line); + } + builder.setStyle(inboxStyle); + } catch (Exception e) { + Log.w(TAG, e); + } + } + + // Messages count + builder.setContentInfo(String.valueOf(messageCount)); + builder.setNumber(messageCount); + + // Show notification + // try..catch potentially needed for very specific devices + try { + notificationManager.notify( + String.valueOf(accountId), ID_MSG_OFFSET + chatId, builder.build()); + } catch (Exception e) { + Log.e(TAG, "cannot add notification", e); + } + + // Group notifications in a summary (Android 7+) + if (includeSummary && Build.VERSION.SDK_INT >= 24) { + try { + NotificationCompat.Builder summary = + new NotificationCompat.Builder(context, notificationChannel) + .setGroup(GRP_MSG + "." + accountId) + .setGroupSummary(true) + .setSmallIcon(R.drawable.icon_notification) + .setColor(context.getResources().getColor(R.color.delta_primary, null)) + .setCategory(NotificationCompat.CATEGORY_MESSAGE) + .setContentTitle("Delta Chat") + .setContentText("New messages") + .setContentIntent(getOpenChatlistIntent(accountId)); + if (privacy.isDisplayContact() && !TextUtils.isEmpty(accountTag)) { + summary.setSubText(accountTag); + } + notificationManager.notify(String.valueOf(accountId), ID_MSG_SUMMARY, summary.build()); + } catch (Exception e) { + Log.e(TAG, "cannot add notification summary", e); + } + } + } catch (Exception e) { + Log.e(TAG, "cannot show notification", e); + } + } + + @WorkerThread + private void rebuildNotification( + int accountId, int chatId, LinkedHashMap messages) { + try { + DcContext dcContext = ApplicationContext.getDcAccounts().getAccount(accountId); + DcChat dcChat = dcContext.getChat(chatId); + + if (dcContext.isMuted() || dcChat.isMuted()) { + return; + } + + NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU + && !notificationManager.areNotificationsEnabled()) { + return; + } + + // Get the latest message ID (last entry in LinkedHashMap) + Integer latestMsgId = null; + String lastLine = null; + for (Map.Entry entry : messages.entrySet()) { + latestMsgId = entry.getKey(); + lastLine = entry.getValue(); + } + if (latestMsgId == null || lastLine == null) { + return; + } + + ChatData chatData = new ChatData(accountId, chatId); + String notificationChannel = getNotificationChannel(notificationManager, chatData, dcChat); + + int cnt = dcContext.getFreshMsgCount(chatId); + buildAndShowChatNotification( + accountId, + chatId, + latestMsgId, + dcContext, + dcChat, + notificationChannel, + lastLine, + null, + false, + messages, + cnt, + false); + + } catch (Exception e) { + Log.e(TAG, "cannot rebuild notification", e); + } + } + + public Bitmap getAvatar(DcChat dcChat) { + Recipient recipient = new Recipient(context, dcChat); + try { + Drawable drawable; + ContactPhoto contactPhoto = recipient.getContactPhoto(context); + if (contactPhoto != null) { + drawable = + GlideApp.with(context.getApplicationContext()) + .load(contactPhoto) + .diskCacheStrategy(DiskCacheStrategy.NONE) + .circleCrop() + .submit( + context + .getResources() + .getDimensionPixelSize(android.R.dimen.notification_large_icon_width), + context + .getResources() + .getDimensionPixelSize(android.R.dimen.notification_large_icon_height)) + .get(); + + } else { + drawable = + recipient + .getFallbackContactPhoto() + .asDrawable(context, recipient.getFallbackAvatarColor()); + } + if (drawable != null) { + int wh = context.getResources().getDimensionPixelSize(R.dimen.contact_photo_target_size); + return BitmapUtil.createFromDrawable(drawable, wh, wh); + } + } catch (Exception e) { + Log.w(TAG, e); + } + + return null; + } + + public void removeNotification(int accountId, int chatId, int msgId) { + boolean shouldCancelNotification = false; + boolean removeSummary = false; + LinkedHashMap remainingMessages = null; + + synchronized (inboxes) { + HashMap> accountInbox = inboxes.get(accountId); + if (accountInbox != null) { + LinkedHashMap messages = accountInbox.get(chatId); + if (messages != null) { + messages.remove(msgId); + + if (messages.isEmpty()) { + // No more messages for this chat + accountInbox.remove(chatId); + shouldCancelNotification = true; + removeSummary = accountInbox.isEmpty(); + } else { + // Keep a copy of remaining messages for rebuilding + remainingMessages = new LinkedHashMap<>(messages); + } + } + } + } + + if (shouldCancelNotification) { + // Cancel the notification entirely + NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); + String tag = String.valueOf(accountId); + notificationManager.cancel(tag, ID_MSG_OFFSET + chatId); + if (removeSummary) { + notificationManager.cancel(tag, ID_MSG_SUMMARY); + } + } else if (remainingMessages != null && !remainingMessages.isEmpty()) { + rebuildNotification(accountId, chatId, remainingMessages); + } + } + + public void removeNotifications(int accountId, int chatId) { + boolean removeSummary; + synchronized (inboxes) { + HashMap> accountInbox = inboxes.get(accountId); + if (accountInbox == null) { + accountInbox = new HashMap<>(); + } + accountInbox.remove(chatId); + removeSummary = accountInbox.isEmpty(); + } + + // cancel notification independently of inboxes array, + // due to restarts, the app may have notification even when inboxes is empty. + try { + NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); + String tag = String.valueOf(accountId); + notificationManager.cancel(tag, ID_MSG_OFFSET + chatId); + if (removeSummary) { + notificationManager.cancel(tag, ID_MSG_SUMMARY); + } + } catch (Exception e) { + Log.w(TAG, e); + } + } + + public void removeAllNotifications(int accountId) { + NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); + String tag = String.valueOf(accountId); + synchronized (inboxes) { + HashMap> accountInbox = inboxes.get(accountId); + notificationManager.cancel(tag, ID_MSG_SUMMARY); + if (accountInbox != null) { + for (Integer chatId : accountInbox.keySet()) { + notificationManager.cancel(tag, ID_MSG_OFFSET + chatId); + } + accountInbox.clear(); + } + } + } + + public void updateVisibleChat(int accountId, int chatId) { + Util.runOnAnyBackgroundThread( + () -> { + if (accountId != 0 && chatId != 0) { + visibleChat = new ChatData(accountId, chatId); + removeNotifications(accountId, chatId); + } else { + visibleChat = null; + } + }); + } + + public void clearVisibleChat() { + visibleChat = null; + } + + public void updateVisibleWebxdc(int accountId, int msgId) { + if (accountId != 0 && msgId != 0) { + visibleWebxdc = new Pair<>(accountId, msgId); + } else { + visibleWebxdc = null; + } + } + + public void clearVisibleWebxdc() { + visibleWebxdc = null; + } + + public void maybePlaySendSound(DcChat dcChat) { + if (Prefs.isInChatNotifications(context) && !dcChat.isMuted()) { + InChatSounds.getInstance(context).playSendSound(); + } + } + public static class ChatData { public final int accountId; public final int chatId; public ChatData(int accountId, int chatId) { - this.accountId = accountId; - this.chatId = chatId; + this.accountId = accountId; + this.chatId = chatId; } @Override diff --git a/src/main/java/org/thoughtcrime/securesms/webrtc/WebRTCClient.java b/src/main/java/org/thoughtcrime/securesms/webrtc/WebRTCClient.java index 64ca88397..5c9f21a84 100644 --- a/src/main/java/org/thoughtcrime/securesms/webrtc/WebRTCClient.java +++ b/src/main/java/org/thoughtcrime/securesms/webrtc/WebRTCClient.java @@ -5,10 +5,16 @@ import android.os.Build; import android.os.Handler; import android.os.Looper; import android.util.Log; - import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; - +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -33,19 +39,7 @@ import org.webrtc.VideoDecoderFactory; import org.webrtc.VideoEncoderFactory; import org.webrtc.VideoTrack; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -/** - * Manages WebRTC PeerConnection. - * Mirrors TypeScript CallsManager. - */ +/** Manages WebRTC PeerConnection. Mirrors TypeScript CallsManager. */ @RequiresApi(Build.VERSION_CODES.M) public class WebRTCClient { @@ -95,17 +89,22 @@ public class WebRTCClient { // Callbacks to ViewModel private final Callbacks callbacks; - /** - * Callbacks to ViewModel of connection events - */ + /** Callbacks to ViewModel of connection events */ public interface Callbacks { void onOfferReady(String offerSdp); + void onAnswerReady(String answerSdp); + void onRemoteVideoTrack(VideoTrack videoTrack); + void onRemoteAudioTrack(AudioTrack audioTrack); + void onConnectionStateChanged(PeerConnection.PeerConnectionState state); + void onRemoteMutedStateChanged(boolean audioEnabled, boolean videoEnabled); + void onRelayUsageChanged(Boolean isRelayUsed); + void onError(String error); } @@ -124,20 +123,21 @@ public class WebRTCClient { private void initializePeerConnectionFactory() { PeerConnectionFactory.InitializationOptions initOptions = - PeerConnectionFactory.InitializationOptions.builder(context) - .setEnableInternalTracer(false) - .setFieldTrials("") - .createInitializationOptions(); + PeerConnectionFactory.InitializationOptions.builder(context) + .setEnableInternalTracer(false) + .setFieldTrials("") + .createInitializationOptions(); PeerConnectionFactory.initialize(initOptions); EglBase.Context eglBaseContext = EglUtils.getEglBase().getEglBaseContext(); // Create video encoder/decoder factories - VideoEncoderFactory encoderFactory = new DefaultVideoEncoderFactory( - eglBaseContext, - true, // enableIntelVp8Encoder - true // enableH264HighProfile - ); + VideoEncoderFactory encoderFactory = + new DefaultVideoEncoderFactory( + eglBaseContext, + true, // enableIntelVp8Encoder + true // enableH264HighProfile + ); VideoDecoderFactory decoderFactory = new DefaultVideoDecoderFactory(eglBaseContext); @@ -145,21 +145,19 @@ public class WebRTCClient { options.disableEncryption = false; options.disableNetworkMonitor = false; - peerConnectionFactory = PeerConnectionFactory.builder() - .setOptions(options) - .setVideoEncoderFactory(encoderFactory) - .setVideoDecoderFactory(decoderFactory) - .createPeerConnectionFactory(); + peerConnectionFactory = + PeerConnectionFactory.builder() + .setOptions(options) + .setVideoEncoderFactory(encoderFactory) + .setVideoDecoderFactory(decoderFactory) + .createPeerConnectionFactory(); Log.d(TAG, "PeerConnectionFactory initialized"); } /** - * Expected JSON format: - * [ - * {"urls": "stun:stun.example.com:3478"}, - * {"urls": "turn:turn.example.com", "username": "user", "credential": "pass"} - * ] + * Expected JSON format: [ {"urls": "stun:stun.example.com:3478"}, {"urls": + * "turn:turn.example.com", "username": "user", "credential": "pass"} ] */ public void configure(String iceServersJson) { this.iceServers = parseIceServers(iceServersJson); @@ -195,8 +193,7 @@ public class WebRTCClient { } } - PeerConnection.IceServer.Builder builder = - PeerConnection.IceServer.builder(urls); + PeerConnection.IceServer.Builder builder = PeerConnection.IceServer.builder(urls); if (serverObj.has("username")) { builder.setUsername(serverObj.getString("username")); @@ -214,9 +211,7 @@ public class WebRTCClient { return servers; } - /** - * Set local media stream - */ + /** Set local media stream */ public void setLocalMediaStream(MediaStream stream) { this.localStream = stream; @@ -227,8 +222,12 @@ public class WebRTCClient { this.localVideoTrack = stream.videoTracks.get(0); } - Log.d(TAG, "Local media stream set: audio: " + (localAudioTrack != null) - + ", video: " + (localVideoTrack != null)); + Log.d( + TAG, + "Local media stream set: audio: " + + (localAudioTrack != null) + + ", video: " + + (localVideoTrack != null)); } public boolean hasLocalMediaStream() { @@ -236,18 +235,15 @@ public class WebRTCClient { } private void createPeerConnection() { - PeerConnection.RTCConfiguration rtcConfig = - new PeerConnection.RTCConfiguration(iceServers); + PeerConnection.RTCConfiguration rtcConfig = new PeerConnection.RTCConfiguration(iceServers); rtcConfig.iceTransportsType = PeerConnection.IceTransportsType.ALL; rtcConfig.bundlePolicy = PeerConnection.BundlePolicy.MAXBUNDLE; rtcConfig.rtcpMuxPolicy = PeerConnection.RtcpMuxPolicy.REQUIRE; rtcConfig.iceCandidatePoolSize = 1; rtcConfig.sdpSemantics = PeerConnection.SdpSemantics.UNIFIED_PLAN; - peerConnection = peerConnectionFactory.createPeerConnection( - rtcConfig, - new PeerConnectionObserver() - ); + peerConnection = + peerConnectionFactory.createPeerConnection(rtcConfig, new PeerConnectionObserver()); if (peerConnection == null) { callbacks.onError("Failed to create PeerConnection"); @@ -362,37 +358,38 @@ public class WebRTCClient { iceTricklingDataChannel = peerConnection.createDataChannel("iceTrickling", init); - iceTricklingDataChannel.registerObserver(new DataChannel.Observer() { - @Override - public void onBufferedAmountChange(long amount) {} + iceTricklingDataChannel.registerObserver( + new DataChannel.Observer() { + @Override + public void onBufferedAmountChange(long amount) {} - @Override - public void onStateChange() { - DataChannel.State state = iceTricklingDataChannel.state(); - Log.d(TAG, "ICE Trickling channel state: " + state); + @Override + public void onStateChange() { + DataChannel.State state = iceTricklingDataChannel.state(); + Log.d(TAG, "ICE Trickling channel state: " + state); - if (state == DataChannel.State.OPEN) { - iceTricklingChannelOpen = true; - flushIceCandidateBuffer(); - } else if (state == DataChannel.State.CLOSED) { - iceTricklingChannelOpen = false; - } - } + if (state == DataChannel.State.OPEN) { + iceTricklingChannelOpen = true; + flushIceCandidateBuffer(); + } else if (state == DataChannel.State.CLOSED) { + iceTricklingChannelOpen = false; + } + } - @Override - public void onMessage(DataChannel.Buffer buffer) { - String json = extractString(buffer); - Log.d(TAG, "Received ICE candidate: " + json); + @Override + public void onMessage(DataChannel.Buffer buffer) { + String json = extractString(buffer); + Log.d(TAG, "Received ICE candidate: " + json); - IceCandidate candidate = parseIceCandidate(json); + IceCandidate candidate = parseIceCandidate(json); - if (candidate != null) { - peerConnection.addIceCandidate(candidate); - } else { - Log.d(TAG, "Received end-of-candidates signal"); - } - } - }); + if (candidate != null) { + peerConnection.addIceCandidate(candidate); + } else { + Log.d(TAG, "Received end-of-candidates signal"); + } + } + }); } private void setupMutedStateDataChannel() { @@ -402,44 +399,45 @@ public class WebRTCClient { mutedStateDataChannel = peerConnection.createDataChannel("mutedState", init); - mutedStateDataChannel.registerObserver(new DataChannel.Observer() { - @Override - public void onBufferedAmountChange(long amount) {} + mutedStateDataChannel.registerObserver( + new DataChannel.Observer() { + @Override + public void onBufferedAmountChange(long amount) {} - @Override - public void onStateChange() { - DataChannel.State state = mutedStateDataChannel.state(); - Log.d(TAG, "mutedState channel state: " + state); + @Override + public void onStateChange() { + DataChannel.State state = mutedStateDataChannel.state(); + Log.d(TAG, "mutedState channel state: " + state); - if (state == DataChannel.State.OPEN) { - mutedStateChannelOpen = true; + if (state == DataChannel.State.OPEN) { + mutedStateChannelOpen = true; - boolean audioEnabled = localAudioTrack != null && localAudioTrack.enabled(); - boolean videoEnabled = localVideoTrack != null && localVideoTrack.enabled(); - sendMutedState(audioEnabled, videoEnabled); + boolean audioEnabled = localAudioTrack != null && localAudioTrack.enabled(); + boolean videoEnabled = localVideoTrack != null && localVideoTrack.enabled(); + sendMutedState(audioEnabled, videoEnabled); - } else if (state == DataChannel.State.CLOSED) { - mutedStateChannelOpen = false; - } - } + } else if (state == DataChannel.State.CLOSED) { + mutedStateChannelOpen = false; + } + } - @Override - public void onMessage(DataChannel.Buffer buffer) { - String json = extractString(buffer); - Log.d(TAG, "Received muted state: " + json); + @Override + public void onMessage(DataChannel.Buffer buffer) { + String json = extractString(buffer); + Log.d(TAG, "Received muted state: " + json); - try { - JSONObject obj = new JSONObject(json); - boolean audioEnabled = obj.getBoolean("audioEnabled"); - boolean videoEnabled = obj.getBoolean("videoEnabled"); + try { + JSONObject obj = new JSONObject(json); + boolean audioEnabled = obj.getBoolean("audioEnabled"); + boolean videoEnabled = obj.getBoolean("videoEnabled"); - mainHandler.post(() -> - callbacks.onRemoteMutedStateChanged(audioEnabled, videoEnabled)); - } catch (JSONException e) { - Log.e(TAG, "Failed to parse muted state JSON", e); - } - } - }); + mainHandler.post( + () -> callbacks.onRemoteMutedStateChanged(audioEnabled, videoEnabled)); + } catch (JSONException e) { + Log.e(TAG, "Failed to parse muted state JSON", e); + } + } + }); } // Flush buffered ICE candidates when data channel opens @@ -465,9 +463,7 @@ public class WebRTCClient { Log.d(TAG, "Sent ICE candidate using data channel: " + candidate.sdpMid); } - /** - * Send current muted state to remote peer - */ + /** Send current muted state to remote peer */ public void sendMutedState(boolean audioEnabled, boolean videoEnabled) { if (!mutedStateChannelOpen) { Log.w(TAG, "Muted state channel not open"); @@ -479,8 +475,7 @@ public class WebRTCClient { json.put("audioEnabled", audioEnabled); json.put("videoEnabled", videoEnabled); - ByteBuffer buffer = ByteBuffer.wrap( - json.toString().getBytes(StandardCharsets.UTF_8)); + ByteBuffer buffer = ByteBuffer.wrap(json.toString().getBytes(StandardCharsets.UTF_8)); mutedStateDataChannel.send(new DataChannel.Buffer(buffer, false)); Log.d(TAG, "Sent muted state: audio: " + audioEnabled + ", video: " + videoEnabled); @@ -519,10 +514,7 @@ public class WebRTCClient { } } - /** - * Wait for enough ICE before sending offer/answer - * Mirrors TypeScript gatheredEnoughIce() - */ + /** Wait for enough ICE before sending offer/answer Mirrors TypeScript gatheredEnoughIce() */ private boolean waitForEnoughIce() { boolean hasTurnServer = false; boolean hasStunServer = false; @@ -584,9 +576,7 @@ public class WebRTCClient { // Outgoing Call - /** - * Start outgoing call - */ + /** Start outgoing call */ public void startOutgoingCall() { if (localStream == null) { mainHandler.post(() -> callbacks.onError("Local media stream not set")); @@ -594,126 +584,129 @@ public class WebRTCClient { } Log.d(TAG, "Starting outgoing call"); - mainHandler.post(() -> - callbacks.onConnectionStateChanged(PeerConnection.PeerConnectionState.CONNECTING)); + mainHandler.post( + () -> callbacks.onConnectionStateChanged(PeerConnection.PeerConnectionState.CONNECTING)); createPeerConnection(); for (AudioTrack track : localStream.audioTracks) { - RtpSender sender = peerConnection.addTrack(track, Collections.singletonList(localStream.getId())); + RtpSender sender = + peerConnection.addTrack(track, Collections.singletonList(localStream.getId())); Log.d(TAG, "Added audio track, sender: " + sender); } for (VideoTrack track : localStream.videoTracks) { - RtpSender sender = peerConnection.addTrack(track, Collections.singletonList(localStream.getId())); + RtpSender sender = + peerConnection.addTrack(track, Collections.singletonList(localStream.getId())); Log.d(TAG, "Added video track, sender: " + sender); } Log.d(TAG, "Total senders: " + peerConnection.getSenders().size()); // Create offer - peerConnection.createOffer(new SdpObserver() { - @Override - public void onCreateSuccess(SessionDescription sdp) { - onOfferCreated(sdp); - } + peerConnection.createOffer( + new SdpObserver() { + @Override + public void onCreateSuccess(SessionDescription sdp) { + onOfferCreated(sdp); + } - @Override - public void onSetSuccess() {} + @Override + public void onSetSuccess() {} - @Override - public void onCreateFailure(String error) { - Log.e(TAG, "Failed to create offer: " + error); - mainHandler.post(() -> callbacks.onError("Failed to create offer: " + error)); - } + @Override + public void onCreateFailure(String error) { + Log.e(TAG, "Failed to create offer: " + error); + mainHandler.post(() -> callbacks.onError("Failed to create offer: " + error)); + } - @Override - public void onSetFailure(String error) {} - }, new MediaConstraints()); + @Override + public void onSetFailure(String error) {} + }, + new MediaConstraints()); } private void onOfferCreated(SessionDescription offerSdp) { - peerConnection.setLocalDescription(new SdpObserver() { - @Override - public void onSetSuccess() { - Log.d(TAG, "Local description set, waiting for ICE..."); + peerConnection.setLocalDescription( + new SdpObserver() { + @Override + public void onSetSuccess() { + Log.d(TAG, "Local description set, waiting for ICE..."); - // Wait for ICE in background - new Thread(() -> { - boolean gotIce = waitForEnoughIce(); + // Wait for ICE in background + new Thread( + () -> { + boolean gotIce = waitForEnoughIce(); - if (!gotIce) { - Log.w(TAG, "Proceeding without optimal ICE candidates"); + if (!gotIce) { + Log.w(TAG, "Proceeding without optimal ICE candidates"); + } + + // Get final SDP + SessionDescription localDesc = peerConnection.getLocalDescription(); + if (localDesc != null) { + String finalSdp = localDesc.description; + + // Enable trickling for additional candidates + enableIceTrickling = true; + + // Notify ViewModel + mainHandler.post(() -> callbacks.onOfferReady(finalSdp)); + } else { + mainHandler.post( + () -> + callbacks.onError("Local description is null after ICE gathering")); + } + }) + .start(); } - // Get final SDP - SessionDescription localDesc = peerConnection.getLocalDescription(); - if (localDesc != null) { - String finalSdp = localDesc.description; + @Override + public void onCreateSuccess(SessionDescription sdp) {} - // Enable trickling for additional candidates - enableIceTrickling = true; + @Override + public void onCreateFailure(String error) {} - // Notify ViewModel - mainHandler.post(() -> callbacks.onOfferReady(finalSdp)); - } else { - mainHandler.post(() -> - callbacks.onError("Local description is null after ICE gathering")); + @Override + public void onSetFailure(String error) { + Log.e(TAG, "Failed to set local description: " + error); + mainHandler.post(() -> callbacks.onError("Failed to set local description: " + error)); } - }).start(); - } - - @Override - public void onCreateSuccess(SessionDescription sdp) {} - - @Override - public void onCreateFailure(String error) {} - - @Override - public void onSetFailure(String error) { - Log.e(TAG, "Failed to set local description: " + error); - mainHandler.post(() -> - callbacks.onError("Failed to set local description: " + error)); - } - }, offerSdp); + }, + offerSdp); } - /** - * Handle answer SDP from remote peer for outgoing call - */ + /** Handle answer SDP from remote peer for outgoing call */ public void handleAnswerSdp(String answerSdp) { Log.d(TAG, "Handling answer SDP"); - SessionDescription remoteSdp = new SessionDescription( - SessionDescription.Type.ANSWER, - answerSdp - ); + SessionDescription remoteSdp = + new SessionDescription(SessionDescription.Type.ANSWER, answerSdp); - peerConnection.setRemoteDescription(new SdpObserver() { - @Override - public void onSetSuccess() { - Log.d(TAG, "Remote answer set, connection should establish"); - } + peerConnection.setRemoteDescription( + new SdpObserver() { + @Override + public void onSetSuccess() { + Log.d(TAG, "Remote answer set, connection should establish"); + } - @Override - public void onCreateSuccess(SessionDescription sdp) {} + @Override + public void onCreateSuccess(SessionDescription sdp) {} - @Override - public void onCreateFailure(String error) {} + @Override + public void onCreateFailure(String error) {} - @Override - public void onSetFailure(String error) { - Log.e(TAG, "Failed to set remote description: " + error); - mainHandler.post(() -> - callbacks.onError("Failed to set remote description: " + error)); - } - }, remoteSdp); + @Override + public void onSetFailure(String error) { + Log.e(TAG, "Failed to set remote description: " + error); + mainHandler.post(() -> callbacks.onError("Failed to set remote description: " + error)); + } + }, + remoteSdp); } // Incoming Call - /** - * Accept incoming call - */ + /** Accept incoming call */ public void acceptIncomingCall(String offerSdp) { if (localStream == null) { mainHandler.post(() -> callbacks.onError("Local media stream not set")); @@ -721,36 +714,34 @@ public class WebRTCClient { } Log.d(TAG, "Accepting incoming call"); - mainHandler.post(() -> - callbacks.onConnectionStateChanged(PeerConnection.PeerConnectionState.CONNECTING)); + mainHandler.post( + () -> callbacks.onConnectionStateChanged(PeerConnection.PeerConnectionState.CONNECTING)); createPeerConnection(); - SessionDescription remoteSdp = new SessionDescription( - SessionDescription.Type.OFFER, - offerSdp - ); + SessionDescription remoteSdp = new SessionDescription(SessionDescription.Type.OFFER, offerSdp); - peerConnection.setRemoteDescription(new SdpObserver() { - @Override - public void onSetSuccess() { - Log.d(TAG, "Remote offer set, adding local tracks..."); - addLocalTracksAndCreateAnswer(); - } + peerConnection.setRemoteDescription( + new SdpObserver() { + @Override + public void onSetSuccess() { + Log.d(TAG, "Remote offer set, adding local tracks..."); + addLocalTracksAndCreateAnswer(); + } - @Override - public void onCreateSuccess(SessionDescription sdp) {} + @Override + public void onCreateSuccess(SessionDescription sdp) {} - @Override - public void onCreateFailure(String error) {} + @Override + public void onCreateFailure(String error) {} - @Override - public void onSetFailure(String error) { - Log.e(TAG, "Failed to set remote description: " + error); - mainHandler.post(() -> - callbacks.onError("Failed to set remote description: " + error)); - } - }, remoteSdp); + @Override + public void onSetFailure(String error) { + Log.e(TAG, "Failed to set remote description: " + error); + mainHandler.post(() -> callbacks.onError("Failed to set remote description: " + error)); + } + }, + remoteSdp); } private void addLocalTracksAndCreateAnswer() { @@ -763,70 +754,76 @@ public class WebRTCClient { } // Create answer - peerConnection.createAnswer(new SdpObserver() { - @Override - public void onCreateSuccess(SessionDescription sdp) { - onAnswerCreated(sdp); - } + peerConnection.createAnswer( + new SdpObserver() { + @Override + public void onCreateSuccess(SessionDescription sdp) { + onAnswerCreated(sdp); + } - @Override - public void onSetSuccess() {} + @Override + public void onSetSuccess() {} - @Override - public void onCreateFailure(String error) { - Log.e(TAG, "Failed to create answer: " + error); - mainHandler.post(() -> callbacks.onError("Failed to create answer: " + error)); - } + @Override + public void onCreateFailure(String error) { + Log.e(TAG, "Failed to create answer: " + error); + mainHandler.post(() -> callbacks.onError("Failed to create answer: " + error)); + } - @Override - public void onSetFailure(String error) {} - }, new MediaConstraints()); + @Override + public void onSetFailure(String error) {} + }, + new MediaConstraints()); } private void onAnswerCreated(SessionDescription answerSdp) { - peerConnection.setLocalDescription(new SdpObserver() { - @Override - public void onSetSuccess() { - Log.d(TAG, "Local answer set, waiting for ICE..."); + peerConnection.setLocalDescription( + new SdpObserver() { + @Override + public void onSetSuccess() { + Log.d(TAG, "Local answer set, waiting for ICE..."); - // Wait for ICE on background thread - new Thread(() -> { - boolean gotIce = waitForEnoughIce(); + // Wait for ICE on background thread + new Thread( + () -> { + boolean gotIce = waitForEnoughIce(); - if (!gotIce) { - Log.w(TAG, "Proceeding without optimal ICE candidates"); + if (!gotIce) { + Log.w(TAG, "Proceeding without optimal ICE candidates"); + } + + // Get final SDP + SessionDescription localDesc = peerConnection.getLocalDescription(); + if (localDesc != null) { + String finalSdp = localDesc.description; + + // Enable trickling for additional candidates + enableIceTrickling = true; + + // Notify ViewModel + mainHandler.post(() -> callbacks.onAnswerReady(finalSdp)); + } else { + mainHandler.post( + () -> + callbacks.onError("Local description is null after ICE gathering")); + } + }) + .start(); } - // Get final SDP - SessionDescription localDesc = peerConnection.getLocalDescription(); - if (localDesc != null) { - String finalSdp = localDesc.description; + @Override + public void onCreateSuccess(SessionDescription sdp) {} - // Enable trickling for additional candidates - enableIceTrickling = true; + @Override + public void onCreateFailure(String error) {} - // Notify ViewModel - mainHandler.post(() -> callbacks.onAnswerReady(finalSdp)); - } else { - mainHandler.post(() -> - callbacks.onError("Local description is null after ICE gathering")); + @Override + public void onSetFailure(String error) { + Log.e(TAG, "Failed to set local description: " + error); + mainHandler.post(() -> callbacks.onError("Failed to set local description: " + error)); } - }).start(); - } - - @Override - public void onCreateSuccess(SessionDescription sdp) {} - - @Override - public void onCreateFailure(String error) {} - - @Override - public void onSetFailure(String error) { - Log.e(TAG, "Failed to set local description: " + error); - mainHandler.post(() -> - callbacks.onError("Failed to set local description: " + error)); - } - }, answerSdp); + }, + answerSdp); } // Media Control @@ -854,62 +851,67 @@ public class WebRTCClient { private void detectRelayUsage() { // Schedule detection after connection settles - mainHandler.postDelayed(() -> { - if (peerConnection == null) return; + mainHandler.postDelayed( + () -> { + if (peerConnection == null) return; - peerConnection.getStats(report -> { - boolean relayUsed = false; + peerConnection.getStats( + report -> { + boolean relayUsed = false; - Map statsMap = report.getStatsMap(); + Map statsMap = report.getStatsMap(); - // First, find the selected candidate pair - String selectedLocalCandidateId = null; - String selectedRemoteCandidateId = null; + // First, find the selected candidate pair + String selectedLocalCandidateId = null; + String selectedRemoteCandidateId = null; - for (Map.Entry entry : statsMap.entrySet()) { - RTCStats stats = entry.getValue(); + for (Map.Entry entry : statsMap.entrySet()) { + RTCStats stats = entry.getValue(); - if ("candidate-pair".equals(stats.getType())) { - Map members = stats.getMembers(); + if ("candidate-pair".equals(stats.getType())) { + Map members = stats.getMembers(); - // Check if this pair is selected/nominated - Object state = members.get("state"); - if ("succeeded".equals(state) || Boolean.TRUE.equals(members.get("nominated"))) { - selectedLocalCandidateId = (String) members.get("localCandidateId"); - selectedRemoteCandidateId = (String) members.get("remoteCandidateId"); - break; - } - } - } - - // Now check if either candidate is relay type - if (selectedLocalCandidateId != null || selectedRemoteCandidateId != null) { - for (Map.Entry entry : statsMap.entrySet()) { - RTCStats stats = entry.getValue(); - String id = stats.getId(); - - if (id.equals(selectedLocalCandidateId) || id.equals(selectedRemoteCandidateId)) { - if ("local-candidate".equals(stats.getType()) || - "remote-candidate".equals(stats.getType())) { - - Map members = stats.getMembers(); - String candidateType = (String) members.get("candidateType"); - - if ("relay".equals(candidateType)) { - relayUsed = true; - break; + // Check if this pair is selected/nominated + Object state = members.get("state"); + if ("succeeded".equals(state) + || Boolean.TRUE.equals(members.get("nominated"))) { + selectedLocalCandidateId = (String) members.get("localCandidateId"); + selectedRemoteCandidateId = (String) members.get("remoteCandidateId"); + break; + } + } } - } - } - } - } - boolean finalRelayUsed = relayUsed; - mainHandler.post(() -> callbacks.onRelayUsageChanged(finalRelayUsed)); + // Now check if either candidate is relay type + if (selectedLocalCandidateId != null || selectedRemoteCandidateId != null) { + for (Map.Entry entry : statsMap.entrySet()) { + RTCStats stats = entry.getValue(); + String id = stats.getId(); - Log.d(TAG, "Relay usage detected: " + finalRelayUsed); - }); - }, 500); + if (id.equals(selectedLocalCandidateId) + || id.equals(selectedRemoteCandidateId)) { + if ("local-candidate".equals(stats.getType()) + || "remote-candidate".equals(stats.getType())) { + + Map members = stats.getMembers(); + String candidateType = (String) members.get("candidateType"); + + if ("relay".equals(candidateType)) { + relayUsed = true; + break; + } + } + } + } + } + + boolean finalRelayUsed = relayUsed; + mainHandler.post(() -> callbacks.onRelayUsageChanged(finalRelayUsed)); + + Log.d(TAG, "Relay usage detected: " + finalRelayUsed); + }); + }, + 500); } // Cleanup diff --git a/src/main/res/drawable/ic_bluetooth_audio.xml b/src/main/res/drawable/ic_bluetooth_audio.xml index 784198e2e..c65875ca5 100644 --- a/src/main/res/drawable/ic_bluetooth_audio.xml +++ b/src/main/res/drawable/ic_bluetooth_audio.xml @@ -1,10 +1,11 @@ - - + diff --git a/src/main/res/drawable/ic_call.xml b/src/main/res/drawable/ic_call.xml index cdfabff84..4e09c3dc3 100644 --- a/src/main/res/drawable/ic_call.xml +++ b/src/main/res/drawable/ic_call.xml @@ -1,10 +1,11 @@ - - + diff --git a/src/main/res/drawable/ic_call_end.xml b/src/main/res/drawable/ic_call_end.xml index d1952da31..956553221 100644 --- a/src/main/res/drawable/ic_call_end.xml +++ b/src/main/res/drawable/ic_call_end.xml @@ -1,10 +1,11 @@ - - + diff --git a/src/main/res/drawable/ic_cast.xml b/src/main/res/drawable/ic_cast.xml index 8ac046129..4de746f12 100644 --- a/src/main/res/drawable/ic_cast.xml +++ b/src/main/res/drawable/ic_cast.xml @@ -1,10 +1,11 @@ - - + diff --git a/src/main/res/drawable/ic_check.xml b/src/main/res/drawable/ic_check.xml index 8d84fb7ed..b381ab85e 100644 --- a/src/main/res/drawable/ic_check.xml +++ b/src/main/res/drawable/ic_check.xml @@ -1,10 +1,11 @@ - - + diff --git a/src/main/res/drawable/ic_headset.xml b/src/main/res/drawable/ic_headset.xml index bef9a86c8..a41eae834 100644 --- a/src/main/res/drawable/ic_headset.xml +++ b/src/main/res/drawable/ic_headset.xml @@ -1,10 +1,11 @@ - - + diff --git a/src/main/res/drawable/ic_mic_off.xml b/src/main/res/drawable/ic_mic_off.xml index eb8b20892..92c6d0d34 100644 --- a/src/main/res/drawable/ic_mic_off.xml +++ b/src/main/res/drawable/ic_mic_off.xml @@ -1,10 +1,11 @@ - - + diff --git a/src/main/res/drawable/ic_mic_on.xml b/src/main/res/drawable/ic_mic_on.xml index 7d2e09902..d2491ebb5 100644 --- a/src/main/res/drawable/ic_mic_on.xml +++ b/src/main/res/drawable/ic_mic_on.xml @@ -1,10 +1,11 @@ - - + diff --git a/src/main/res/drawable/ic_person.xml b/src/main/res/drawable/ic_person.xml index 4ac431fb0..9aa4908a1 100644 --- a/src/main/res/drawable/ic_person.xml +++ b/src/main/res/drawable/ic_person.xml @@ -1,10 +1,11 @@ - - + diff --git a/src/main/res/drawable/ic_phone_in_talk.xml b/src/main/res/drawable/ic_phone_in_talk.xml index 0609963b1..2909de78b 100644 --- a/src/main/res/drawable/ic_phone_in_talk.xml +++ b/src/main/res/drawable/ic_phone_in_talk.xml @@ -1,10 +1,11 @@ - - + diff --git a/src/main/res/drawable/ic_switch_camera.xml b/src/main/res/drawable/ic_switch_camera.xml index 62f2207a1..065b2d324 100644 --- a/src/main/res/drawable/ic_switch_camera.xml +++ b/src/main/res/drawable/ic_switch_camera.xml @@ -1,10 +1,11 @@ - - + diff --git a/src/main/res/drawable/ic_videocam_off.xml b/src/main/res/drawable/ic_videocam_off.xml index f8fad1f90..49ce05ef8 100644 --- a/src/main/res/drawable/ic_videocam_off.xml +++ b/src/main/res/drawable/ic_videocam_off.xml @@ -1,10 +1,11 @@ - - + diff --git a/src/main/res/drawable/ic_videocam_on.xml b/src/main/res/drawable/ic_videocam_on.xml index 8c92b49d6..6177960ab 100644 --- a/src/main/res/drawable/ic_videocam_on.xml +++ b/src/main/res/drawable/ic_videocam_on.xml @@ -1,10 +1,11 @@ - - + diff --git a/src/main/res/drawable/ic_volume_up.xml b/src/main/res/drawable/ic_volume_up.xml index bc9c5c827..707e0420c 100644 --- a/src/main/res/drawable/ic_volume_up.xml +++ b/src/main/res/drawable/ic_volume_up.xml @@ -1,11 +1,12 @@ - - + diff --git a/src/main/res/layout/dialog_audio_device_picker.xml b/src/main/res/layout/dialog_audio_device_picker.xml index ee1073b81..7ea839698 100644 --- a/src/main/res/layout/dialog_audio_device_picker.xml +++ b/src/main/res/layout/dialog_audio_device_picker.xml @@ -1,9 +1,10 @@ - + - + diff --git a/src/main/res/layout/item_audio_device.xml b/src/main/res/layout/item_audio_device.xml index 8a26eb61f..6deb65458 100644 --- a/src/main/res/layout/item_audio_device.xml +++ b/src/main/res/layout/item_audio_device.xml @@ -1,13 +1,14 @@ - + - + diff --git a/src/main/res/values/themes.xml b/src/main/res/values/themes.xml index 972b065e1..9254d46ca 100644 --- a/src/main/res/values/themes.xml +++ b/src/main/res/values/themes.xml @@ -270,7 +270,9 @@ true -