From 84c35c7483958a2cd2f9b8d7c0f1a02eface2fcf Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Sat, 16 May 2020 18:56:12 +0200 Subject: [PATCH 01/41] replace global calls to MessageNotifierCompat with MsgNotificationManager --- .../securesms/ApplicationContext.java | 2 - .../securesms/ConversationActivity.java | 9 ++--- .../securesms/ConversationListFragment.java | 5 +-- .../connect/ApplicationDcContext.java | 7 ++-- .../notifications/MsgNotificationManager.java | 37 +++++++++++++++++++ .../NotificationsPreferenceFragment.java | 22 +---------- 6 files changed, 48 insertions(+), 34 deletions(-) create mode 100644 src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java diff --git a/src/org/thoughtcrime/securesms/ApplicationContext.java b/src/org/thoughtcrime/securesms/ApplicationContext.java index 7884b6349..0d9e60060 100644 --- a/src/org/thoughtcrime/securesms/ApplicationContext.java +++ b/src/org/thoughtcrime/securesms/ApplicationContext.java @@ -27,7 +27,6 @@ import org.thoughtcrime.securesms.connect.NetworkStateReceiver; import org.thoughtcrime.securesms.crypto.PRNGFixes; import org.thoughtcrime.securesms.geolocation.DcLocationManager; import org.thoughtcrime.securesms.jobmanager.JobManager; -import org.thoughtcrime.securesms.notifications.MessageNotifierCompat; import org.thoughtcrime.securesms.util.AndroidSignalProtocolLogger; import org.thoughtcrime.securesms.util.DynamicLanguage; import org.thoughtcrime.securesms.util.ScreenLockUtil; @@ -72,7 +71,6 @@ public class ApplicationContext extends MultiDexApplication implements DefaultLi initializeLogging(); initializeJobManager(); ProcessLifecycleOwner.get().getLifecycle().addObserver(this); - MessageNotifierCompat.init(this); dcLocationManager = new DcLocationManager(this); try { diff --git a/src/org/thoughtcrime/securesms/ConversationActivity.java b/src/org/thoughtcrime/securesms/ConversationActivity.java index 0981c14e5..1aab93d25 100644 --- a/src/org/thoughtcrime/securesms/ConversationActivity.java +++ b/src/org/thoughtcrime/securesms/ConversationActivity.java @@ -93,7 +93,6 @@ import org.thoughtcrime.securesms.mms.GlideRequests; import org.thoughtcrime.securesms.mms.MediaConstraints; import org.thoughtcrime.securesms.mms.PartAuthority; import org.thoughtcrime.securesms.mms.SlideDeck; -import org.thoughtcrime.securesms.notifications.MessageNotifierCompat; import org.thoughtcrime.securesms.permissions.Permissions; import org.thoughtcrime.securesms.providers.PersistentBlobProvider; import org.thoughtcrime.securesms.recipients.Recipient; @@ -302,14 +301,14 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity titleView.setTitle(glideRequests, dcChat); - MessageNotifierCompat.updateVisibleChat(chatId); + dcContext.notificationManger.updateVisibleChat(chatId); } @Override protected void onPause() { super.onPause(); processComposeControls(ACTION_SAVE_DRAFT); - MessageNotifierCompat.updateVisibleChat(MessageNotifierCompat.NO_VISIBLE_CHAT_ID); + dcContext.notificationManger.updateVisibleChat(0); if (isFinishing()) overridePendingTransition(R.anim.fade_scale_in, R.anim.slide_to_right); quickAttachmentDrawer.onPause(); inputPanel.onPause(); @@ -1224,7 +1223,7 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity if (refreshFragment) { fragment.reload(recipient, chatId); - MessageNotifierCompat.updateVisibleChat(chatId); + dcContext.notificationManger.updateVisibleChat(chatId); } fragment.scrollToBottom(); @@ -1443,7 +1442,7 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity } else { processComposeControls(ACTION_SEND_OUT); - MessageNotifierCompat.playSendSound(); + dcContext.notificationManger.playSendSound(); } } diff --git a/src/org/thoughtcrime/securesms/ConversationListFragment.java b/src/org/thoughtcrime/securesms/ConversationListFragment.java index 207e6c5b6..e4a9275b9 100644 --- a/src/org/thoughtcrime/securesms/ConversationListFragment.java +++ b/src/org/thoughtcrime/securesms/ConversationListFragment.java @@ -62,7 +62,6 @@ import org.thoughtcrime.securesms.connect.ApplicationDcContext; import org.thoughtcrime.securesms.connect.DcChatlistLoader; import org.thoughtcrime.securesms.connect.DcHelper; import org.thoughtcrime.securesms.mms.GlideApp; -import org.thoughtcrime.securesms.notifications.MessageNotifierCompat; import org.thoughtcrime.securesms.util.Prefs; import org.thoughtcrime.securesms.util.ViewUtil; import org.thoughtcrime.securesms.util.guava.Optional; @@ -294,7 +293,7 @@ public class ConversationListFragment extends Fragment @SuppressLint("StaticFieldLeak") private void handleDeleteAllSelected() { - final DcContext dcContext = DcHelper.getContext(getActivity()); + final ApplicationDcContext dcContext = DcHelper.getContext(getActivity()); int conversationsCount = getListAdapter().getBatchSelections().size(); AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); alert.setMessage(getActivity().getResources().getQuantityString(R.plurals.ask_delete_chat, @@ -324,7 +323,7 @@ public class ConversationListFragment extends Fragment dcContext.marknoticedContact(getListAdapter().getDeaddropContactId()); } else { - MessageNotifierCompat.removeNotifications((int) chatId); + dcContext.notificationManger.removeNotifications((int) chatId); dcContext.deleteChat((int) chatId); } } diff --git a/src/org/thoughtcrime/securesms/connect/ApplicationDcContext.java b/src/org/thoughtcrime/securesms/connect/ApplicationDcContext.java index 916f16eaf..5e3ab8d08 100644 --- a/src/org/thoughtcrime/securesms/connect/ApplicationDcContext.java +++ b/src/org/thoughtcrime/securesms/connect/ApplicationDcContext.java @@ -30,7 +30,7 @@ import com.b44t.messenger.DcMsg; import org.thoughtcrime.securesms.BuildConfig; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.database.model.ThreadRecord; -import org.thoughtcrime.securesms.notifications.MessageNotifierCompat; +import org.thoughtcrime.securesms.notifications.MsgNotificationManager; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.util.Prefs; import org.thoughtcrime.securesms.util.Util; @@ -53,6 +53,7 @@ public class ApplicationDcContext extends DcContext { public static final int RECIPIENT_TYPE_CONTACT = 1; public Context context; + public MsgNotificationManager notificationManger; public ApplicationDcContext(Context context) { super("Android "+BuildConfig.VERSION_NAME); @@ -121,6 +122,7 @@ public class ApplicationDcContext extends DcContext { Log.e(TAG, "Cannot create wakeLocks"); } + notificationManger = new MsgNotificationManager(this); startThreads(0); } @@ -578,13 +580,12 @@ public class ApplicationDcContext extends DcContext { break; case DC_EVENT_INCOMING_MSG: - MessageNotifierCompat.updateNotification((int) data1, (int) data2); // updateNotification() makes sure to run in the correct thread + Util.runOnAnyBackgroundThread(() -> notificationManger.addNotification((int) data1, (int) data2)); if (eventCenter != null) { eventCenter.sendToObservers(event, data1, data2); // Other parts of the code are also interested in this event } break; - default: { final Object data1obj = data1IsString(event) ? dataToString(data1) : data1; final Object data2obj = data2IsString(event) ? dataToString(data2) : data2; diff --git a/src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java b/src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java new file mode 100644 index 000000000..921b6a6b1 --- /dev/null +++ b/src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java @@ -0,0 +1,37 @@ +package org.thoughtcrime.securesms.notifications; + +import androidx.annotation.NonNull; + +import com.b44t.messenger.DcContext; + +import org.thoughtcrime.securesms.util.Util; + +public class MsgNotificationManager { + @NonNull private DcContext dcContext; + + public MsgNotificationManager(DcContext dcContext) { + this.dcContext = dcContext; + } + + public void addNotification(int chatId, int msgId) { + Util.runOnAnyBackgroundThread(() -> { + + }); + } + + public void removeNotifications(int chatId) { + Util.runOnAnyBackgroundThread(() -> { + + }); + } + + public void updateVisibleChat(int chatId) { + Util.runOnAnyBackgroundThread(() -> { + removeNotifications(chatId); + }); + } + + public void playSendSound() { + + } +} diff --git a/src/org/thoughtcrime/securesms/preferences/NotificationsPreferenceFragment.java b/src/org/thoughtcrime/securesms/preferences/NotificationsPreferenceFragment.java index 0b0a5e76b..8178ca0bb 100644 --- a/src/org/thoughtcrime/securesms/preferences/NotificationsPreferenceFragment.java +++ b/src/org/thoughtcrime/securesms/preferences/NotificationsPreferenceFragment.java @@ -1,12 +1,10 @@ package org.thoughtcrime.securesms.preferences; -import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; -import android.os.AsyncTask; import android.os.Bundle; import android.provider.Settings; import androidx.annotation.Nullable; @@ -18,7 +16,6 @@ import android.text.TextUtils; import org.thoughtcrime.securesms.ApplicationPreferencesActivity; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.connect.KeepAliveService; -import org.thoughtcrime.securesms.notifications.MessageNotifierCompat; import org.thoughtcrime.securesms.util.Prefs; import static android.app.Activity.RESULT_OK; @@ -40,7 +37,7 @@ public class NotificationsPreferenceFragment extends ListSummaryPreferenceFragme this.findPreference(Prefs.RINGTONE_PREF) .setOnPreferenceChangeListener(new RingtoneSummaryListener()); this.findPreference(Prefs.NOTIFICATION_PRIVACY_PREF) - .setOnPreferenceChangeListener(new NotificationPrivacyListener()); + .setOnPreferenceChangeListener(new ListSummaryListener()); this.findPreference(Prefs.NOTIFICATION_PRIORITY_PREF) .setOnPreferenceChangeListener(new ListSummaryListener()); @@ -151,21 +148,4 @@ public class NotificationsPreferenceFragment extends ListSummaryPreferenceFragme String ret = context.getString(notificationsEnabled ? R.string.on : R.string.off); return ret; } - - private class NotificationPrivacyListener extends ListSummaryListener { - @SuppressLint("StaticFieldLeak") - @Override - public boolean onPreferenceChange(Preference preference, Object value) { - new AsyncTask() { - @Override - protected Void doInBackground(Void... params) { - MessageNotifierCompat.onNotificationPrivacyChanged(); - return null; - } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - - return super.onPreferenceChange(preference, value); - } - - } } From 48f16934208f8c1defcdfca93f35425025619f93 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Sat, 16 May 2020 19:48:06 +0200 Subject: [PATCH 02/41] move in-chat sounds to InChatSounds class --- .../securesms/ApplicationContext.java | 2 + .../securesms/ConversationActivity.java | 3 +- .../securesms/notifications/InChatSounds.java | 61 +++++++++++++++++++ .../notifications/MsgNotificationManager.java | 28 ++++++--- 4 files changed, 85 insertions(+), 9 deletions(-) create mode 100644 src/org/thoughtcrime/securesms/notifications/InChatSounds.java diff --git a/src/org/thoughtcrime/securesms/ApplicationContext.java b/src/org/thoughtcrime/securesms/ApplicationContext.java index 0d9e60060..bde9c3b0d 100644 --- a/src/org/thoughtcrime/securesms/ApplicationContext.java +++ b/src/org/thoughtcrime/securesms/ApplicationContext.java @@ -27,6 +27,7 @@ import org.thoughtcrime.securesms.connect.NetworkStateReceiver; import org.thoughtcrime.securesms.crypto.PRNGFixes; import org.thoughtcrime.securesms.geolocation.DcLocationManager; import org.thoughtcrime.securesms.jobmanager.JobManager; +import org.thoughtcrime.securesms.notifications.InChatSounds; import org.thoughtcrime.securesms.util.AndroidSignalProtocolLogger; import org.thoughtcrime.securesms.util.DynamicLanguage; import org.thoughtcrime.securesms.util.ScreenLockUtil; @@ -71,6 +72,7 @@ public class ApplicationContext extends MultiDexApplication implements DefaultLi initializeLogging(); initializeJobManager(); ProcessLifecycleOwner.get().getLifecycle().addObserver(this); + InChatSounds.getInstance(this); dcLocationManager = new DcLocationManager(this); try { diff --git a/src/org/thoughtcrime/securesms/ConversationActivity.java b/src/org/thoughtcrime/securesms/ConversationActivity.java index 1aab93d25..546f8d43d 100644 --- a/src/org/thoughtcrime/securesms/ConversationActivity.java +++ b/src/org/thoughtcrime/securesms/ConversationActivity.java @@ -93,6 +93,7 @@ import org.thoughtcrime.securesms.mms.GlideRequests; import org.thoughtcrime.securesms.mms.MediaConstraints; import org.thoughtcrime.securesms.mms.PartAuthority; import org.thoughtcrime.securesms.mms.SlideDeck; +import org.thoughtcrime.securesms.notifications.InChatSounds; import org.thoughtcrime.securesms.permissions.Permissions; import org.thoughtcrime.securesms.providers.PersistentBlobProvider; import org.thoughtcrime.securesms.recipients.Recipient; @@ -1442,7 +1443,7 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity } else { processComposeControls(ACTION_SEND_OUT); - dcContext.notificationManger.playSendSound(); + InChatSounds.getInstance(ConversationActivity.this).playSendSound(); } } diff --git a/src/org/thoughtcrime/securesms/notifications/InChatSounds.java b/src/org/thoughtcrime/securesms/notifications/InChatSounds.java new file mode 100644 index 000000000..7a40dda29 --- /dev/null +++ b/src/org/thoughtcrime/securesms/notifications/InChatSounds.java @@ -0,0 +1,61 @@ +package org.thoughtcrime.securesms.notifications; + +import android.content.Context; +import android.media.AudioManager; +import android.media.SoundPool; +import android.util.Log; + +import org.thoughtcrime.securesms.R; +import org.thoughtcrime.securesms.util.Prefs; + +public class InChatSounds { + private static final String TAG = InChatSounds.class.getSimpleName(); + private static volatile InChatSounds instance; + + private Context appContext = null; + private SoundPool soundPool = null; + private int soundIn = 0; + private int soundOut = 0; + + static public InChatSounds getInstance(Context context) { + if (instance == null) { + synchronized (InChatSounds.class) { + if (instance == null) { + instance = new InChatSounds(context); + } + } + } + return instance; + } + + private InChatSounds(Context context) { + try { + appContext = context.getApplicationContext(); + soundPool = new SoundPool(3, AudioManager.STREAM_SYSTEM, 0); + soundIn = soundPool.load(context, R.raw.sound_in, 1); + soundOut = soundPool.load(context, R.raw.sound_out, 1); + } catch(Exception e) { + Log.e(TAG, "cannot initialize sounds", e); + } + } + + public void playSendSound() { + try { + if (Prefs.isInChatNotifications(appContext)) { + soundPool.play(soundOut, 1.0f, 1.0f, 1, 0, 1.0f); + } + } catch(Exception e) { + Log.e(TAG, "cannot play send sound", e); + } + } + + public void playIncomingSound() { + try { + if (Prefs.isInChatNotifications(appContext)) { + soundPool.play(soundIn, 1.0f, 1.0f, 1, 0, 1.0f); + } + } catch(Exception e) { + Log.e(TAG, "cannot play incoming sound", e); + } + } +} diff --git a/src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java b/src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java index 921b6a6b1..8a5f9e84c 100644 --- a/src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java +++ b/src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java @@ -1,21 +1,34 @@ package org.thoughtcrime.securesms.notifications; +import android.util.Log; + import androidx.annotation.NonNull; -import com.b44t.messenger.DcContext; - +import org.thoughtcrime.securesms.connect.ApplicationDcContext; +import org.thoughtcrime.securesms.util.Prefs; import org.thoughtcrime.securesms.util.Util; public class MsgNotificationManager { - @NonNull private DcContext dcContext; + private static final String TAG = InChatSounds.class.getSimpleName(); + @NonNull private ApplicationDcContext dcContext; + private volatile int visibleChatId = 0; - public MsgNotificationManager(DcContext dcContext) { + public MsgNotificationManager(ApplicationDcContext dcContext) { this.dcContext = dcContext; } public void addNotification(int chatId, int msgId) { Util.runOnAnyBackgroundThread(() -> { + if (Prefs.isChatMuted(dcContext.context, chatId)) { + return; + } + + if (chatId == visibleChatId) { + InChatSounds.getInstance(dcContext.context).playIncomingSound(); + return; + } + }); } @@ -27,11 +40,10 @@ public class MsgNotificationManager { public void updateVisibleChat(int chatId) { Util.runOnAnyBackgroundThread(() -> { + + visibleChatId = chatId; removeNotifications(chatId); + }); } - - public void playSendSound() { - - } } From 14289db25dfe2948e5d32642beccf55faf546151 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Sun, 17 May 2020 02:39:43 +0200 Subject: [PATCH 03/41] make basic notifications work --- .../securesms/connect/KeepAliveService.java | 2 +- .../notifications/MsgNotificationManager.java | 131 ++++++++++++++++++ 2 files changed, 132 insertions(+), 1 deletion(-) diff --git a/src/org/thoughtcrime/securesms/connect/KeepAliveService.java b/src/org/thoughtcrime/securesms/connect/KeepAliveService.java index 4a672dd6e..f04d194a2 100644 --- a/src/org/thoughtcrime/securesms/connect/KeepAliveService.java +++ b/src/org/thoughtcrime/securesms/connect/KeepAliveService.java @@ -93,7 +93,7 @@ public class KeepAliveService extends Service { * Delta Chat won't get new messages reliable **********************************************************************************************/ - public static final int FG_NOTIFICATION_ID = 4142; + public static final int FG_NOTIFICATION_ID = 1; // given to NotificationManagerCompat.notify(); for normal notifications, we use msgId>=10 private Notification createNotification() { Intent intent = new Intent(this, ConversationListActivity.class); diff --git a/src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java b/src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java index 8a5f9e84c..2d10bc8a3 100644 --- a/src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java +++ b/src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java @@ -1,22 +1,142 @@ package org.thoughtcrime.securesms.notifications; +import android.app.NotificationChannel; +import android.app.NotificationManager; +import android.content.Context; +import android.graphics.Color; +import android.media.AudioAttributes; +import android.net.Uri; +import android.os.Build; +import android.text.TextUtils; import android.util.Log; import androidx.annotation.NonNull; +import androidx.core.app.NotificationCompat; +import androidx.core.app.NotificationManagerCompat; +import com.b44t.messenger.DcChat; +import com.b44t.messenger.DcMsg; + +import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.connect.ApplicationDcContext; import org.thoughtcrime.securesms.util.Prefs; import org.thoughtcrime.securesms.util.Util; +import java.math.BigInteger; +import java.security.MessageDigest; +import java.util.List; + public class MsgNotificationManager { private static final String TAG = InChatSounds.class.getSimpleName(); @NonNull private ApplicationDcContext dcContext; + @NonNull private Context context; private volatile int visibleChatId = 0; public MsgNotificationManager(ApplicationDcContext dcContext) { this.dcContext = dcContext; + this.context = dcContext.context.getApplicationContext(); } + + // handle notification channels + // -------------------------------------------------------------------------------------------- + + // - since oreo, a NotificationChannel is a MUST + // - NotificationChannels have default values that have a higher precedence as the Notification.Builder setting + // - once created, NotificationChannels cannot be modified programmatically + // - NotificationChannels can be deleted, however, on re-creation it becomes un-deleted with the old settings + // - the idea is that sound and vibrate are handled outside of the scope of the notification channel + + private boolean notificationChannelsSupported() { + return Build.VERSION.SDK_INT >= 26; + } + + private String getNotificationChannel(NotificationManagerCompat notificationManager) { + final String chBase = "ch_msg4_"; + String chId = chBase + "unsupported"; + + if(notificationChannelsSupported()) { + try { + // get all values we'll use as settings for the NotificationChannel + String ledColor = Prefs.getNotificationLedColor(context); + boolean defaultVibrate = Prefs.isNotificationVibrateEnabled(context); + Uri ringtone = Prefs.getNotificationRingtone(context); + + // compute hash from these settings + String hash = ""; + MessageDigest md = MessageDigest.getInstance("SHA-256"); + md.update(ledColor.getBytes()); + md.update(defaultVibrate ? (byte) 1 : (byte) 0); + md.update(ringtone.toString().getBytes()); + hash = String.format("%X", new BigInteger(1, md.digest())).substring(0, 16); + + // get channel name + chId = chBase + hash; + String oldChId = Prefs.getStringPreference(context, "ch_curr_" + chBase, ""); + if (!oldChId.equals(chId)) { + try { + notificationManager.deleteNotificationChannel(oldChId); + } + catch (Exception e) { + // channel not created before + } + Prefs.setStringPreference(context, "ch_curr_" + chBase, chId); + } + + // 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++) { + if (chId.equals(channels.get(i).getId())) { + channelExists = true; + } + } + + // 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(chId, + "New messages", NotificationManager.IMPORTANCE_HIGH); + channel.setDescription("Informs about new messages."); + + if (!ledColor.equals("none")) { + channel.enableLights(true); + int argb; + try { + argb = Color.parseColor(ledColor); + } + catch (Exception e) { + argb = Color.rgb(0xFF, 0xFF, 0xFF); + } + channel.setLightColor(argb); + } else { + channel.enableLights(false); + } + + channel.enableVibration(defaultVibrate); + + if (!TextUtils.isEmpty(ringtone.toString())) { + channel.setSound(ringtone, + new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN) + .setUsage(AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT) + .build()); + } + + notificationManager.createNotificationChannel(channel); + } + } + catch(Exception e) { + e.printStackTrace(); + } + } + + return chId; + } + + + // add notifications & co. + // -------------------------------------------------------------------------------------------- + public void addNotification(int chatId, int msgId) { Util.runOnAnyBackgroundThread(() -> { @@ -29,6 +149,17 @@ public class MsgNotificationManager { return; } + NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); + + NotificationCompat.Builder builder = new NotificationCompat.Builder(context, getNotificationChannel(notificationManager)) + .setSmallIcon(R.drawable.icon_notification) + .setColor(context.getResources().getColor(R.color.delta_primary)) + .setPriority(Prefs.getNotificationPriority(context)) + .setCategory(NotificationCompat.CATEGORY_MESSAGE) + .setContentTitle(dcContext.getChat(chatId).getName()) + .setContentText(dcContext.getMsg(msgId).getSummarytext(100)); + + notificationManager.notify(msgId, builder.build()); }); } From 9563000da7e9a9c15c35d62d2217ec1cb34d7b4e Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Sun, 17 May 2020 17:37:48 +0200 Subject: [PATCH 04/41] set sound/vibrate/led for systems Date: Sun, 17 May 2020 19:07:16 +0200 Subject: [PATCH 05/41] just delete all unused channels --- .../notifications/MsgNotificationManager.java | 59 +++++++++++++------ 1 file changed, 41 insertions(+), 18 deletions(-) diff --git a/src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java b/src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java index f139baf1c..0836578b4 100644 --- a/src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java +++ b/src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java @@ -61,6 +61,13 @@ public class MsgNotificationManager { return Prefs.isNotificationVibrateEnabled(context); } + private boolean requiresIndependentChannel(int chatId) { + if (Prefs.getChatRingtone(context, chatId)!=null || Prefs.getChatVibrate(context, chatId)!=Prefs.VibrateState.DEFAULT) { + return true; + } + return false; + } + private int getLedArgb(String ledColor) { int argb; try { @@ -83,13 +90,35 @@ public class MsgNotificationManager { // - NotificationChannels can be deleted, however, on re-creation it becomes un-deleted with the old settings // - the idea is that sound and vibrate are handled outside of the scope of the notification channel + // our Channel-IDs have the format ""ch_msgV_HASH" or "ch_msgV_HASH.CHATID" + // note, that there are other Channel-IDs as "dc_foreground_notification_ch" + static private final String CH_PREFIX = "ch_msg"; + static private final String CH_VERSION = "4"; + private boolean notificationChannelsSupported() { return Build.VERSION.SDK_INT >= 26; } + private boolean isNotificationChannelInUse(String chId) { + try { + if (chId.startsWith(CH_PREFIX + CH_VERSION)) { + int point = chId.lastIndexOf("."); + if (point == -1) { + return true; // this is the current standard channel for all chats that do not have explicit sound/vibrate set + } else { + int chatId = Integer.parseInt(chId.substring(point + 1)); + if (requiresIndependentChannel(chatId)) { + return true; // this is a channel for a chat with explicit sound/vibrate set + } + + } + } + } catch(Exception e) { } + return false; + } + private String getNotificationChannel(NotificationManagerCompat notificationManager) { - final String chBase = "ch_msg4_"; - String chId = chBase + "unsupported"; + String chId = CH_PREFIX + CH_VERSION + "_" + "unsupported"; if(notificationChannelsSupported()) { try { @@ -107,27 +136,21 @@ public class MsgNotificationManager { hash = String.format("%X", new BigInteger(1, md.digest())).substring(0, 16); // get channel name - chId = chBase + hash; + chId = CH_PREFIX + CH_VERSION + "_" + hash; - // delete previously used channel, if changed - String oldChId = Prefs.getStringPreference(context, "ch_curr_" + chBase, ""); - if (!oldChId.equals(chId)) { - try { - notificationManager.deleteNotificationChannel(oldChId); - } - catch (Exception e) { - // channel not created before - } - Prefs.setStringPreference(context, "ch_curr_" + chBase, chId); - } - - // check if there is already a channel with the given name + // check if there is already a channel with the given name, + // delete unused `ch_msg` channel names (keep others as `dc_foreground_notification_ch`) List channels = notificationManager.getNotificationChannels(); boolean channelExists = false; for (int i = 0; i < channels.size(); i++) { - if (chId.equals(channels.get(i).getId())) { + String testChId = channels.get(i).getId(); + if (chId.equals(testChId)) { channelExists = true; - break; + } else if (testChId.startsWith(CH_PREFIX) && !isNotificationChannelInUse(testChId)) { + try { + notificationManager.deleteNotificationChannel(testChId); + } + catch (Exception e) { } } } From fd4404c1e304b0b8feb0845fc8b6fa7e87988fe6 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Sun, 17 May 2020 19:22:56 +0200 Subject: [PATCH 06/41] allow chat-specific sounds+vibrate by creating channels as needed --- .../notifications/MsgNotificationManager.java | 45 ++++++++++++------- 1 file changed, 30 insertions(+), 15 deletions(-) diff --git a/src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java b/src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java index 0836578b4..69d87bba9 100644 --- a/src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java +++ b/src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java @@ -117,15 +117,17 @@ public class MsgNotificationManager { return false; } - private String getNotificationChannel(NotificationManagerCompat notificationManager) { - String chId = CH_PREFIX + CH_VERSION + "_" + "unsupported"; + private String getNotificationChannel(NotificationManagerCompat notificationManager, DcChat dcChat) { + int chatId = dcChat.getId(); + String channelId = CH_PREFIX + CH_VERSION + "_" + "unsupported"; if(notificationChannelsSupported()) { try { // get all values we'll use as settings for the NotificationChannel String ledColor = Prefs.getNotificationLedColor(context); - boolean defaultVibrate = Prefs.isNotificationVibrateEnabled(context); - Uri ringtone = Prefs.getNotificationRingtone(context); + boolean defaultVibrate = getEffectiveVibrate(chatId); + Uri ringtone = getEffectiveSound(chatId); + boolean isIndependent = requiresIndependentChannel(chatId); // compute hash from these settings String hash = ""; @@ -135,20 +137,32 @@ public class MsgNotificationManager { md.update(ringtone.toString().getBytes()); hash = String.format("%X", new BigInteger(1, md.digest())).substring(0, 16); - // get channel name - chId = CH_PREFIX + CH_VERSION + "_" + hash; + // get channel id + channelId = CH_PREFIX + CH_VERSION + "_" + hash; + if (isIndependent) { + channelId += String.format(".%d", chatId); + } + + // user-visible name of the channel + String name = "New messages"; + if (isIndependent) { + name = dcChat.getName(); + } // check if there is already a channel with the given name, // delete unused `ch_msg` channel names (keep others as `dc_foreground_notification_ch`) List channels = notificationManager.getNotificationChannels(); boolean channelExists = false; for (int i = 0; i < channels.size(); i++) { - String testChId = channels.get(i).getId(); - if (chId.equals(testChId)) { + String testChannelId = channels.get(i).getId(); + if (channelId.equals(testChannelId)) { channelExists = true; - } else if (testChId.startsWith(CH_PREFIX) && !isNotificationChannelInUse(testChId)) { try { - notificationManager.deleteNotificationChannel(testChId); + channels.get(i).setName(name); + } catch(Exception e) { } + } else if (testChannelId.startsWith(CH_PREFIX) && !isNotificationChannelInUse(testChannelId)) { + try { + notificationManager.deleteNotificationChannel(testChannelId); } catch (Exception e) { } } @@ -157,8 +171,8 @@ public class MsgNotificationManager { // 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(chId, - "New messages", NotificationManager.IMPORTANCE_HIGH); + NotificationChannel channel = new NotificationChannel(channelId, + name, NotificationManager.IMPORTANCE_HIGH); channel.setDescription("Informs about new messages."); if (!ledColor.equals("none")) { @@ -185,7 +199,7 @@ public class MsgNotificationManager { } } - return chId; + return channelId; } @@ -207,12 +221,13 @@ public class MsgNotificationManager { NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); // create a basic notification - NotificationCompat.Builder builder = new NotificationCompat.Builder(context, getNotificationChannel(notificationManager)) + DcChat dcChat = dcContext.getChat(chatId); + NotificationCompat.Builder builder = new NotificationCompat.Builder(context, getNotificationChannel(notificationManager, dcChat)) .setSmallIcon(R.drawable.icon_notification) .setColor(context.getResources().getColor(R.color.delta_primary)) .setPriority(Prefs.getNotificationPriority(context)) .setCategory(NotificationCompat.CATEGORY_MESSAGE) - .setContentTitle(dcContext.getChat(chatId).getName()) + .setContentTitle(dcChat.getName()) .setContentText(dcContext.getMsg(msgId).getSummarytext(100)); // set sound, vibrate, led for systems that do not have notification channels From 1e60eb9c1a2aa31e85bcc8d41e5d7850185a33b7 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Sun, 17 May 2020 22:22:49 +0200 Subject: [PATCH 07/41] just use defaults for led-pattern, it is no longer supported since andoid8; in-chat sounds are independent from global-notification-switch --- res/values/arrays.xml | 12 ------------ res/xml/preferences_notifications.xml | 19 +++++-------------- .../AbstractNotificationBuilder.java | 2 ++ .../NotificationsPreferenceFragment.java | 3 --- .../thoughtcrime/securesms/util/Prefs.java | 12 +----------- 5 files changed, 8 insertions(+), 40 deletions(-) diff --git a/res/values/arrays.xml b/res/values/arrays.xml index de59271f7..508fab4a9 100644 --- a/res/values/arrays.xml +++ b/res/values/arrays.xml @@ -117,18 +117,6 @@ none - - @string/fast - @string/normal - @string/slow - - - - 300,300 - 500,2000 - 3000,3000 - - default custom diff --git a/res/xml/preferences_notifications.xml b/res/xml/preferences_notifications.xml index d451db047..8c885c30e 100644 --- a/res/xml/preferences_notifications.xml +++ b/res/xml/preferences_notifications.xml @@ -35,20 +35,6 @@ android:entries="@array/pref_led_color_entries" android:entryValues="@array/pref_led_color_values" /> - - - - + + diff --git a/src/org/thoughtcrime/securesms/notifications/AbstractNotificationBuilder.java b/src/org/thoughtcrime/securesms/notifications/AbstractNotificationBuilder.java index d436f5c9f..9225cf536 100644 --- a/src/org/thoughtcrime/securesms/notifications/AbstractNotificationBuilder.java +++ b/src/org/thoughtcrime/securesms/notifications/AbstractNotificationBuilder.java @@ -72,6 +72,7 @@ abstract class AbstractNotificationBuilder extends NotificationCompat.Builder { } private void setLed() { + /* String ledColor = Prefs.getNotificationLedColor(context); String ledBlinkPattern = Prefs.getNotificationLedPattern(context); String ledBlinkPatternCustom = Prefs.getNotificationLedPatternCustom(context); @@ -89,6 +90,7 @@ abstract class AbstractNotificationBuilder extends NotificationCompat.Builder { Integer.parseInt(blinkPatternArray[0]), Integer.parseInt(blinkPatternArray[1])); } + */ } void setTicker(@NonNull Recipient recipient, @Nullable CharSequence message) { diff --git a/src/org/thoughtcrime/securesms/preferences/NotificationsPreferenceFragment.java b/src/org/thoughtcrime/securesms/preferences/NotificationsPreferenceFragment.java index 8178ca0bb..5bef4365e 100644 --- a/src/org/thoughtcrime/securesms/preferences/NotificationsPreferenceFragment.java +++ b/src/org/thoughtcrime/securesms/preferences/NotificationsPreferenceFragment.java @@ -32,8 +32,6 @@ public class NotificationsPreferenceFragment extends ListSummaryPreferenceFragme this.findPreference(Prefs.LED_COLOR_PREF) .setOnPreferenceChangeListener(new ListSummaryListener()); - this.findPreference(Prefs.LED_BLINK_PREF) - .setOnPreferenceChangeListener(new ListSummaryListener()); this.findPreference(Prefs.RINGTONE_PREF) .setOnPreferenceChangeListener(new RingtoneSummaryListener()); this.findPreference(Prefs.NOTIFICATION_PRIVACY_PREF) @@ -58,7 +56,6 @@ public class NotificationsPreferenceFragment extends ListSummaryPreferenceFragme }); initializeListSummary((ListPreference) findPreference(Prefs.LED_COLOR_PREF)); - initializeListSummary((ListPreference) findPreference(Prefs.LED_BLINK_PREF)); initializeListSummary((ListPreference) findPreference(Prefs.NOTIFICATION_PRIVACY_PREF)); initializeListSummary((ListPreference) findPreference(Prefs.NOTIFICATION_PRIORITY_PREF)); diff --git a/src/org/thoughtcrime/securesms/util/Prefs.java b/src/org/thoughtcrime/securesms/util/Prefs.java index 3452c8aeb..9bd745d63 100644 --- a/src/org/thoughtcrime/securesms/util/Prefs.java +++ b/src/org/thoughtcrime/securesms/util/Prefs.java @@ -42,9 +42,7 @@ public class Prefs { private static final String CHAT_VIBRATE = "pref_chat_vibrate_"; // followed by chat-id private static final String NOTIFICATION_PREF = "pref_key_enable_notifications"; public static final String LED_COLOR_PREF = "pref_led_color"; - public static final String LED_BLINK_PREF = "pref_led_blink"; - private static final String LED_BLINK_PREF_CUSTOM = "pref_led_blink_custom"; - public static final String CHAT_MUTED_UNTIL = "pref_chat_muted_until_"; // followed by chat-id + public static final String CHAT_MUTED_UNTIL = "pref_chat_muted_until_"; // followed by chat-id private static final String CHAT_RINGTONE = "pref_chat_ringtone_"; // followed by chat-id public static final String SCREEN_LOCK_TIMEOUT_INTERVAL_PREF = "pref_timeout_interval"; public static final String SCREEN_LOCK_TIMEOUT_PREF = "pref_timeout_passphrase"; @@ -269,14 +267,6 @@ public class Prefs { return getStringPreference(context, LED_COLOR_PREF, "blue"); } - public static String getNotificationLedPattern(Context context) { - return getStringPreference(context, LED_BLINK_PREF, "500,2000"); - } - - public static String getNotificationLedPatternCustom(Context context) { - return getStringPreference(context, LED_BLINK_PREF_CUSTOM, "500,2000"); - } - // mute public static void setChatMuteDuration(DcContext context, int chatId, long duration) { From b46fea9529ad048177a3e97cc516522e004a79a5 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Sun, 17 May 2020 22:31:30 +0200 Subject: [PATCH 08/41] rename MsgNotificationManager to NotificationCenter --- .../securesms/connect/ApplicationDcContext.java | 6 +++--- ...{MsgNotificationManager.java => NotificationCenter.java} | 5 ++--- 2 files changed, 5 insertions(+), 6 deletions(-) rename src/org/thoughtcrime/securesms/notifications/{MsgNotificationManager.java => NotificationCenter.java} (98%) diff --git a/src/org/thoughtcrime/securesms/connect/ApplicationDcContext.java b/src/org/thoughtcrime/securesms/connect/ApplicationDcContext.java index 5e3ab8d08..171893842 100644 --- a/src/org/thoughtcrime/securesms/connect/ApplicationDcContext.java +++ b/src/org/thoughtcrime/securesms/connect/ApplicationDcContext.java @@ -30,7 +30,7 @@ import com.b44t.messenger.DcMsg; import org.thoughtcrime.securesms.BuildConfig; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.database.model.ThreadRecord; -import org.thoughtcrime.securesms.notifications.MsgNotificationManager; +import org.thoughtcrime.securesms.notifications.NotificationCenter; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.util.Prefs; import org.thoughtcrime.securesms.util.Util; @@ -53,7 +53,7 @@ public class ApplicationDcContext extends DcContext { public static final int RECIPIENT_TYPE_CONTACT = 1; public Context context; - public MsgNotificationManager notificationManger; + public NotificationCenter notificationManger; public ApplicationDcContext(Context context) { super("Android "+BuildConfig.VERSION_NAME); @@ -122,7 +122,7 @@ public class ApplicationDcContext extends DcContext { Log.e(TAG, "Cannot create wakeLocks"); } - notificationManger = new MsgNotificationManager(this); + notificationManger = new NotificationCenter(this); startThreads(0); } diff --git a/src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java similarity index 98% rename from src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java rename to src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index 69d87bba9..3406d1705 100644 --- a/src/org/thoughtcrime/securesms/notifications/MsgNotificationManager.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -9,7 +9,6 @@ import android.media.AudioAttributes; import android.net.Uri; import android.os.Build; import android.text.TextUtils; -import android.util.Log; import androidx.annotation.NonNull; import androidx.core.app.NotificationCompat; @@ -27,13 +26,13 @@ import java.math.BigInteger; import java.security.MessageDigest; import java.util.List; -public class MsgNotificationManager { +public class NotificationCenter { private static final String TAG = InChatSounds.class.getSimpleName(); @NonNull private ApplicationDcContext dcContext; @NonNull private Context context; private volatile int visibleChatId = 0; - public MsgNotificationManager(ApplicationDcContext dcContext) { + public NotificationCenter(ApplicationDcContext dcContext) { this.dcContext = dcContext; this.context = dcContext.context.getApplicationContext(); } From 6865d812d01a6be59eec5ff0fe88509846994878 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Tue, 19 May 2020 18:37:40 +0200 Subject: [PATCH 09/41] group notifications --- .../notifications/NotificationCenter.java | 24 +++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index 3406d1705..f0398d39e 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -2,6 +2,7 @@ package org.thoughtcrime.securesms.notifications; import android.app.Notification; import android.app.NotificationChannel; +import android.app.NotificationChannelGroup; import android.app.NotificationManager; import android.content.Context; import android.graphics.Color; @@ -116,6 +117,15 @@ public class NotificationCenter { return false; } + private String getNotificationChannelGroup(NotificationManagerCompat notificationManager) { + final String chGrpId = "chgrp_msg"; + if (notificationChannelsSupported() && notificationManager.getNotificationChannelGroup(chGrpId) == null) { + NotificationChannelGroup chGrp = new NotificationChannelGroup(chGrpId, context.getString(R.string.pref_chats)); + notificationManager.createNotificationChannelGroup(chGrp); + } + return chGrpId; + } + private String getNotificationChannel(NotificationManagerCompat notificationManager, DcChat dcChat) { int chatId = dcChat.getId(); String channelId = CH_PREFIX + CH_VERSION + "_" + "unsupported"; @@ -143,7 +153,7 @@ public class NotificationCenter { } // user-visible name of the channel - String name = "New messages"; + String name = context.getString(R.string.def); if (isIndependent) { name = dcChat.getName(); } @@ -157,9 +167,11 @@ public class NotificationCenter { if (channelId.equals(testChannelId)) { channelExists = true; try { + // update the name to reflect localize changes and chat renames channels.get(i).setName(name); } catch(Exception e) { } } else if (testChannelId.startsWith(CH_PREFIX) && !isNotificationChannelInUse(testChannelId)) { + // TODO: outdated un-independent channels are not deleted try { notificationManager.deleteNotificationChannel(testChannelId); } @@ -173,6 +185,7 @@ public class NotificationCenter { NotificationChannel channel = new NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_HIGH); channel.setDescription("Informs about new messages."); + channel.setGroup(getNotificationChannelGroup(notificationManager)); if (!ledColor.equals("none")) { channel.enableLights(true); @@ -208,10 +221,18 @@ public class NotificationCenter { public void addNotification(int chatId, int msgId) { Util.runOnAnyBackgroundThread(() -> { + DcChat dcChat = dcContext.getChat(chatId); + if (Prefs.isChatMuted(dcContext.context, chatId)) { return; } + if (dcChat.isDeviceTalk()) { + // currently, we just never notify on device chat. + // esp. on first start, this is annoying. + return; + } + if (chatId == visibleChatId) { InChatSounds.getInstance(dcContext.context).playIncomingSound(); return; @@ -220,7 +241,6 @@ public class NotificationCenter { NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); // create a basic notification - DcChat dcChat = dcContext.getChat(chatId); NotificationCompat.Builder builder = new NotificationCompat.Builder(context, getNotificationChannel(notificationManager, dcChat)) .setSmallIcon(R.drawable.icon_notification) .setColor(context.getResources().getColor(R.color.delta_primary)) From 6c7a17ac41a4e510e58d06b629ee527821699336 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Tue, 19 May 2020 19:01:37 +0200 Subject: [PATCH 10/41] steamline notification channel names --- .../securesms/connect/KeepAliveService.java | 6 +- .../notifications/NotificationCenter.java | 59 +++++++++++-------- 2 files changed, 37 insertions(+), 28 deletions(-) diff --git a/src/org/thoughtcrime/securesms/connect/KeepAliveService.java b/src/org/thoughtcrime/securesms/connect/KeepAliveService.java index f04d194a2..42f7ab640 100644 --- a/src/org/thoughtcrime/securesms/connect/KeepAliveService.java +++ b/src/org/thoughtcrime/securesms/connect/KeepAliveService.java @@ -15,6 +15,7 @@ import android.util.Log; import org.thoughtcrime.securesms.ConversationListActivity; import org.thoughtcrime.securesms.R; +import org.thoughtcrime.securesms.notifications.NotificationCenter; import org.thoughtcrime.securesms.util.Prefs; public class KeepAliveService extends Service { @@ -112,18 +113,17 @@ public class KeepAliveService extends Service { builder.setSmallIcon(R.drawable.notification_permanent); if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O) { createFgNotificationChannel(this); - builder.setChannelId(FG_CHANNEL_ID); + builder.setChannelId(NotificationCenter.CH_PERMANENT_NOTIFICATION); } return builder.build(); } private static boolean ch_created = false; - private static final String FG_CHANNEL_ID = "dc_foreground_notification_ch"; @TargetApi(Build.VERSION_CODES.O) static private void createFgNotificationChannel(Context context) { if(!ch_created) { ch_created = true; - NotificationChannel channel = new NotificationChannel(FG_CHANNEL_ID, + NotificationChannel channel = new NotificationChannel(NotificationCenter.CH_PERMANENT_NOTIFICATION, "Receive messages in background.", NotificationManager.IMPORTANCE_MIN); // IMPORTANCE_DEFAULT will play a sound channel.setDescription("Ensure reliable message receiving."); NotificationManager notificationManager = context.getSystemService(NotificationManager.class); diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index f0398d39e..8b153579f 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -81,19 +81,27 @@ public class NotificationCenter { - // handle notification channels + // Notification channels // -------------------------------------------------------------------------------------------- - // - since oreo, a NotificationChannel is a MUST - // - NotificationChannels have default values that have a higher precedence as the Notification.Builder setting + // 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 it becomes un-deleted with the old settings - // - the idea is that sound and vibrate are handled outside of the scope of the notification channel + // - 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 - // our Channel-IDs have the format ""ch_msgV_HASH" or "ch_msgV_HASH.CHATID" - // note, that there are other Channel-IDs as "dc_foreground_notification_ch" - static private final String CH_PREFIX = "ch_msg"; - static private final String CH_VERSION = "4"; + // 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"; // full name is "ch_msgV_HASH" or "ch_msgV_HASH.CHATID" + public static final String CH_MSG_VERSION = "4"; + public static final String CH_PERMANENT_NOTIFICATION = "dc_foreground_notification_ch"; private boolean notificationChannelsSupported() { return Build.VERSION.SDK_INT >= 26; @@ -101,7 +109,7 @@ public class NotificationCenter { private boolean isNotificationChannelInUse(String chId) { try { - if (chId.startsWith(CH_PREFIX + CH_VERSION)) { + if (chId.startsWith(CH_MSG_PREFIX + CH_MSG_VERSION)) { int point = chId.lastIndexOf("."); if (point == -1) { return true; // this is the current standard channel for all chats that do not have explicit sound/vibrate set @@ -128,15 +136,15 @@ public class NotificationCenter { private String getNotificationChannel(NotificationManagerCompat notificationManager, DcChat dcChat) { int chatId = dcChat.getId(); - String channelId = CH_PREFIX + CH_VERSION + "_" + "unsupported"; + String channelId = CH_MSG_PREFIX + CH_MSG_VERSION + "_" + "unsupported"; if(notificationChannelsSupported()) { try { // get all values we'll use as settings for the NotificationChannel - String ledColor = Prefs.getNotificationLedColor(context); + String ledColor = Prefs.getNotificationLedColor(context); boolean defaultVibrate = getEffectiveVibrate(chatId); - Uri ringtone = getEffectiveSound(chatId); - boolean isIndependent = requiresIndependentChannel(chatId); + Uri ringtone = getEffectiveSound(chatId); + boolean isIndependent = requiresIndependentChannel(chatId); // compute hash from these settings String hash = ""; @@ -147,12 +155,14 @@ public class NotificationCenter { hash = String.format("%X", new BigInteger(1, md.digest())).substring(0, 16); // get channel id - channelId = CH_PREFIX + CH_VERSION + "_" + hash; + channelId = CH_MSG_PREFIX + CH_MSG_VERSION + "_" + hash; if (isIndependent) { channelId += String.format(".%d", chatId); } - // user-visible name of the channel + // 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(); @@ -163,17 +173,18 @@ public class NotificationCenter { List channels = notificationManager.getNotificationChannels(); boolean channelExists = false; for (int i = 0; i < channels.size(); i++) { - String testChannelId = channels.get(i).getId(); - if (channelId.equals(testChannelId)) { + NotificationChannel currChannel = channels.get(i); + String currChannelId = currChannel.getId(); + if (channelId.equals(currChannelId)) { channelExists = true; try { // update the name to reflect localize changes and chat renames - channels.get(i).setName(name); + currChannel.setName(name); } catch(Exception e) { } - } else if (testChannelId.startsWith(CH_PREFIX) && !isNotificationChannelInUse(testChannelId)) { + } else if (currChannelId.startsWith(CH_MSG_PREFIX) && !isNotificationChannelInUse(currChannelId)) { // TODO: outdated un-independent channels are not deleted try { - notificationManager.deleteNotificationChannel(testChannelId); + notificationManager.deleteNotificationChannel(currChannelId); } catch (Exception e) { } } @@ -182,10 +193,10 @@ public class NotificationCenter { // 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); + NotificationChannel channel = new NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_HIGH); channel.setDescription("Informs about new messages."); channel.setGroup(getNotificationChannelGroup(notificationManager)); + channel.enableVibration(defaultVibrate); if (!ledColor.equals("none")) { channel.enableLights(true); @@ -194,8 +205,6 @@ public class NotificationCenter { channel.enableLights(false); } - channel.enableVibration(defaultVibrate); - if (!TextUtils.isEmpty(ringtone.toString())) { channel.setSound(ringtone, new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN) From 267b3c8a753458067b711e8712e90c396ed5e2be Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Tue, 19 May 2020 23:55:52 +0200 Subject: [PATCH 11/41] delete unused dc_msg notification channels --- .../notifications/NotificationCenter.java | 99 ++++++++++--------- 1 file changed, 50 insertions(+), 49 deletions(-) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index 8b153579f..9bfc2bff0 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -38,7 +38,7 @@ public class NotificationCenter { this.context = dcContext.context.getApplicationContext(); } - private Uri getEffectiveSound(int chatId) { + private Uri effectiveSound(int chatId) { // chatId=0: return app-global setting Uri chatRingtone = Prefs.getChatRingtone(context, chatId); if (chatRingtone!=null) { return chatRingtone; @@ -51,7 +51,7 @@ public class NotificationCenter { return null; } - private boolean getEffectiveVibrate(int chatId) { + private boolean effectiveVibrate(int chatId) { // chatId=0: return app-global setting Prefs.VibrateState vibrate = Prefs.getChatVibrate(context, chatId); if (vibrate == Prefs.VibrateState.ENABLED) { return true; @@ -78,8 +78,7 @@ public class NotificationCenter { } return argb; } - - + // Notification channels // -------------------------------------------------------------------------------------------- @@ -99,7 +98,7 @@ public class NotificationCenter { // 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"; // full name is "ch_msgV_HASH" or "ch_msgV_HASH.CHATID" + public static final String CH_MSG_PREFIX = "ch_msg"; public static final String CH_MSG_VERSION = "4"; public static final String CH_PERMANENT_NOTIFICATION = "dc_foreground_notification_ch"; @@ -107,22 +106,35 @@ public class NotificationCenter { return Build.VERSION.SDK_INT >= 26; } - private boolean isNotificationChannelInUse(String chId) { + // full name is "ch_msgV_HASH" or "ch_msgV_HASH.CHATID" + private String computeChannelId(String ledColor, boolean vibrate, Uri ringtone, int chatId) { + String channelId = CH_MSG_PREFIX; try { - if (chId.startsWith(CH_MSG_PREFIX + CH_MSG_VERSION)) { - int point = chId.lastIndexOf("."); - if (point == -1) { - return true; // this is the current standard channel for all chats that do not have explicit sound/vibrate set - } else { - int chatId = Integer.parseInt(chId.substring(point + 1)); - if (requiresIndependentChannel(chatId)) { - return true; // this is a channel for a chat with explicit sound/vibrate set - } + String hash = ""; + MessageDigest md = MessageDigest.getInstance("SHA-256"); + md.update(ledColor.getBytes()); + md.update(vibrate ? (byte) 1 : (byte) 0); + md.update(ringtone.toString().getBytes()); + hash = String.format("%X", new BigInteger(1, md.digest())).substring(0, 16); - } + channelId = CH_MSG_PREFIX + CH_MSG_VERSION + "_" + hash; + if (chatId!=0) { + channelId += String.format(".%d", chatId); + } + + } catch(Exception e) { } + return channelId; + } + + // return chatId from "ch_msgV_HASH.CHATID" or 0 + private int parseNotificationChannelChatId(String channelId) { + try { + int point = channelId.lastIndexOf("."); + if (point>0) { + return Integer.parseInt(channelId.substring(point + 1)); } } catch(Exception e) { } - return false; + return 0; } private String getNotificationChannelGroup(NotificationManagerCompat notificationManager) { @@ -136,29 +148,18 @@ public class NotificationCenter { private String getNotificationChannel(NotificationManagerCompat notificationManager, DcChat dcChat) { int chatId = dcChat.getId(); - String channelId = CH_MSG_PREFIX + CH_MSG_VERSION + "_" + "unsupported"; + 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 = getEffectiveVibrate(chatId); - Uri ringtone = getEffectiveSound(chatId); + boolean defaultVibrate = effectiveVibrate(chatId); + Uri ringtone = effectiveSound(chatId); boolean isIndependent = requiresIndependentChannel(chatId); - // compute hash from these settings - String hash = ""; - MessageDigest md = MessageDigest.getInstance("SHA-256"); - md.update(ledColor.getBytes()); - md.update(defaultVibrate ? (byte) 1 : (byte) 0); - md.update(ringtone.toString().getBytes()); - hash = String.format("%X", new BigInteger(1, md.digest())).substring(0, 16); - - // get channel id - channelId = CH_MSG_PREFIX + CH_MSG_VERSION + "_" + hash; - if (isIndependent) { - channelId += String.format(".%d", chatId); - } + // get channel id from these settings + channelId = computeChannelId(ledColor, defaultVibrate, ringtone, isIndependent? chatId : 0); // user-visible name of the channel - // we just use the name of the chat or "Default" @@ -168,25 +169,25 @@ public class NotificationCenter { name = dcChat.getName(); } - // check if there is already a channel with the given name, - // delete unused `ch_msg` channel names (keep others as `dc_foreground_notification_ch`) + // 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++) { - NotificationChannel currChannel = channels.get(i); - String currChannelId = currChannel.getId(); - if (channelId.equals(currChannelId)) { - channelExists = true; - try { + 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 - currChannel.setName(name); - } catch(Exception e) { } - } else if (currChannelId.startsWith(CH_MSG_PREFIX) && !isNotificationChannelInUse(currChannelId)) { - // TODO: outdated un-independent channels are not deleted - try { - notificationManager.deleteNotificationChannel(currChannelId); + channelExists = true; + channels.get(i).setName(name); + } else { + // ... another message channel, delete if it is not in use. + int currChatId = parseNotificationChannelChatId(currChannelId); + if (!currChannelId.equals(computeChannelId(ledColor, effectiveVibrate(currChatId), effectiveSound(currChatId), currChatId))) { + notificationManager.deleteNotificationChannel(currChannelId); + } } - catch (Exception e) { } } } @@ -260,11 +261,11 @@ public class NotificationCenter { // set sound, vibrate, led for systems that do not have notification channels if (!notificationChannelsSupported()) { - Uri sound = getEffectiveSound(chatId); + Uri sound = effectiveSound(chatId); if (sound != null) { builder.setSound(sound); } - boolean vibrate = getEffectiveVibrate(chatId); + boolean vibrate = effectiveVibrate(chatId); if (vibrate) { builder.setDefaults(Notification.DEFAULT_VIBRATE); } From f54d076e0b1d6cc317a715fb39ad4174670ff45c Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Wed, 20 May 2020 00:45:30 +0200 Subject: [PATCH 12/41] steamline notification-ids --- .../securesms/connect/KeepAliveService.java | 7 +++---- .../securesms/notifications/NotificationCenter.java | 13 ++++++++++--- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/src/org/thoughtcrime/securesms/connect/KeepAliveService.java b/src/org/thoughtcrime/securesms/connect/KeepAliveService.java index 42f7ab640..3523f8be3 100644 --- a/src/org/thoughtcrime/securesms/connect/KeepAliveService.java +++ b/src/org/thoughtcrime/securesms/connect/KeepAliveService.java @@ -58,7 +58,7 @@ public class KeepAliveService extends Service { // set self as foreground try { stopForeground(true); - startForeground(FG_NOTIFICATION_ID, createNotification()); + startForeground(NotificationCenter.ID_PERMANTENT, createNotification()); } catch (Exception e) { e.printStackTrace(); @@ -94,7 +94,6 @@ public class KeepAliveService extends Service { * Delta Chat won't get new messages reliable **********************************************************************************************/ - public static final int FG_NOTIFICATION_ID = 1; // given to NotificationManagerCompat.notify(); for normal notifications, we use msgId>=10 private Notification createNotification() { Intent intent = new Intent(this, ConversationListActivity.class); @@ -113,7 +112,7 @@ public class KeepAliveService extends Service { builder.setSmallIcon(R.drawable.notification_permanent); if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O) { createFgNotificationChannel(this); - builder.setChannelId(NotificationCenter.CH_PERMANENT_NOTIFICATION); + builder.setChannelId(NotificationCenter.CH_PERMANENT); } return builder.build(); } @@ -123,7 +122,7 @@ public class KeepAliveService extends Service { static private void createFgNotificationChannel(Context context) { if(!ch_created) { ch_created = true; - NotificationChannel channel = new NotificationChannel(NotificationCenter.CH_PERMANENT_NOTIFICATION, + NotificationChannel channel = new NotificationChannel(NotificationCenter.CH_PERMANENT, "Receive messages in background.", NotificationManager.IMPORTANCE_MIN); // IMPORTANCE_DEFAULT will play a sound channel.setDescription("Ensure reliable message receiving."); NotificationManager notificationManager = context.getSystemService(NotificationManager.class); diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index 9bfc2bff0..0cb74d6d8 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -78,7 +78,14 @@ public class NotificationCenter { } return argb; } - + + + // Notification IDs + // -------------------------------------------------------------------------------------------- + + public static final int ID_PERMANTENT = 1; + 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 // -------------------------------------------------------------------------------------------- @@ -100,7 +107,7 @@ public class NotificationCenter { // 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 = "4"; - public static final String CH_PERMANENT_NOTIFICATION = "dc_foreground_notification_ch"; + public static final String CH_PERMANENT = "dc_foreground_notification_ch"; private boolean notificationChannelsSupported() { return Build.VERSION.SDK_INT >= 26; @@ -276,7 +283,7 @@ public class NotificationCenter { } // add notification - notificationManager.notify(msgId, builder.build()); + notificationManager.notify(ID_MSG_OFFSET+msgId, builder.build()); }); } From ddc770a9c9a6f1aad16333a8aea01aa84af5a917 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Wed, 20 May 2020 01:18:53 +0200 Subject: [PATCH 13/41] delete handled notifications --- .../securesms/ConversationActivity.java | 6 ++--- .../securesms/ConversationListFragment.java | 2 +- .../connect/ApplicationDcContext.java | 7 ++--- .../notifications/NotificationCenter.java | 26 ++++++++++++++----- 4 files changed, 28 insertions(+), 13 deletions(-) diff --git a/src/org/thoughtcrime/securesms/ConversationActivity.java b/src/org/thoughtcrime/securesms/ConversationActivity.java index 546f8d43d..fbfcdbbe9 100644 --- a/src/org/thoughtcrime/securesms/ConversationActivity.java +++ b/src/org/thoughtcrime/securesms/ConversationActivity.java @@ -302,14 +302,14 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity titleView.setTitle(glideRequests, dcChat); - dcContext.notificationManger.updateVisibleChat(chatId); + dcContext.notificationCenter.updateVisibleChat(chatId); } @Override protected void onPause() { super.onPause(); processComposeControls(ACTION_SAVE_DRAFT); - dcContext.notificationManger.updateVisibleChat(0); + dcContext.notificationCenter.updateVisibleChat(0); if (isFinishing()) overridePendingTransition(R.anim.fade_scale_in, R.anim.slide_to_right); quickAttachmentDrawer.onPause(); inputPanel.onPause(); @@ -1224,7 +1224,7 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity if (refreshFragment) { fragment.reload(recipient, chatId); - dcContext.notificationManger.updateVisibleChat(chatId); + dcContext.notificationCenter.updateVisibleChat(chatId); } fragment.scrollToBottom(); diff --git a/src/org/thoughtcrime/securesms/ConversationListFragment.java b/src/org/thoughtcrime/securesms/ConversationListFragment.java index e4a9275b9..5d0d1f1e4 100644 --- a/src/org/thoughtcrime/securesms/ConversationListFragment.java +++ b/src/org/thoughtcrime/securesms/ConversationListFragment.java @@ -323,7 +323,7 @@ public class ConversationListFragment extends Fragment dcContext.marknoticedContact(getListAdapter().getDeaddropContactId()); } else { - dcContext.notificationManger.removeNotifications((int) chatId); + dcContext.notificationCenter.removeNotifications((int) chatId); dcContext.deleteChat((int) chatId); } } diff --git a/src/org/thoughtcrime/securesms/connect/ApplicationDcContext.java b/src/org/thoughtcrime/securesms/connect/ApplicationDcContext.java index 171893842..e52af1e4a 100644 --- a/src/org/thoughtcrime/securesms/connect/ApplicationDcContext.java +++ b/src/org/thoughtcrime/securesms/connect/ApplicationDcContext.java @@ -53,7 +53,7 @@ public class ApplicationDcContext extends DcContext { public static final int RECIPIENT_TYPE_CONTACT = 1; public Context context; - public NotificationCenter notificationManger; + public NotificationCenter notificationCenter; public ApplicationDcContext(Context context) { super("Android "+BuildConfig.VERSION_NAME); @@ -122,7 +122,7 @@ public class ApplicationDcContext extends DcContext { Log.e(TAG, "Cannot create wakeLocks"); } - notificationManger = new NotificationCenter(this); + notificationCenter = new NotificationCenter(this); startThreads(0); } @@ -446,6 +446,7 @@ public class ApplicationDcContext extends DcContext { } public void stopThreads() { + notificationCenter.removeAllNotifiations(); run = false; synchronized (threadsCritical) { while (true) { @@ -580,7 +581,7 @@ public class ApplicationDcContext extends DcContext { break; case DC_EVENT_INCOMING_MSG: - Util.runOnAnyBackgroundThread(() -> notificationManger.addNotification((int) data1, (int) data2)); + notificationCenter.addNotification((int) data1, (int) data2); if (eventCenter != null) { eventCenter.sendToObservers(event, data1, data2); // Other parts of the code are also interested in this event } diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index 0cb74d6d8..c5f874962 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -257,6 +257,13 @@ public class NotificationCenter { NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); + // get notification text + DcMsg dcMsg = dcContext.getMsg(msgId); + String text = dcMsg.getSummarytext(100); + if (dcChat.isGroup()) { + text = dcContext.getContact(dcMsg.getFromId()).getFirstName() + ": " + text; + } + // create a basic notification NotificationCompat.Builder builder = new NotificationCompat.Builder(context, getNotificationChannel(notificationManager, dcChat)) .setSmallIcon(R.drawable.icon_notification) @@ -264,7 +271,7 @@ public class NotificationCenter { .setPriority(Prefs.getNotificationPriority(context)) .setCategory(NotificationCompat.CATEGORY_MESSAGE) .setContentTitle(dcChat.getName()) - .setContentText(dcContext.getMsg(msgId).getSummarytext(100)); + .setContentText(text); // set sound, vibrate, led for systems that do not have notification channels if (!notificationChannelsSupported()) { @@ -282,22 +289,29 @@ public class NotificationCenter { } } - // add notification - notificationManager.notify(ID_MSG_OFFSET+msgId, builder.build()); + // add notification, we use one notification per chat, + // esp. older android are not that great at grouping + notificationManager.notify(ID_MSG_OFFSET+chatId, builder.build()); }); } public void removeNotifications(int chatId) { - Util.runOnAnyBackgroundThread(() -> { + NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); + notificationManager.cancel(ID_MSG_OFFSET + chatId); + } - }); + public void removeAllNotifiations() { + NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); + notificationManager.cancelAll(); } public void updateVisibleChat(int chatId) { Util.runOnAnyBackgroundThread(() -> { visibleChatId = chatId; - removeNotifications(chatId); + if (chatId!=0) { + removeNotifications(chatId); + } }); } From d592110de553dad8358fe64c0a9518fcea93fad2 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Wed, 20 May 2020 01:46:40 +0200 Subject: [PATCH 14/41] make notification-channels ready for multi-account --- src/com/b44t/messenger/DcContext.java | 6 ++++++ .../securesms/notifications/NotificationCenter.java | 4 ++++ 2 files changed, 10 insertions(+) diff --git a/src/com/b44t/messenger/DcContext.java b/src/com/b44t/messenger/DcContext.java index 38a4f8fca..6bcaa252c 100644 --- a/src/com/b44t/messenger/DcContext.java +++ b/src/com/b44t/messenger/DcContext.java @@ -84,6 +84,12 @@ public class DcContext { contextCPtr = 0; } + public String getDbName() { + String ret = getBlobdir(); + ret = ret.substring(ret.lastIndexOf('/') + 1); + return ret.replace("-blobs", ""); + } + public native int open (String dbfile); public native void close (); public native void setStockTranslation (int stockId, String translation); diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index c5f874962..392b86fd1 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -122,6 +122,10 @@ public class NotificationCenter { md.update(ledColor.getBytes()); md.update(vibrate ? (byte) 1 : (byte) 0); md.update(ringtone.toString().getBytes()); + if (chatId!=0) { + // for multi-account, force different channelIds for maybe the same chatIds in multiple accounts + md.update(dcContext.getDbName().getBytes()); + } hash = String.format("%X", new BigInteger(1, md.digest())).substring(0, 16); channelId = CH_MSG_PREFIX + CH_MSG_VERSION + "_" + hash; From f3cc4e923439b9b7056e172927384d6cf75f2a36 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Wed, 20 May 2020 01:54:33 +0200 Subject: [PATCH 15/41] also group on notification-level --- .../notifications/NotificationCenter.java | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index 392b86fd1..d66681b94 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -80,6 +80,12 @@ public class NotificationCenter { } + // Groups and Notifcation channel groups + // -------------------------------------------------------------------------------------------- + + public static final String GRP_MSG = "chgrp_msg"; + + // Notification IDs // -------------------------------------------------------------------------------------------- @@ -149,12 +155,11 @@ public class NotificationCenter { } private String getNotificationChannelGroup(NotificationManagerCompat notificationManager) { - final String chGrpId = "chgrp_msg"; - if (notificationChannelsSupported() && notificationManager.getNotificationChannelGroup(chGrpId) == null) { - NotificationChannelGroup chGrp = new NotificationChannelGroup(chGrpId, context.getString(R.string.pref_chats)); + if (notificationChannelsSupported() && notificationManager.getNotificationChannelGroup(GRP_MSG) == null) { + NotificationChannelGroup chGrp = new NotificationChannelGroup(GRP_MSG, context.getString(R.string.pref_chats)); notificationManager.createNotificationChannelGroup(chGrp); } - return chGrpId; + return GRP_MSG; } private String getNotificationChannel(NotificationManagerCompat notificationManager, DcChat dcChat) { @@ -274,6 +279,7 @@ public class NotificationCenter { .setColor(context.getResources().getColor(R.color.delta_primary)) .setPriority(Prefs.getNotificationPriority(context)) .setCategory(NotificationCompat.CATEGORY_MESSAGE) + .setGroup(GRP_MSG) .setContentTitle(dcChat.getName()) .setContentText(text); From 291dc06f0737594f0250568d98355bafb90b8b28 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Wed, 20 May 2020 02:02:00 +0200 Subject: [PATCH 16/41] open correct chat --- .../notifications/NotificationCenter.java | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index d66681b94..e73998c4a 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -4,7 +4,9 @@ import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationChannelGroup; import android.app.NotificationManager; +import android.app.PendingIntent; import android.content.Context; +import android.content.Intent; import android.graphics.Color; import android.media.AudioAttributes; import android.net.Uri; @@ -14,10 +16,12 @@ import android.text.TextUtils; import androidx.annotation.NonNull; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; +import androidx.core.app.TaskStackBuilder; import com.b44t.messenger.DcChat; import com.b44t.messenger.DcMsg; +import org.thoughtcrime.securesms.ConversationActivity; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.connect.ApplicationDcContext; import org.thoughtcrime.securesms.util.Prefs; @@ -78,6 +82,15 @@ public class NotificationCenter { } return argb; } + + private PendingIntent getPendingIntent(int chatId) { + Intent intent = new Intent(context, ConversationActivity.class); + intent.putExtra(ConversationActivity.CHAT_ID_EXTRA, chatId); + intent.setData((Uri.parse("custom://"+System.currentTimeMillis()))); + return TaskStackBuilder.create(context) + .addNextIntentWithParentStack(intent) + .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); + } // Groups and Notifcation channel groups @@ -281,7 +294,8 @@ public class NotificationCenter { .setCategory(NotificationCompat.CATEGORY_MESSAGE) .setGroup(GRP_MSG) .setContentTitle(dcChat.getName()) - .setContentText(text); + .setContentText(text) + .setContentIntent(getPendingIntent(chatId)); // set sound, vibrate, led for systems that do not have notification channels if (!notificationChannelsSupported()) { From c79401d6b41e0eab3a9a6fe4f882625b90ea04c0 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Wed, 20 May 2020 13:12:38 +0200 Subject: [PATCH 17/41] add avatar beside notification --- .../notifications/NotificationCenter.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index e73998c4a..a1e787f39 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -7,11 +7,14 @@ import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; +import android.graphics.Bitmap; import android.graphics.Color; +import android.graphics.drawable.Drawable; import android.media.AudioAttributes; import android.net.Uri; import android.os.Build; import android.text.TextUtils; +import android.util.Log; import androidx.annotation.NonNull; import androidx.core.app.NotificationCompat; @@ -20,10 +23,15 @@ import androidx.core.app.TaskStackBuilder; import com.b44t.messenger.DcChat; import com.b44t.messenger.DcMsg; +import com.bumptech.glide.load.engine.DiskCacheStrategy; import org.thoughtcrime.securesms.ConversationActivity; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.connect.ApplicationDcContext; +import org.thoughtcrime.securesms.contacts.avatars.ContactPhoto; +import org.thoughtcrime.securesms.mms.GlideApp; +import org.thoughtcrime.securesms.recipients.Recipient; +import org.thoughtcrime.securesms.util.BitmapUtil; import org.thoughtcrime.securesms.util.Prefs; import org.thoughtcrime.securesms.util.Util; @@ -313,6 +321,32 @@ public class NotificationCenter { } } + // set avatar + try { + Drawable drawable; + Recipient recipient = new Recipient(context, dcChat, null); + 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(context)); + } + if (drawable!=null) { + int wh = context.getResources().getDimensionPixelSize(R.dimen.contact_photo_target_size); + Bitmap bitmap = BitmapUtil.createFromDrawable(drawable, wh, wh); + if (bitmap!=null) { + builder.setLargeIcon(bitmap); + } + } + } catch (Exception e) { Log.w(TAG, e); } + // add notification, we use one notification per chat, // esp. older android are not that great at grouping notificationManager.notify(ID_MSG_OFFSET+chatId, builder.build()); From 3646314a13048d279bbca265ebaf951be94c0680 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Wed, 20 May 2020 14:11:55 +0200 Subject: [PATCH 18/41] support notification badge/dot --- .../securesms/notifications/NotificationCenter.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index a1e787f39..4890dcedd 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -235,6 +235,7 @@ public class NotificationCenter { channel.setDescription("Informs about new messages."); channel.setGroup(getNotificationChannelGroup(notificationManager)); channel.enableVibration(defaultVibrate); + channel.setShowBadge(true); if (!ledColor.equals("none")) { channel.enableLights(true); @@ -347,6 +348,14 @@ public class NotificationCenter { } } catch (Exception e) { Log.w(TAG, e); } + // messages count, some os make some use of that + // - do not use setSubText() as this is displayed together with setContentInfo() eg. on Lollipop + // - setNumber() may overwrite setContentInfo(), should be called last + // weird stuff. + int cnt = dcContext.getFreshMsgCount(chatId); + builder.setContentInfo(String.valueOf(cnt)); + builder.setNumber(cnt); + // add notification, we use one notification per chat, // esp. older android are not that great at grouping notificationManager.notify(ID_MSG_OFFSET+chatId, builder.build()); From d09c7da4039629a0b26cd080062acda7e744a291 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Wed, 20 May 2020 15:16:39 +0200 Subject: [PATCH 19/41] avoid a load of sounds --- .../notifications/NotificationCenter.java | 27 ++++++++++++++----- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index 4890dcedd..7e504b75b 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -38,12 +38,15 @@ import org.thoughtcrime.securesms.util.Util; import java.math.BigInteger; import java.security.MessageDigest; import java.util.List; +import java.util.concurrent.TimeUnit; public class NotificationCenter { private static final String TAG = InChatSounds.class.getSimpleName(); @NonNull private ApplicationDcContext dcContext; @NonNull private Context context; private volatile int visibleChatId = 0; + private volatile long lastAudibleNotification = 0; + private static final long MIN_AUDIBLE_PERIOD_MILLIS = TimeUnit.SECONDS.toMillis(2); public NotificationCenter(ApplicationDcContext dcContext) { this.dcContext = dcContext; @@ -295,6 +298,13 @@ public class NotificationCenter { text = dcContext.getContact(dcMsg.getFromId()).getFirstName() + ": " + text; } + // play signal? + long now = System.currentTimeMillis(); + boolean signal = (now - lastAudibleNotification) > MIN_AUDIBLE_PERIOD_MILLIS; + if (signal) { + lastAudibleNotification = now; + } + // create a basic notification NotificationCompat.Builder builder = new NotificationCompat.Builder(context, getNotificationChannel(notificationManager, dcChat)) .setSmallIcon(R.drawable.icon_notification) @@ -302,19 +312,22 @@ public class NotificationCenter { .setPriority(Prefs.getNotificationPriority(context)) .setCategory(NotificationCompat.CATEGORY_MESSAGE) .setGroup(GRP_MSG) + .setOnlyAlertOnce(!signal) .setContentTitle(dcChat.getName()) .setContentText(text) .setContentIntent(getPendingIntent(chatId)); // set sound, vibrate, led for systems that do not have notification channels if (!notificationChannelsSupported()) { - Uri sound = effectiveSound(chatId); - if (sound != null) { - builder.setSound(sound); - } - boolean vibrate = effectiveVibrate(chatId); - if (vibrate) { - builder.setDefaults(Notification.DEFAULT_VIBRATE); + if (signal) { + Uri sound = effectiveSound(chatId); + if (sound != null) { + builder.setSound(sound); + } + boolean vibrate = effectiveVibrate(chatId); + if (vibrate) { + builder.setDefaults(Notification.DEFAULT_VIBRATE); + } } String ledColor = Prefs.getNotificationLedColor(context); if (!ledColor.equals("none")) { From 73f20f528861328b8a554cf11de1dbb28d3f4b30 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Wed, 20 May 2020 15:43:30 +0200 Subject: [PATCH 20/41] respect privacy settings --- .../notifications/NotificationCenter.java | 46 +++++++++++-------- 1 file changed, 28 insertions(+), 18 deletions(-) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index 7e504b75b..ae912ffe7 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -30,6 +30,7 @@ import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.connect.ApplicationDcContext; import org.thoughtcrime.securesms.contacts.avatars.ContactPhoto; import org.thoughtcrime.securesms.mms.GlideApp; +import org.thoughtcrime.securesms.preferences.widgets.NotificationPrivacyPreference; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.util.BitmapUtil; import org.thoughtcrime.securesms.util.Prefs; @@ -292,9 +293,11 @@ public class NotificationCenter { NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); // get notification text + NotificationPrivacyPreference privacy = Prefs.getNotificationPrivacy(context); + DcMsg dcMsg = dcContext.getMsg(msgId); - String text = dcMsg.getSummarytext(100); - if (dcChat.isGroup()) { + String text = privacy.isDisplayMessage()? dcMsg.getSummarytext(100) : context.getString(R.string.notify_new_message); + if (dcChat.isGroup() && privacy.isDisplayContact()) { text = dcContext.getContact(dcMsg.getFromId()).getFirstName() + ": " + text; } @@ -313,10 +316,13 @@ public class NotificationCenter { .setCategory(NotificationCompat.CATEGORY_MESSAGE) .setGroup(GRP_MSG) .setOnlyAlertOnce(!signal) - .setContentTitle(dcChat.getName()) .setContentText(text) .setContentIntent(getPendingIntent(chatId)); + if (privacy.isDisplayContact()) { + builder.setContentTitle(dcChat.getName()); + } + // set sound, vibrate, led for systems that do not have notification channels if (!notificationChannelsSupported()) { if (signal) { @@ -336,12 +342,13 @@ public class NotificationCenter { } // set avatar - try { - Drawable drawable; - Recipient recipient = new Recipient(context, dcChat, null); - ContactPhoto contactPhoto = recipient.getContactPhoto(context); - if (contactPhoto != null) { - drawable = GlideApp.with(context.getApplicationContext()) + if (privacy.isDisplayContact()) { + try { + Drawable drawable; + Recipient recipient = new Recipient(context, dcChat, null); + ContactPhoto contactPhoto = recipient.getContactPhoto(context); + if (contactPhoto != null) { + drawable = GlideApp.with(context.getApplicationContext()) .load(contactPhoto) .diskCacheStrategy(DiskCacheStrategy.NONE) .circleCrop() @@ -349,17 +356,20 @@ public class NotificationCenter { context.getResources().getDimensionPixelSize(android.R.dimen.notification_large_icon_height)) .get(); - } else { - drawable = recipient.getFallbackContactPhoto().asDrawable(context, recipient.getFallbackAvatarColor(context)); - } - if (drawable!=null) { - int wh = context.getResources().getDimensionPixelSize(R.dimen.contact_photo_target_size); - Bitmap bitmap = BitmapUtil.createFromDrawable(drawable, wh, wh); - if (bitmap!=null) { - builder.setLargeIcon(bitmap); + } else { + drawable = recipient.getFallbackContactPhoto().asDrawable(context, recipient.getFallbackAvatarColor(context)); } + if (drawable != null) { + int wh = context.getResources().getDimensionPixelSize(R.dimen.contact_photo_target_size); + Bitmap bitmap = BitmapUtil.createFromDrawable(drawable, wh, wh); + if (bitmap != null) { + builder.setLargeIcon(bitmap); + } + } + } catch (Exception e) { + Log.w(TAG, e); } - } catch (Exception e) { Log.w(TAG, e); } + } // messages count, some os make some use of that // - do not use setSubText() as this is displayed together with setContentInfo() eg. on Lollipop From 6b4f9772a80fe2ba4036fa669b55ec69ff404f97 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Wed, 20 May 2020 17:01:23 +0200 Subject: [PATCH 21/41] add remote reply option to notification --- .../notifications/MessageNotifier.java | 4 +- .../notifications/NotificationCenter.java | 40 ++++++++++++++++++- .../notifications/NotificationState.java | 14 ------- .../notifications/RemoteReplyReceiver.java | 17 +++----- 4 files changed, 46 insertions(+), 29 deletions(-) diff --git a/src/org/thoughtcrime/securesms/notifications/MessageNotifier.java b/src/org/thoughtcrime/securesms/notifications/MessageNotifier.java index 0f5230ab9..2bd245a73 100644 --- a/src/org/thoughtcrime/securesms/notifications/MessageNotifier.java +++ b/src/org/thoughtcrime/securesms/notifications/MessageNotifier.java @@ -264,8 +264,8 @@ abstract class MessageNotifier { long timestamp = firstItem.getTimestamp(); if (timestamp != 0) builder.setWhen(timestamp); - builder.addActions(notificationState.getMarkAsReadIntent(context, chatId, notificationId), - notificationState.getRemoteReplyIntent(context, recipient)); + //builder.addActions(notificationState.getMarkAsReadIntent(context, chatId, notificationId), + // notificationState.getRemoteReplyIntent(context, recipient)); ListIterator iterator = notifications.listIterator(notifications.size()); diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index ae912ffe7..e83cc9d9b 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -19,6 +19,7 @@ import android.util.Log; import androidx.annotation.NonNull; 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; @@ -104,8 +105,18 @@ public class NotificationCenter { .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); } + private PendingIntent getRemoteReplyIntent(int chatId) { + Intent intent = new Intent(RemoteReplyReceiver.REPLY_ACTION); + intent.setClass(context, RemoteReplyReceiver.class); + intent.setData((Uri.parse("custom://"+System.currentTimeMillis()))); + intent.putExtra(RemoteReplyReceiver.CHAT_ID_EXTRA, chatId); + intent.setPackage(context.getPackageName()); + return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); + } - // Groups and Notifcation channel groups + + + // Groups and Notification channel groups // -------------------------------------------------------------------------------------------- public static final String GRP_MSG = "chgrp_msg"; @@ -342,10 +353,10 @@ public class NotificationCenter { } // set avatar + Recipient recipient = new Recipient(context, dcChat, null); if (privacy.isDisplayContact()) { try { Drawable drawable; - Recipient recipient = new Recipient(context, dcChat, null); ContactPhoto contactPhoto = recipient.getContactPhoto(context); if (contactPhoto != null) { drawable = GlideApp.with(context.getApplicationContext()) @@ -371,6 +382,31 @@ public class NotificationCenter { } } + // add a reply-button that allows answering without opening Delta Chat. + // the reply-button is useful only if sender+message is displayed and if app-lock is disabled. + if (privacy.isDisplayContact() && privacy.isDisplayMessage() + && !Prefs.isScreenLockEnabled(context)) { + PendingIntent inNotificationReplyIntent = getRemoteReplyIntent(chatId); + + 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(MessageNotifierCompat.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(MessageNotifierCompat.EXTRA_REMOTE_REPLY) + .setLabel(context.getString(R.string.notify_reply_button)).build()) + .build(); + builder.extend(new NotificationCompat.WearableExtender().addAction(wearableReplyAction)); + } + // messages count, some os make some use of that // - do not use setSubText() as this is displayed together with setContentInfo() eg. on Lollipop // - setNumber() may overwrite setContentInfo(), should be called last diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationState.java b/src/org/thoughtcrime/securesms/notifications/NotificationState.java index ad94b64f9..79bc723ac 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationState.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationState.java @@ -139,18 +139,4 @@ public class NotificationState { return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } - - PendingIntent getRemoteReplyIntent(Context context, Recipient recipient) { - if (chats.size() != 1) throw new AssertionError("We only support replies to single chat notifications!"); - - Intent intent = new Intent(RemoteReplyReceiver.REPLY_ACTION); - intent.setClass(context, RemoteReplyReceiver.class); - intent.setData((Uri.parse("custom://"+System.currentTimeMillis()))); - intent.putExtra(RemoteReplyReceiver.ADDRESS_EXTRA, recipient.getAddress()); - intent.setPackage(context.getPackageName()); - - return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); - } - - } diff --git a/src/org/thoughtcrime/securesms/notifications/RemoteReplyReceiver.java b/src/org/thoughtcrime/securesms/notifications/RemoteReplyReceiver.java index 3f1096620..e5d2d315f 100644 --- a/src/org/thoughtcrime/securesms/notifications/RemoteReplyReceiver.java +++ b/src/org/thoughtcrime/securesms/notifications/RemoteReplyReceiver.java @@ -27,7 +27,6 @@ import androidx.core.app.RemoteInput; import org.thoughtcrime.securesms.connect.ApplicationDcContext; import org.thoughtcrime.securesms.connect.DcHelper; -import org.thoughtcrime.securesms.database.Address; /** @@ -37,30 +36,26 @@ public class RemoteReplyReceiver extends BroadcastReceiver { public static final String TAG = RemoteReplyReceiver.class.getSimpleName(); public static final String REPLY_ACTION = "org.thoughtcrime.securesms.notifications.WEAR_REPLY"; - public static final String ADDRESS_EXTRA = "address"; + public static final String CHAT_ID_EXTRA = "chat_id"; @SuppressLint("StaticFieldLeak") @Override public void onReceive(final Context context, Intent intent) { if (!REPLY_ACTION.equals(intent.getAction())) return; Bundle remoteInput = RemoteInput.getResultsFromIntent(intent); + final int chatId = intent.getIntExtra(CHAT_ID_EXTRA, 0); - if (remoteInput == null) return; + if (remoteInput == null || chatId == 0) return; - final Address address = intent.getParcelableExtra(ADDRESS_EXTRA); final CharSequence responseText = remoteInput.getCharSequence(MessageNotifierCompat.EXTRA_REMOTE_REPLY); if (responseText != null) { new AsyncTask() { @Override protected Void doInBackground(Void... params) { - - if(address.isDcChat()) { - ApplicationDcContext dcContext = DcHelper.getContext(context); - dcContext.sendTextMsg(address.getDcChatId(), responseText.toString()); - MessageNotifierCompat.removeNotifications(address.getDcChatId()); - } - + ApplicationDcContext dcContext = DcHelper.getContext(context); + dcContext.sendTextMsg(chatId, responseText.toString()); + dcContext.notificationCenter.removeNotifications(chatId); return null; } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); From b68a187c741e30bfe2633279b1eacab5f5b56acc Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Wed, 20 May 2020 18:42:29 +0200 Subject: [PATCH 22/41] add inbox-style to notifications --- .../notifications/NotificationCenter.java | 67 +++++++++++++------ 1 file changed, 48 insertions(+), 19 deletions(-) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index e83cc9d9b..deb595359 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -39,6 +39,8 @@ import org.thoughtcrime.securesms.util.Util; import java.math.BigInteger; import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.concurrent.TimeUnit; @@ -49,6 +51,7 @@ public class NotificationCenter { private volatile int visibleChatId = 0; private volatile long lastAudibleNotification = 0; private static final long MIN_AUDIBLE_PERIOD_MILLIS = TimeUnit.SECONDS.toMillis(2); + private final HashMap> inboxes = new HashMap<>(); // contains the last lines of each chat public NotificationCenter(ApplicationDcContext dcContext) { this.dcContext = dcContext; @@ -303,13 +306,13 @@ public class NotificationCenter { NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); - // get notification text + // get notification text as a single line NotificationPrivacyPreference privacy = Prefs.getNotificationPrivacy(context); DcMsg dcMsg = dcContext.getMsg(msgId); - String text = privacy.isDisplayMessage()? dcMsg.getSummarytext(100) : context.getString(R.string.notify_new_message); + String line = privacy.isDisplayMessage()? dcMsg.getSummarytext(100) : context.getString(R.string.notify_new_message); if (dcChat.isGroup() && privacy.isDisplayContact()) { - text = dcContext.getContact(dcMsg.getFromId()).getFirstName() + ": " + text; + line = dcContext.getContact(dcMsg.getFromId()).getFirstName() + ": " + line; } // play signal? @@ -327,7 +330,7 @@ public class NotificationCenter { .setCategory(NotificationCompat.CATEGORY_MESSAGE) .setGroup(GRP_MSG) .setOnlyAlertOnce(!signal) - .setContentText(text) + .setContentText(line) .setContentIntent(getPendingIntent(chatId)); if (privacy.isDisplayContact()) { @@ -377,34 +380,54 @@ public class NotificationCenter { builder.setLargeIcon(bitmap); } } - } catch (Exception e) { - Log.w(TAG, e); - } + } catch (Exception e) { Log.w(TAG, e); } } // add a reply-button that allows answering without opening Delta Chat. // the reply-button is useful only if sender+message is displayed and if app-lock is disabled. if (privacy.isDisplayContact() && privacy.isDisplayMessage() && !Prefs.isScreenLockEnabled(context)) { - PendingIntent inNotificationReplyIntent = getRemoteReplyIntent(chatId); + try { + PendingIntent inNotificationReplyIntent = getRemoteReplyIntent(chatId); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(R.drawable.ic_reply_white_36dp, + 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(MessageNotifierCompat.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(MessageNotifierCompat.EXTRA_REMOTE_REPLY) .setLabel(context.getString(R.string.notify_reply_button)).build()) .build(); - builder.addAction(replyAction); - } + builder.extend(new NotificationCompat.WearableExtender().addAction(wearableReplyAction)); + } catch(Exception e) { Log.w(TAG, e); } + } - NotificationCompat.Action wearableReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_reply, - context.getString(R.string.notify_reply_button), - inNotificationReplyIntent) - .addRemoteInput(new RemoteInput.Builder(MessageNotifierCompat.EXTRA_REMOTE_REPLY) - .setLabel(context.getString(R.string.notify_reply_button)).build()) - .build(); - builder.extend(new NotificationCompat.WearableExtender().addAction(wearableReplyAction)); + // create a tiny inbox (gets visible if the notification is expanded) + if (privacy.isDisplayContact() && privacy.isDisplayMessage()) { + try { + NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); + synchronized (inboxes) { + ArrayList lines = inboxes.get(chatId); + if (lines == null) { + lines = new ArrayList<>(); + inboxes.put(chatId, lines); + } + lines.add(line); + + for (int l = lines.size() - 1; l >= 0; l--) { + inboxStyle.addLine(lines.get(l)); + } + } + builder.setStyle(inboxStyle); + } catch(Exception e) { Log.w(TAG, e); } } // messages count, some os make some use of that @@ -422,11 +445,17 @@ public class NotificationCenter { } public void removeNotifications(int chatId) { + synchronized (inboxes) { + inboxes.remove(chatId); + } NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.cancel(ID_MSG_OFFSET + chatId); } public void removeAllNotifiations() { + synchronized (inboxes) { + inboxes.clear(); + } NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.cancelAll(); } From 3595bc445d2cdbe505b8e7b206c115a6c911e86f Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Wed, 20 May 2020 18:52:11 +0200 Subject: [PATCH 23/41] tweak notification-accessibility --- .../securesms/notifications/NotificationCenter.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index deb595359..375ed5d54 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -337,6 +337,14 @@ public class NotificationCenter { builder.setContentTitle(dcChat.getName()); } + // if privacy allows, for better accessibility, + // prepend the sender in the ticker also for one-to-one chats (for group-chats, this is already done) + String tickerLine = line; + if (!dcChat.isGroup() && privacy.isDisplayContact()) { + line = dcContext.getContact(dcMsg.getFromId()).getFirstName() + ": " + line; + } + builder.setTicker(tickerLine); + // set sound, vibrate, led for systems that do not have notification channels if (!notificationChannelsSupported()) { if (signal) { From 7b8776ac2e99e314086a99ccc55f6b12777c3774 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Wed, 20 May 2020 18:56:19 +0200 Subject: [PATCH 24/41] remove dependency to MessageNotifierCompat --- .../securesms/notifications/NotificationCenter.java | 4 ++-- .../securesms/notifications/RemoteReplyReceiver.java | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index 375ed5d54..439d2863b 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -402,7 +402,7 @@ public class NotificationCenter { 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(MessageNotifierCompat.EXTRA_REMOTE_REPLY) + .addRemoteInput(new RemoteInput.Builder(RemoteReplyReceiver.EXTRA_REMOTE_REPLY) .setLabel(context.getString(R.string.notify_reply_button)).build()) .build(); builder.addAction(replyAction); @@ -411,7 +411,7 @@ public class NotificationCenter { NotificationCompat.Action wearableReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_reply, context.getString(R.string.notify_reply_button), inNotificationReplyIntent) - .addRemoteInput(new RemoteInput.Builder(MessageNotifierCompat.EXTRA_REMOTE_REPLY) + .addRemoteInput(new RemoteInput.Builder(RemoteReplyReceiver.EXTRA_REMOTE_REPLY) .setLabel(context.getString(R.string.notify_reply_button)).build()) .build(); builder.extend(new NotificationCompat.WearableExtender().addAction(wearableReplyAction)); diff --git a/src/org/thoughtcrime/securesms/notifications/RemoteReplyReceiver.java b/src/org/thoughtcrime/securesms/notifications/RemoteReplyReceiver.java index e5d2d315f..c39fcb668 100644 --- a/src/org/thoughtcrime/securesms/notifications/RemoteReplyReceiver.java +++ b/src/org/thoughtcrime/securesms/notifications/RemoteReplyReceiver.java @@ -37,6 +37,7 @@ public class RemoteReplyReceiver extends BroadcastReceiver { public static final String TAG = RemoteReplyReceiver.class.getSimpleName(); public static final String REPLY_ACTION = "org.thoughtcrime.securesms.notifications.WEAR_REPLY"; public static final String CHAT_ID_EXTRA = "chat_id"; + public static final String EXTRA_REMOTE_REPLY = "extra_remote_reply"; @SuppressLint("StaticFieldLeak") @Override @@ -47,7 +48,7 @@ public class RemoteReplyReceiver extends BroadcastReceiver { if (remoteInput == null || chatId == 0) return; - final CharSequence responseText = remoteInput.getCharSequence(MessageNotifierCompat.EXTRA_REMOTE_REPLY); + final CharSequence responseText = remoteInput.getCharSequence(EXTRA_REMOTE_REPLY); if (responseText != null) { new AsyncTask() { From bdb31e5d36e11f4f02975a59275a2d01524283e5 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Wed, 20 May 2020 23:16:28 +0200 Subject: [PATCH 25/41] wording --- .../securesms/notifications/NotificationCenter.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index 439d2863b..9a7637b4e 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -99,7 +99,7 @@ public class NotificationCenter { return argb; } - private PendingIntent getPendingIntent(int chatId) { + private PendingIntent getOpenChatIntent(int chatId) { Intent intent = new Intent(context, ConversationActivity.class); intent.putExtra(ConversationActivity.CHAT_ID_EXTRA, chatId); intent.setData((Uri.parse("custom://"+System.currentTimeMillis()))); @@ -323,6 +323,9 @@ public class NotificationCenter { } // 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 NotificationCompat.Builder builder = new NotificationCompat.Builder(context, getNotificationChannel(notificationManager, dcChat)) .setSmallIcon(R.drawable.icon_notification) .setColor(context.getResources().getColor(R.color.delta_primary)) @@ -331,8 +334,7 @@ public class NotificationCenter { .setGroup(GRP_MSG) .setOnlyAlertOnce(!signal) .setContentText(line) - .setContentIntent(getPendingIntent(chatId)); - + .setContentIntent(getOpenChatIntent(chatId)); if (privacy.isDisplayContact()) { builder.setContentTitle(dcChat.getName()); } From 96114c415d6502db9d7c234d9b026b24e646bdfc Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Thu, 21 May 2020 00:35:13 +0200 Subject: [PATCH 26/41] respect global notification switch --- .../securesms/notifications/NotificationCenter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index 9a7637b4e..c86ac91ca 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -289,7 +289,7 @@ public class NotificationCenter { DcChat dcChat = dcContext.getChat(chatId); - if (Prefs.isChatMuted(dcContext.context, chatId)) { + if (!Prefs.isNotificationsEnabled(context) || Prefs.isChatMuted(context, chatId)) { return; } From 2b8b54ce10bbdd0dd6fd12fef5dbb749dc895ec5 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Thu, 21 May 2020 00:41:04 +0200 Subject: [PATCH 27/41] tweak in-chat-sounds --- .../securesms/notifications/NotificationCenter.java | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index c86ac91ca..2cc898c87 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -289,6 +289,13 @@ public class NotificationCenter { DcChat dcChat = dcContext.getChat(chatId); + if (chatId == visibleChatId) { + // in-chat sounds are not related to notifications, + // they can be enabled/disabled independently + InChatSounds.getInstance(dcContext.context).playIncomingSound(); + return; + } + if (!Prefs.isNotificationsEnabled(context) || Prefs.isChatMuted(context, chatId)) { return; } @@ -299,11 +306,6 @@ public class NotificationCenter { return; } - if (chatId == visibleChatId) { - InChatSounds.getInstance(dcContext.context).playIncomingSound(); - return; - } - NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); // get notification text as a single line From 1b814f4d867795a5f9c9547424552798083a282c Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Thu, 21 May 2020 01:28:40 +0200 Subject: [PATCH 28/41] adapt to new mute-api --- .../securesms/notifications/NotificationCenter.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index 2cc898c87..b28469bd4 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -292,11 +292,11 @@ public class NotificationCenter { if (chatId == visibleChatId) { // in-chat sounds are not related to notifications, // they can be enabled/disabled independently - InChatSounds.getInstance(dcContext.context).playIncomingSound(); + InChatSounds.getInstance(context).playIncomingSound(); return; } - if (!Prefs.isNotificationsEnabled(context) || Prefs.isChatMuted(context, chatId)) { + if (!Prefs.isNotificationsEnabled(context) || dcChat.isMuted()) { return; } From 9e9c9014c6cded8585a3198be97f5dff8758f784 Mon Sep 17 00:00:00 2001 From: bjoern Date: Fri, 22 May 2020 21:35:12 +0200 Subject: [PATCH 29/41] Update src/org/thoughtcrime/securesms/notifications/NotificationCenter.java Co-authored-by: Hocuri --- .../securesms/notifications/NotificationCenter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index b28469bd4..d8083a6bc 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -45,7 +45,7 @@ import java.util.List; import java.util.concurrent.TimeUnit; public class NotificationCenter { - private static final String TAG = InChatSounds.class.getSimpleName(); + private static final String TAG = NotificationCenter.class.getSimpleName(); @NonNull private ApplicationDcContext dcContext; @NonNull private Context context; private volatile int visibleChatId = 0; From f7af21cd1f6593ca0328dfe98ad48dbea57fe666 Mon Sep 17 00:00:00 2001 From: bjoern Date: Fri, 22 May 2020 21:35:38 +0200 Subject: [PATCH 30/41] Update src/org/thoughtcrime/securesms/notifications/NotificationCenter.java Co-authored-by: Hocuri --- .../securesms/notifications/NotificationCenter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index d8083a6bc..b9e07e8cf 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -452,7 +452,7 @@ public class NotificationCenter { // add notification, we use one notification per chat, // esp. older android are not that great at grouping - notificationManager.notify(ID_MSG_OFFSET+chatId, builder.build()); + notificationManager.notify(ID_MSG_OFFSET + chatId, builder.build()); }); } From c66473d88ad80f8411dc0639e05fe3ac1a28e4c0 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Sat, 23 May 2020 00:12:40 +0200 Subject: [PATCH 31/41] use addr instead of db-name as unique-element for multi-account, thanks @Hocuri --- src/com/b44t/messenger/DcContext.java | 6 ------ .../securesms/notifications/NotificationCenter.java | 2 +- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/src/com/b44t/messenger/DcContext.java b/src/com/b44t/messenger/DcContext.java index 6bcaa252c..38a4f8fca 100644 --- a/src/com/b44t/messenger/DcContext.java +++ b/src/com/b44t/messenger/DcContext.java @@ -84,12 +84,6 @@ public class DcContext { contextCPtr = 0; } - public String getDbName() { - String ret = getBlobdir(); - ret = ret.substring(ret.lastIndexOf('/') + 1); - return ret.replace("-blobs", ""); - } - public native int open (String dbfile); public native void close (); public native void setStockTranslation (int stockId, String translation); diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index b9e07e8cf..578090bf5 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -169,7 +169,7 @@ public class NotificationCenter { md.update(ringtone.toString().getBytes()); if (chatId!=0) { // for multi-account, force different channelIds for maybe the same chatIds in multiple accounts - md.update(dcContext.getDbName().getBytes()); + md.update(dcContext.getConfig("addr").getBytes()); } hash = String.format("%X", new BigInteger(1, md.digest())).substring(0, 16); From bec77fcb924933fdc43929167a6a98b1c1bca7eb Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Sat, 23 May 2020 00:18:36 +0200 Subject: [PATCH 32/41] format respecting used style in the rest of the file --- .../thoughtcrime/securesms/ConversationListFragment.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/org/thoughtcrime/securesms/ConversationListFragment.java b/src/org/thoughtcrime/securesms/ConversationListFragment.java index 5d0d1f1e4..c6318b012 100644 --- a/src/org/thoughtcrime/securesms/ConversationListFragment.java +++ b/src/org/thoughtcrime/securesms/ConversationListFragment.java @@ -293,9 +293,9 @@ public class ConversationListFragment extends Fragment @SuppressLint("StaticFieldLeak") private void handleDeleteAllSelected() { - final ApplicationDcContext dcContext = DcHelper.getContext(getActivity()); - int conversationsCount = getListAdapter().getBatchSelections().size(); - AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); + final ApplicationDcContext dcContext = DcHelper.getContext(getActivity()); + int conversationsCount = getListAdapter().getBatchSelections().size(); + AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); alert.setMessage(getActivity().getResources().getQuantityString(R.plurals.ask_delete_chat, conversationsCount, conversationsCount)); alert.setCancelable(true); From 20f488807e9550e4e0fbfef1fe16f8239fa3e077 Mon Sep 17 00:00:00 2001 From: bjoern Date: Sat, 23 May 2020 00:22:32 +0200 Subject: [PATCH 33/41] Update src/org/thoughtcrime/securesms/notifications/NotificationCenter.java Co-authored-by: Hocuri --- .../securesms/notifications/NotificationCenter.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index 578090bf5..5264111f6 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -82,10 +82,8 @@ public class NotificationCenter { } private boolean requiresIndependentChannel(int chatId) { - if (Prefs.getChatRingtone(context, chatId)!=null || Prefs.getChatVibrate(context, chatId)!=Prefs.VibrateState.DEFAULT) { - return true; - } - return false; + return Prefs.getChatRingtone(context, chatId) != null + || Prefs.getChatVibrate(context, chatId) != Prefs.VibrateState.DEFAULT; } private int getLedArgb(String ledColor) { From d8c0e1367ed0bff0675fbf7fbdf8ed169915472a Mon Sep 17 00:00:00 2001 From: bjoern Date: Sat, 23 May 2020 00:27:16 +0200 Subject: [PATCH 34/41] Update src/org/thoughtcrime/securesms/notifications/NotificationCenter.java Co-authored-by: Hocuri --- .../securesms/notifications/NotificationCenter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index 5264111f6..076aff9c7 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -260,7 +260,7 @@ public class NotificationCenter { channel.enableLights(false); } - if (!TextUtils.isEmpty(ringtone.toString())) { + if (ringtone != null && !TextUtils.isEmpty(ringtone.toString())) { channel.setSound(ringtone, new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN) .setUsage(AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT) From 143f6c5b673099cd9d38cb9f8c964fa9624c4cd6 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Sat, 23 May 2020 00:29:37 +0200 Subject: [PATCH 35/41] remove useless init, thanks @Hocuri --- .../securesms/notifications/NotificationCenter.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index 076aff9c7..dcafee5f5 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -160,7 +160,6 @@ public class NotificationCenter { private String computeChannelId(String ledColor, boolean vibrate, Uri ringtone, int chatId) { String channelId = CH_MSG_PREFIX; try { - String hash = ""; MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(ledColor.getBytes()); md.update(vibrate ? (byte) 1 : (byte) 0); @@ -169,7 +168,7 @@ public class NotificationCenter { // for multi-account, force different channelIds for maybe the same chatIds in multiple accounts md.update(dcContext.getConfig("addr").getBytes()); } - hash = String.format("%X", new BigInteger(1, md.digest())).substring(0, 16); + String hash = String.format("%X", new BigInteger(1, md.digest())).substring(0, 16); channelId = CH_MSG_PREFIX + CH_MSG_VERSION + "_" + hash; if (chatId!=0) { From cf3d22f6ea491b1d5d2637731432743790329b94 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Sat, 23 May 2020 00:37:00 +0200 Subject: [PATCH 36/41] handle null in ringtones more carefully, thanks @Hocuri --- .../notifications/NotificationCenter.java | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index dcafee5f5..f7367ee4c 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -17,6 +17,7 @@ import android.text.TextUtils; import android.util.Log; import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import androidx.core.app.RemoteInput; @@ -58,12 +59,12 @@ public class NotificationCenter { this.context = dcContext.context.getApplicationContext(); } - private Uri effectiveSound(int chatId) { // chatId=0: return app-global setting - Uri chatRingtone = Prefs.getChatRingtone(context, chatId); + private @Nullable Uri effectiveSound(int chatId) { // chatId=0: return app-global setting + @Nullable Uri chatRingtone = Prefs.getChatRingtone(context, chatId); if (chatRingtone!=null) { return chatRingtone; } else { - Uri appDefaultRingtone = Prefs.getNotificationRingtone(context); + @NonNull Uri appDefaultRingtone = Prefs.getNotificationRingtone(context); if (!TextUtils.isEmpty(appDefaultRingtone.toString())) { return appDefaultRingtone; } @@ -157,13 +158,13 @@ public class NotificationCenter { } // full name is "ch_msgV_HASH" or "ch_msgV_HASH.CHATID" - private String computeChannelId(String ledColor, boolean vibrate, Uri ringtone, int chatId) { + private String computeChannelId(String ledColor, boolean vibrate, @Nullable Uri ringtone, int chatId) { 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.toString().getBytes()); + md.update((ringtone != null ? ringtone.toString() : "").getBytes()); if (chatId!=0) { // for multi-account, force different channelIds for maybe the same chatIds in multiple accounts md.update(dcContext.getConfig("addr").getBytes()); @@ -205,10 +206,10 @@ public class NotificationCenter { if(notificationChannelsSupported()) { try { // get all values we'll use as settings for the NotificationChannel - String ledColor = Prefs.getNotificationLedColor(context); - boolean defaultVibrate = effectiveVibrate(chatId); - Uri ringtone = effectiveSound(chatId); - boolean isIndependent = requiresIndependentChannel(chatId); + String ledColor = Prefs.getNotificationLedColor(context); + boolean defaultVibrate = effectiveVibrate(chatId); + @Nullable Uri ringtone = effectiveSound(chatId); + boolean isIndependent = requiresIndependentChannel(chatId); // get channel id from these settings channelId = computeChannelId(ledColor, defaultVibrate, ringtone, isIndependent? chatId : 0); From a65a463bf9074cf97defa2bc8ba0b9820bbd7c14 Mon Sep 17 00:00:00 2001 From: bjoern Date: Sat, 23 May 2020 00:46:34 +0200 Subject: [PATCH 37/41] Update src/org/thoughtcrime/securesms/notifications/NotificationCenter.java Co-authored-by: Hocuri --- .../securesms/notifications/NotificationCenter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index f7367ee4c..411ebabc1 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -203,7 +203,7 @@ public class NotificationCenter { int chatId = dcChat.getId(); String channelId = CH_MSG_PREFIX; - if(notificationChannelsSupported()) { + if (notificationChannelsSupported()) { try { // get all values we'll use as settings for the NotificationChannel String ledColor = Prefs.getNotificationLedColor(context); From f30da6e912165f9a03eebfa49c5ea4dbeefc9964 Mon Sep 17 00:00:00 2001 From: bjoern Date: Sat, 23 May 2020 00:49:41 +0200 Subject: [PATCH 38/41] Update src/org/thoughtcrime/securesms/notifications/NotificationCenter.java Co-authored-by: Hocuri --- .../securesms/notifications/NotificationCenter.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index 411ebabc1..bbfe87544 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -176,7 +176,9 @@ public class NotificationCenter { channelId += String.format(".%d", chatId); } - } catch(Exception e) { } + } catch(Exception e) { + Log.e(TAG, e.toString()); + } return channelId; } From 050c358859fc3c802c92481d5dc383e2d8d5981e Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Sat, 23 May 2020 13:10:01 +0200 Subject: [PATCH 39/41] make in-chat-sounds respect notification- and mute-settings --- res/xml/preferences_notifications.xml | 1 + .../securesms/ConversationActivity.java | 3 +-- .../securesms/notifications/InChatSounds.java | 8 ++------ .../notifications/NotificationCenter.java | 16 +++++++++++----- 4 files changed, 15 insertions(+), 13 deletions(-) diff --git a/res/xml/preferences_notifications.xml b/res/xml/preferences_notifications.xml index 8c885c30e..3971ff3bb 100644 --- a/res/xml/preferences_notifications.xml +++ b/res/xml/preferences_notifications.xml @@ -53,6 +53,7 @@ diff --git a/src/org/thoughtcrime/securesms/ConversationActivity.java b/src/org/thoughtcrime/securesms/ConversationActivity.java index fbfcdbbe9..6b352990d 100644 --- a/src/org/thoughtcrime/securesms/ConversationActivity.java +++ b/src/org/thoughtcrime/securesms/ConversationActivity.java @@ -93,7 +93,6 @@ import org.thoughtcrime.securesms.mms.GlideRequests; import org.thoughtcrime.securesms.mms.MediaConstraints; import org.thoughtcrime.securesms.mms.PartAuthority; import org.thoughtcrime.securesms.mms.SlideDeck; -import org.thoughtcrime.securesms.notifications.InChatSounds; import org.thoughtcrime.securesms.permissions.Permissions; import org.thoughtcrime.securesms.providers.PersistentBlobProvider; import org.thoughtcrime.securesms.recipients.Recipient; @@ -1443,7 +1442,7 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity } else { processComposeControls(ACTION_SEND_OUT); - InChatSounds.getInstance(ConversationActivity.this).playSendSound(); + dcContext.notificationCenter.maybePlaySendSound(dcChat); } } diff --git a/src/org/thoughtcrime/securesms/notifications/InChatSounds.java b/src/org/thoughtcrime/securesms/notifications/InChatSounds.java index 7a40dda29..7fad06f85 100644 --- a/src/org/thoughtcrime/securesms/notifications/InChatSounds.java +++ b/src/org/thoughtcrime/securesms/notifications/InChatSounds.java @@ -41,9 +41,7 @@ public class InChatSounds { public void playSendSound() { try { - if (Prefs.isInChatNotifications(appContext)) { - soundPool.play(soundOut, 1.0f, 1.0f, 1, 0, 1.0f); - } + soundPool.play(soundOut, 1.0f, 1.0f, 1, 0, 1.0f); } catch(Exception e) { Log.e(TAG, "cannot play send sound", e); } @@ -51,9 +49,7 @@ public class InChatSounds { public void playIncomingSound() { try { - if (Prefs.isInChatNotifications(appContext)) { - soundPool.play(soundIn, 1.0f, 1.0f, 1, 0, 1.0f); - } + soundPool.play(soundIn, 1.0f, 1.0f, 1, 0, 1.0f); } catch(Exception e) { Log.e(TAG, "cannot play incoming sound", e); } diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index bbfe87544..8788e7a67 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -289,14 +289,14 @@ public class NotificationCenter { DcChat dcChat = dcContext.getChat(chatId); - if (chatId == visibleChatId) { - // in-chat sounds are not related to notifications, - // they can be enabled/disabled independently - InChatSounds.getInstance(context).playIncomingSound(); + if (!Prefs.isNotificationsEnabled(context) || dcChat.isMuted()) { return; } - if (!Prefs.isNotificationsEnabled(context) || dcChat.isMuted()) { + if (chatId == visibleChatId) { + if (Prefs.isInChatNotifications(context)) { + InChatSounds.getInstance(context).playIncomingSound(); + } return; } @@ -482,4 +482,10 @@ public class NotificationCenter { }); } + + public void maybePlaySendSound(DcChat dcChat) { + if (Prefs.isNotificationsEnabled(context) && !dcChat.isMuted()) { + InChatSounds.getInstance(context).playSendSound(); + } + } } From e8a3bae004f730ee5499cca657dd5f90b0faf079 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Mon, 25 May 2020 14:18:00 +0200 Subject: [PATCH 40/41] re-add mark-read action button --- .../notifications/MarkReadReceiver.java | 24 ++++++++++++------- .../notifications/NotificationCenter.java | 20 +++++++++++++--- .../notifications/NotificationState.java | 4 ++-- 3 files changed, 34 insertions(+), 14 deletions(-) diff --git a/src/org/thoughtcrime/securesms/notifications/MarkReadReceiver.java b/src/org/thoughtcrime/securesms/notifications/MarkReadReceiver.java index 7ffe4b61b..add98df8b 100644 --- a/src/org/thoughtcrime/securesms/notifications/MarkReadReceiver.java +++ b/src/org/thoughtcrime/securesms/notifications/MarkReadReceiver.java @@ -5,26 +5,32 @@ package org.thoughtcrime.securesms.notifications; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; -import android.os.AsyncTask; import org.thoughtcrime.securesms.connect.ApplicationDcContext; import org.thoughtcrime.securesms.connect.DcHelper; +import org.thoughtcrime.securesms.util.Util; public class MarkReadReceiver extends BroadcastReceiver { - private static final String TAG = MarkReadReceiver.class.getSimpleName(); public static final String CLEAR_ACTION = "org.thoughtcrime.securesms.notifications.CLEAR"; - public static final String CHAT_IDS_EXTRA = "chat_ids"; - public static final String NOTIFICATION_ID_EXTRA = "notification_id"; + public static final String CHAT_ID_EXTRA = "chat_id"; @Override public void onReceive(final Context context, Intent intent) { - if (!CLEAR_ACTION.equals(intent.getAction())) + if (!CLEAR_ACTION.equals(intent.getAction())) { return; + } - final int[] chatIds = intent.getIntArrayExtra(CHAT_IDS_EXTRA); - MessageNotifierCompat.removeNotifications(chatIds); - ApplicationDcContext dcContext = DcHelper.getContext(context); - new MarkAsNoticedAsyncTask(chatIds, dcContext, true).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + final int chatId = intent.getIntExtra(CHAT_ID_EXTRA, 0); + if (chatId==0) { + return; + } + + final ApplicationDcContext dcContext = DcHelper.getContext(context); + + Util.runOnAnyBackgroundThread(() -> { + dcContext.notificationCenter.removeNotifications(chatId); + dcContext.marknoticedChat(chatId); + }); } } diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java index 8788e7a67..3e9503b3a 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationCenter.java @@ -116,6 +116,14 @@ public class NotificationCenter { return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } + private PendingIntent getMarkAsReadIntent(int chatId) { + Intent intent = new Intent(MarkReadReceiver.CLEAR_ACTION); + intent.setClass(context, MarkReadReceiver.class); + intent.setData((Uri.parse("custom://"+System.currentTimeMillis()))); + intent.putExtra(MarkReadReceiver.CHAT_ID_EXTRA, chatId); + intent.setPackage(context.getPackageName()); + return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); + } // Groups and Notification channel groups @@ -395,12 +403,17 @@ public class NotificationCenter { } catch (Exception e) { Log.w(TAG, e); } } - // add a reply-button that allows answering without opening Delta Chat. - // the reply-button is useful only if sender+message is displayed and if app-lock is disabled. + // 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() && !Prefs.isScreenLockEnabled(context)) { try { PendingIntent inNotificationReplyIntent = getRemoteReplyIntent(chatId); + PendingIntent markReadIntent = getMarkAsReadIntent(chatId); + + NotificationCompat.Action markAsReadAction = new NotificationCompat.Action(R.drawable.check, + context.getString(R.string.notify_mark_read), + markReadIntent); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(R.drawable.ic_reply_white_36dp, @@ -418,7 +431,8 @@ public class NotificationCenter { .addRemoteInput(new RemoteInput.Builder(RemoteReplyReceiver.EXTRA_REMOTE_REPLY) .setLabel(context.getString(R.string.notify_reply_button)).build()) .build(); - builder.extend(new NotificationCompat.WearableExtender().addAction(wearableReplyAction)); + builder.addAction(markAsReadAction); + builder.extend(new NotificationCompat.WearableExtender().addAction(markAsReadAction).addAction(wearableReplyAction)); } catch(Exception e) { Log.w(TAG, e); } } diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationState.java b/src/org/thoughtcrime/securesms/notifications/NotificationState.java index 79bc723ac..2d3f37825 100644 --- a/src/org/thoughtcrime/securesms/notifications/NotificationState.java +++ b/src/org/thoughtcrime/securesms/notifications/NotificationState.java @@ -134,8 +134,8 @@ public class NotificationState { Intent intent = new Intent(MarkReadReceiver.CLEAR_ACTION); intent.setClass(context, MarkReadReceiver.class); intent.setData((Uri.parse("custom://"+System.currentTimeMillis()))); - intent.putExtra(MarkReadReceiver.CHAT_IDS_EXTRA, chatArray); - intent.putExtra(MarkReadReceiver.NOTIFICATION_ID_EXTRA, notificationId); + //intent.putExtra(MarkReadReceiver.CHAT_IDS_EXTRA, chatArray); + //intent.putExtra(MarkReadReceiver.NOTIFICATION_ID_EXTRA, notificationId); return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } From fe0b1cecd273624b1934062cc1046f8ea4a8e113 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Mon, 25 May 2020 14:30:35 +0200 Subject: [PATCH 41/41] remove dead code --- .../AbstractNotificationBuilder.java | 214 --------- .../notifications/MarkAsNoticedAsyncTask.java | 40 -- .../notifications/MessageNotifier.java | 412 ------------------ .../notifications/MessageNotifierApi23.java | 56 --- .../notifications/MessageNotifierCompat.java | 54 --- .../MessageNotifierPreApi23.java | 82 ---- .../MultipleRecipientNotificationBuilder.java | 147 ------- .../notifications/NotificationItem.java | 87 ---- .../notifications/NotificationState.java | 142 ------ .../SingleRecipientNotificationBuilder.java | 250 ----------- 10 files changed, 1484 deletions(-) delete mode 100644 src/org/thoughtcrime/securesms/notifications/AbstractNotificationBuilder.java delete mode 100644 src/org/thoughtcrime/securesms/notifications/MarkAsNoticedAsyncTask.java delete mode 100644 src/org/thoughtcrime/securesms/notifications/MessageNotifier.java delete mode 100644 src/org/thoughtcrime/securesms/notifications/MessageNotifierApi23.java delete mode 100644 src/org/thoughtcrime/securesms/notifications/MessageNotifierCompat.java delete mode 100644 src/org/thoughtcrime/securesms/notifications/MessageNotifierPreApi23.java delete mode 100644 src/org/thoughtcrime/securesms/notifications/MultipleRecipientNotificationBuilder.java delete mode 100644 src/org/thoughtcrime/securesms/notifications/NotificationItem.java delete mode 100644 src/org/thoughtcrime/securesms/notifications/NotificationState.java delete mode 100644 src/org/thoughtcrime/securesms/notifications/SingleRecipientNotificationBuilder.java diff --git a/src/org/thoughtcrime/securesms/notifications/AbstractNotificationBuilder.java b/src/org/thoughtcrime/securesms/notifications/AbstractNotificationBuilder.java deleted file mode 100644 index 9225cf536..000000000 --- a/src/org/thoughtcrime/securesms/notifications/AbstractNotificationBuilder.java +++ /dev/null @@ -1,214 +0,0 @@ -package org.thoughtcrime.securesms.notifications; - -import android.app.NotificationChannel; -import android.app.NotificationManager; -import android.content.Context; -import android.graphics.Color; -import android.media.AudioManager; -import android.net.Uri; -import android.os.Build; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.core.app.NotificationCompat; -import android.text.SpannableStringBuilder; -import android.text.TextUtils; - -import org.thoughtcrime.securesms.R; -import org.thoughtcrime.securesms.preferences.widgets.NotificationPrivacyPreference; -import org.thoughtcrime.securesms.recipients.Recipient; -import org.thoughtcrime.securesms.util.Prefs; -import org.thoughtcrime.securesms.util.Util; - -import java.math.BigInteger; -import java.security.MessageDigest; -import java.util.List; - -abstract class AbstractNotificationBuilder extends NotificationCompat.Builder { - - @SuppressWarnings("unused") - private static final String TAG = AbstractNotificationBuilder.class.getSimpleName(); - - protected Context context; - protected NotificationPrivacyPreference privacy; - private int notificationId; - private Uri ringtone; - private boolean vibrate; - - AbstractNotificationBuilder(Context context, NotificationPrivacyPreference privacy) { - super(context, createMsgNotificationChannel(context)); - - this.context = context; - this.privacy = privacy; - - setLed(); - } - - CharSequence getStyledMessage(@NonNull Recipient recipient, @Nullable CharSequence message) { - SpannableStringBuilder builder = new SpannableStringBuilder(); - builder.append(Util.getBoldedString(recipient.toShortString())); - builder.append(": "); - builder.append(message == null ? "" : message); - - return builder; - } - - // Alarms are not set in the notification or the notification channel but handled separately - // by the MessageNotifier. It allows us to dynamically turn on and off the sounds and as well as - // to change vibration and sounds during runtime - void setAlarms(int systemRingerMode, @Nullable Uri ringtone, Prefs.VibrateState vibrate) { - Uri appDefaultRingtone = Prefs.getNotificationRingtone(context); - boolean appDefaultVibrate = Prefs.isNotificationVibrateEnabled(context); - if (systemRingerMode == AudioManager.RINGER_MODE_NORMAL) { - if (ringtone == null && !TextUtils.isEmpty(appDefaultRingtone.toString())) { - this.ringtone = appDefaultRingtone; - } else if (ringtone != null && !ringtone.toString().isEmpty()) { - this.ringtone = ringtone; - } - } - - this.vibrate = (systemRingerMode != AudioManager.RINGER_MODE_SILENT) && - (vibrate == Prefs.VibrateState.ENABLED || - (vibrate == Prefs.VibrateState.DEFAULT && appDefaultVibrate)); - } - - private void setLed() { - /* - String ledColor = Prefs.getNotificationLedColor(context); - String ledBlinkPattern = Prefs.getNotificationLedPattern(context); - String ledBlinkPatternCustom = Prefs.getNotificationLedPatternCustom(context); - - if (!ledColor.equals("none")) { - String[] blinkPatternArray = parseBlinkPattern(ledBlinkPattern, ledBlinkPatternCustom); - int argb; - try { - argb = Color.parseColor(ledColor); - } - catch (Exception e) { - argb = Color.rgb(0xFF, 0xFF, 0xFF); - } - setLights(argb, - Integer.parseInt(blinkPatternArray[0]), - Integer.parseInt(blinkPatternArray[1])); - } - */ - } - - void setTicker(@NonNull Recipient recipient, @Nullable CharSequence message) { - if (privacy.isDisplayMessage()) { - setTicker(getStyledMessage(recipient, message)); - } else if (privacy.isDisplayContact()) { - setTicker(getStyledMessage(recipient, context.getString(R.string.notify_new_message))); - } else { - setTicker(context.getString(R.string.notify_new_message)); - } - } - - private String[] parseBlinkPattern(String blinkPattern, String blinkPatternCustom) { - if (blinkPattern.equals("custom")) - blinkPattern = blinkPatternCustom; - - return blinkPattern.split(","); - } - - // handle NotificationChannels: - // - since oreo, a NotificationChannel is a MUST - // - NotificationChannels have default values that have a higher precedence as the Notification.Builder setting - // - once created, NotificationChannels cannot be modified programmatically - // - NotificationChannels can be deleted, however, on re-creation it becomes un-deleted with the old settings - // - the idea is that sound and vibrate are handled outside of the scope of the notification channel - - private static String createMsgNotificationChannel(Context context) { - String chBase = "ch_msg3_"; - String chId = chBase + "unsupported"; - - if(notificationChannelsSupported()) { - try { - NotificationManager notificationManager = context.getSystemService(NotificationManager.class); - - // get all values we'll use as settings for the NotificationChannel - String ledColor = Prefs.getNotificationLedColor(context); - - // compute hash from these settings - String hash = ""; - MessageDigest md = MessageDigest.getInstance("SHA-256"); - md.update(ledColor.getBytes()); - hash = String.format("%X", new BigInteger(1, md.digest())).substring(0, 16); - - // get channel name - chId = chBase + hash; - String oldChId = Prefs.getStringPreference(context, "ch_curr_" + chBase, ""); - if (!oldChId.equals(chId)) { - try { - notificationManager.deleteNotificationChannel(oldChId); - } - catch (Exception e) { - // channel not created before - } - Prefs.setStringPreference(context, "ch_curr_" + chBase, chId); - } - - // 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++) { - if (chId.equals(channels.get(i).getId())) { - channelExists = true; - } - } - - // 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(chId, - "New messages", NotificationManager.IMPORTANCE_HIGH); - channel.setDescription("Informs about new messages."); - - if (!ledColor.equals("none")) { - channel.enableLights(true); - int argb; - try { - argb = Color.parseColor(ledColor); - } - catch (Exception e) { - argb = Color.rgb(0xFF, 0xFF, 0xFF); - } - channel.setLightColor(argb); - } else { - channel.enableLights(false); - } - - channel.setSound(null, null); - channel.enableVibration(false); - - notificationManager.createNotificationChannel(channel); - } - } - catch(Exception e) { - e.printStackTrace(); - } - } - - return chId; - } - - private static boolean notificationChannelsSupported() { - return Build.VERSION.SDK_INT >= 26; - } - - - public void setNotificationId(int notificationId) { - this.notificationId = notificationId; - } - - public int getNotificationId() { - return this.notificationId; - } - - public Uri getRingtone() { - return this.ringtone; - } - - public boolean getVibrate() { - return this.vibrate; - } -} diff --git a/src/org/thoughtcrime/securesms/notifications/MarkAsNoticedAsyncTask.java b/src/org/thoughtcrime/securesms/notifications/MarkAsNoticedAsyncTask.java deleted file mode 100644 index 8f8d3eca6..000000000 --- a/src/org/thoughtcrime/securesms/notifications/MarkAsNoticedAsyncTask.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.thoughtcrime.securesms.notifications; - -import android.os.AsyncTask; - -import org.thoughtcrime.securesms.connect.ApplicationDcContext; - -/** - * This marks the messages the user has acknowledged as noticed. - * @author Angelo Fuchs - */ -public class MarkAsNoticedAsyncTask extends AsyncTask { - private final int[] ids; - private final ApplicationDcContext dcContext; - private final boolean isChat; - - /** - * goes through the given messages or chats and marks them as notified. - * @param ids chat or messages ids to be marked. - * @param dcContext the applications context - * @param isChat true if the ids are chat ids, false to signify message ids. - */ - MarkAsNoticedAsyncTask(int[] ids, ApplicationDcContext dcContext, boolean isChat) { - this.ids = ids; - this.dcContext = dcContext; - this.isChat = isChat; - } - - @Override - protected Void doInBackground(Void... params) { - for (int id : ids) { - if (isChat) - dcContext.marknoticedChat(id); - else - dcContext.marknoticedChat(dcContext.getMsg(id).getChatId()); - } - - return null; - } -} - diff --git a/src/org/thoughtcrime/securesms/notifications/MessageNotifier.java b/src/org/thoughtcrime/securesms/notifications/MessageNotifier.java deleted file mode 100644 index 2bd245a73..000000000 --- a/src/org/thoughtcrime/securesms/notifications/MessageNotifier.java +++ /dev/null @@ -1,412 +0,0 @@ -package org.thoughtcrime.securesms.notifications; - -import android.app.NotificationManager; -import android.content.Context; -import android.media.AudioManager; -import android.media.Ringtone; -import android.media.RingtoneManager; -import android.media.SoundPool; -import android.net.Uri; -import android.os.Vibrator; -import androidx.annotation.NonNull; -import androidx.core.app.NotificationManagerCompat; -import android.text.TextUtils; -import android.util.Log; - -import com.b44t.messenger.DcChat; -import com.b44t.messenger.DcContext; -import com.b44t.messenger.DcMsg; - -import org.thoughtcrime.securesms.R; -import org.thoughtcrime.securesms.connect.ApplicationDcContext; -import org.thoughtcrime.securesms.connect.DcHelper; -import org.thoughtcrime.securesms.mms.SlideDeck; -import org.thoughtcrime.securesms.recipients.Recipient; -import org.thoughtcrime.securesms.util.Prefs; -import org.thoughtcrime.securesms.util.ServiceUtil; -import org.thoughtcrime.securesms.util.SpanUtil; - -import java.util.LinkedList; -import java.util.List; -import java.util.ListIterator; -import java.util.concurrent.TimeUnit; - -import static org.thoughtcrime.securesms.notifications.MessageNotifierCompat.NO_VISIBLE_CHAT_ID; -import static org.thoughtcrime.securesms.notifications.MessageNotifierCompat.SUMMARY_NOTIFICATION_ID; - -abstract class MessageNotifier { - - static final String TAG = org.thoughtcrime.securesms.notifications.MessageNotifierApi23.class.getSimpleName(); - - private static final String NOTIFICATION_GROUP = "messages"; - private static final long MIN_AUDIBLE_PERIOD_MILLIS = TimeUnit.SECONDS.toMillis(20); - private static final long STARTUP_SILENCE_DELTA = TimeUnit.MINUTES.toMillis(1); - private static final long INITIAL_STARTUP = System.currentTimeMillis(); - - static volatile int visibleChatId = NO_VISIBLE_CHAT_ID; - static volatile long lastAudibleNotification = -1; - final NotificationState notificationState; - final Context appContext; - final Object lock; - private final SoundPool soundPool; - private final AudioManager audioManager; - private final int soundIn; - private final int soundOut; - private boolean soundInLoaded; - private boolean soundOutLoaded; - - MessageNotifier(Context context) { - appContext = context.getApplicationContext(); - soundPool = new SoundPool(3, AudioManager.STREAM_SYSTEM, 0); - audioManager = ServiceUtil.getAudioManager(appContext); - soundIn = soundPool.load(context, R.raw.sound_in, 1); - soundOut = soundPool.load(context, R.raw.sound_out, 1); - notificationState = new NotificationState(); - lock = new Object(); - - soundPool.setOnLoadCompleteListener((soundPool, sampleId, status) -> { - if (status == 0) { - if (sampleId == soundIn) { - soundInLoaded = true; - } else if (sampleId == soundOut) { - soundOutLoaded = true; - } - } - }); - } - - public void playSendSound() { - if (Prefs.isInChatNotifications(appContext) && soundOutLoaded) { - soundPool.play(soundOut, 1.0f, 1.0f, 1, 0, 1.0f); - } - } - - public void updateVisibleChat(int chatId) { - visibleChatId = chatId; - if (visibleChatId != NO_VISIBLE_CHAT_ID) { - removeNotifications(visibleChatId); - } - } - - void updateNotification(int chatId, int messageId) { - updateNotification(DcHelper.getContext(appContext).getChat(chatId), messageId); - } - - private void updateNotification(DcChat chat, int messageId) { - boolean isVisible = visibleChatId == chat.getId(); - - if (!Prefs.isNotificationsEnabled(appContext) || - Prefs.isChatMuted(chat)) - { - return; - } - - if (isVisible) { - sendInChatNotification(chat); - } else if (visibleChatId != NO_VISIBLE_CHAT_ID) { - //different chat is on top - sendNotifications(chat, messageId, false); - } else { - //app is in background or different Activity is on top - sendNotifications(chat, messageId, true); - } - } - - /** - * On notification privacy preference changed, - * the notification state needs to be updated. - */ - public void onNotificationPrivacyChanged() { - if (!Prefs.isNotificationsEnabled(appContext)) { - return; - } - - clearNotifications(); - ApplicationDcContext dcContext = DcHelper.getContext(appContext); - int[] freshMessages = dcContext.getFreshMsgs(); - for (int message : freshMessages) { - DcMsg record = dcContext.getMsg(message); - updateNotification(dcContext.getChat(record.getChatId()), record.getId()); - } - } - - public void removeNotifications(int[] chatIds) { - List removedItems = new LinkedList<>(); - synchronized (lock) { - for (int id : chatIds) { - removedItems.addAll(notificationState.removeNotificationsForChat(id)); - } - } - cancelNotifications(removedItems); - recreateSummaryNotification(); - } - - public void removeNotifications(int chatId) { - List removedItems; - synchronized (lock) { - removedItems = notificationState.removeNotificationsForChat(chatId); - } - cancelNotifications(removedItems); - recreateSummaryNotification(); - } - - void cancelNotifications(List removedItems) { - NotificationManager notifications = ServiceUtil.getNotificationManager(appContext); - for (NotificationItem item : removedItems) { - notifications.cancel(item.getId()); - } - } - - private void recreateSummaryNotification() { - NotificationManager notifications = ServiceUtil.getNotificationManager(appContext); - notifications.cancel(SUMMARY_NOTIFICATION_ID); - - synchronized (lock) { - if (notificationState.hasMultipleChats()) { - for (Integer id : notificationState.getChats()) { - sendSingleChatNotification(appContext, new NotificationState(notificationState.getNotificationsForChat(id)), false, true); - } - sendMultipleChatNotification(appContext, notificationState, false); - } else { - sendSingleChatNotification(appContext, notificationState, false, false); - } - } - } - - void cancelActiveNotifications() { - NotificationManager notifications = ServiceUtil.getNotificationManager(appContext); - notifications.cancel(SUMMARY_NOTIFICATION_ID); - } - - void sendNotifications(DcChat chat, int messageId, boolean signal) { - ApplicationDcContext dcContext = DcHelper.getContext(appContext); - if (signal = isSignalAllowed(signal)) { - lastAudibleNotification = System.currentTimeMillis(); - } - - if (chat.isDeviceTalk()) { - // currently, we just never notify on device chat. - // esp. on first start, this is annoying. - return; - } - - synchronized (lock) { - addMessageToNotificationState(dcContext, chat, messageId); - if (notificationState.hasMultipleChats()) { - for (int id : notificationState.getChats()) { - sendSingleChatNotification(appContext, new NotificationState(notificationState.getNotificationsForChat(id)), false, true); - } - sendMultipleChatNotification(appContext, notificationState, signal); - } else { - sendSingleChatNotification(appContext, notificationState, signal, false); - } - } - } - - boolean isSignalAllowed(boolean signalRequested) { - long now = System.currentTimeMillis(); - return signalRequested && - (now - INITIAL_STARTUP) > STARTUP_SILENCE_DELTA && - (now - lastAudibleNotification) > MIN_AUDIBLE_PERIOD_MILLIS; - } - - private void clearNotifications() { - synchronized (lock) { - notificationState.reset(); - } - cancelActiveNotifications(); - } - - void sendSingleChatNotification(@NonNull Context context, - @NonNull NotificationState notificationState, - boolean signal, - boolean bundled) - { - AbstractNotificationBuilder notificationBuilder = createSingleChatNotification(context, notificationState, signal, bundled); - if (notificationBuilder != null) - notify(context, notificationBuilder.getNotificationId(), notificationBuilder, signal); - } - - void sendMultipleChatNotification(@NonNull Context context, - @NonNull NotificationState notificationState, - boolean signal) - { - AbstractNotificationBuilder notificationBuilder = createMultipleChatNotification(context, notificationState, signal); - if (notificationBuilder != null) - notify(context, SUMMARY_NOTIFICATION_ID, notificationBuilder, signal); - } - - protected AbstractNotificationBuilder createSingleChatNotification(@NonNull Context context, - @NonNull NotificationState notificationState, - boolean signal, - boolean bundled) { - if (notificationState.getNotifications().isEmpty()) { - if (!bundled) cancelActiveNotifications(); - return null; - } - - SingleRecipientNotificationBuilder builder = new SingleRecipientNotificationBuilder(context, Prefs.getNotificationPrivacy(context)); - List notifications = notificationState.getNotifications(); - NotificationItem firstItem = notifications.get(0); - Recipient recipient = firstItem.getRecipient(); - int chatId = firstItem.getChatId(); - int notificationId = (SUMMARY_NOTIFICATION_ID + (bundled ? chatId : 0)); - - builder.setNotificationId(notificationId); - builder.setChat(firstItem.getRecipient()); - builder.setMessageCount(notificationState.getMessageCount()); - builder.setPrimaryMessageBody(recipient, firstItem.getIndividualRecipient(), - firstItem.getText(""), firstItem.getSlideDeck()); - builder.setContentIntent(firstItem.getPendingIntent(context)); - builder.setGroup(NOTIFICATION_GROUP); - builder.setDeleteIntent(notificationState.getMarkAsReadIntent(context, chatId, notificationId)); - - long timestamp = firstItem.getTimestamp(); - if (timestamp != 0) builder.setWhen(timestamp); - - //builder.addActions(notificationState.getMarkAsReadIntent(context, chatId, notificationId), - // notificationState.getRemoteReplyIntent(context, recipient)); - - ListIterator iterator = notifications.listIterator(notifications.size()); - - while(iterator.hasPrevious()) { - NotificationItem item = iterator.previous(); - builder.addMessageBody(item.getRecipient(), item.getIndividualRecipient(), item.getText()); - } - - if (signal) { - builder.setAlarms(audioManager.getRingerMode(), - notificationState.getRingtone(context), - notificationState.getVibrate(context)); - builder.setTicker(firstItem.getIndividualRecipient(), - firstItem.getText()); - } - - if (!bundled) { - builder.setGroupSummary(true); - } - - return builder; - - - } - - private void playNotificationSound(Uri uri, boolean vibrate) { - if(uri != null) { - Ringtone ringtone = RingtoneManager.getRingtone(appContext, uri); - - if (ringtone != null) { - ringtone.play(); - } - } // else we selected "no sound" - - if (vibrate) { - Vibrator v = (Vibrator) appContext.getSystemService(Context.VIBRATOR_SERVICE); - if (v!=null) { - v.vibrate(100); - v.vibrate(200); - } - } - } - - protected AbstractNotificationBuilder createMultipleChatNotification(@NonNull Context context, - @NonNull NotificationState notificationState, - boolean signal) { - MultipleRecipientNotificationBuilder builder = new MultipleRecipientNotificationBuilder(context, Prefs.getNotificationPrivacy(context)); - List notifications = notificationState.getNotifications(); - NotificationItem firstItem = notifications.get(0); - - builder.setMessageCount(notificationState.getMessageCount(), notificationState.getChatCount()); - builder.setMostRecentSender(firstItem.getIndividualRecipient()); - builder.setGroup(NOTIFICATION_GROUP); - builder.setDeleteIntent(notificationState.getMarkAsReadIntent(context, 0, SUMMARY_NOTIFICATION_ID)); - - long timestamp = firstItem.getTimestamp(); - if (timestamp != 0) builder.setWhen(timestamp); - - builder.addActions(notificationState.getMarkAsReadIntent(context, 0, SUMMARY_NOTIFICATION_ID)); - - ListIterator iterator = notifications.listIterator(notifications.size()); - - while(iterator.hasPrevious()) { - NotificationItem item = iterator.previous(); - builder.addMessageBody(item.getRecipient(), item.getIndividualRecipient(), item.getText()); - } - - if (signal) { - builder.setAlarms(audioManager.getRingerMode(), - notificationState.getRingtone(context), - notificationState.getVibrate(context)); - builder.setTicker(firstItem.getIndividualRecipient(), - firstItem.getText()); - } - - return builder; - } - - private void notify(Context context, int notificationId, AbstractNotificationBuilder notificationBuilder, boolean signal) { - if (signal) { - playNotificationSound(notificationBuilder.getRingtone(), notificationBuilder.getVibrate()); - } - NotificationManagerCompat.from(context).notify(notificationId, notificationBuilder.build()); - } - - private void sendInChatNotification(DcChat chat) { - if (!Prefs.isInChatNotifications(appContext) || - audioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) - { - return; - } - - if(Prefs.isChatMuted(chat)) { - Log.d(TAG, "chat muted"); - return; - } - - if (soundInLoaded) { - soundPool.play(soundIn, 1.0f, 1.0f, 1, 0, 1.0f); - } - } - - void addMessageToNotificationState(ApplicationDcContext dcContext, DcChat chat, int msgId) { - if (Prefs.isChatMuted(chat)) { - return; - } - - DcMsg record = dcContext.getMsg(msgId); - if (record.isInfo()) { - return; - } - - int id = record.getId(); - CharSequence body = record.getDisplayBody(); - DcMsg dcMsg = dcContext.getMsg(msgId); - Recipient chatRecipient = new Recipient(appContext, dcContext.getChat(dcMsg.getChatId()), null); - Recipient individualRecipient = new Recipient(appContext, null, dcContext.getContact(dcMsg.getFromId())); - SlideDeck slideDeck = new SlideDeck(dcContext.context, record); - long timestamp = record.getTimestamp(); - - - if(slideDeck.getSlides().isEmpty()) - slideDeck = null; - - // TODO: if message content should be hidden on screen lock, do it here. - if (record.hasFile() && TextUtils.isEmpty(body)) { - String summaryText = record.getSummarytext(100); - if (summaryText.isEmpty()) { - body = SpanUtil.italic(appContext.getString(R.string.notify_media_message)); - } else { - body = SpanUtil.italic(summaryText); - } - } else if (record.hasFile() && !record.isMediaPending()) { - String message = appContext.getString(R.string.notify_media_message_with_text, body); - int italicLength = message.length() - body.length(); - body = SpanUtil.italic(message, italicLength); - } - - synchronized (lock) { - notificationState.addNotification(new NotificationItem(id, chatRecipient, individualRecipient, chat.getId(), body, timestamp, slideDeck)); - } - } -} - diff --git a/src/org/thoughtcrime/securesms/notifications/MessageNotifierApi23.java b/src/org/thoughtcrime/securesms/notifications/MessageNotifierApi23.java deleted file mode 100644 index 2461392f9..000000000 --- a/src/org/thoughtcrime/securesms/notifications/MessageNotifierApi23.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2011 Whisper Systems - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package org.thoughtcrime.securesms.notifications; - -import android.annotation.TargetApi; -import android.app.NotificationManager; -import android.content.Context; -import android.service.notification.StatusBarNotification; -import android.util.Log; - -import org.thoughtcrime.securesms.util.ServiceUtil; - - -/** - * Handles posting system notifications for new messages. - * - */ - -@TargetApi(23) -class MessageNotifierApi23 extends MessageNotifier { - - MessageNotifierApi23(Context context) { - super(context); - } - - void cancelActiveNotifications() { - super.cancelActiveNotifications(); - NotificationManager notifications = ServiceUtil.getNotificationManager(appContext); - try { - - StatusBarNotification[] activeNotifications = notifications.getActiveNotifications(); - for (StatusBarNotification activeNotification : activeNotifications) { - notifications.cancel(activeNotification.getId()); - } - } catch (Throwable e) { - // XXX Appears to be a ROM bug, see #6043 - Log.w(TAG, e); - notifications.cancelAll(); - } - } - - } diff --git a/src/org/thoughtcrime/securesms/notifications/MessageNotifierCompat.java b/src/org/thoughtcrime/securesms/notifications/MessageNotifierCompat.java deleted file mode 100644 index 99e62342a..000000000 --- a/src/org/thoughtcrime/securesms/notifications/MessageNotifierCompat.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.thoughtcrime.securesms.notifications; - -import android.content.Context; -import android.os.Build; - -import org.thoughtcrime.securesms.util.Util; - -public class MessageNotifierCompat { - - public static final int NO_VISIBLE_CHAT_ID = -1; - static final int SUMMARY_NOTIFICATION_ID = 1339; - static final String EXTRA_REMOTE_REPLY = "extra_remote_reply"; - - - private static MessageNotifier instance; - - public static void init(Context context) { - if (instance != null) { - return; - } - - if (Build.VERSION.SDK_INT < 23) { - instance = new MessageNotifierPreApi23(context); - } else { - instance = new MessageNotifierApi23(context); - } - } - - public static void playSendSound() { - instance.playSendSound(); - } - - public static void updateNotification(int chatId, int messageId) { - Util.runOnAnyBackgroundThread(() -> instance.updateNotification(chatId, messageId)); - } - - public static void updateVisibleChat(int chatId) { - Util.runOnAnyBackgroundThread(() -> instance.updateVisibleChat(chatId)); - } - - public static void onNotificationPrivacyChanged() { - Util.runOnAnyBackgroundThread(() -> instance.onNotificationPrivacyChanged()); - } - - static void removeNotifications(int[] chatIds) { - Util.runOnAnyBackgroundThread(() -> instance.removeNotifications(chatIds)); - } - - public static void removeNotifications(int chatId) { - Util.runOnAnyBackgroundThread(() -> instance.removeNotifications(chatId)); - } - - -} diff --git a/src/org/thoughtcrime/securesms/notifications/MessageNotifierPreApi23.java b/src/org/thoughtcrime/securesms/notifications/MessageNotifierPreApi23.java deleted file mode 100644 index 5c622aea4..000000000 --- a/src/org/thoughtcrime/securesms/notifications/MessageNotifierPreApi23.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.thoughtcrime.securesms.notifications; - -import android.content.Context; -import androidx.core.app.NotificationManagerCompat; - -import com.b44t.messenger.DcChat; - -import org.thoughtcrime.securesms.connect.ApplicationDcContext; -import org.thoughtcrime.securesms.connect.DcHelper; - -import java.util.List; - -import static org.thoughtcrime.securesms.notifications.MessageNotifierCompat.SUMMARY_NOTIFICATION_ID; - -class MessageNotifierPreApi23 extends MessageNotifier { - - MessageNotifierPreApi23(Context context) { - super(context); - } - - @Override - public void removeNotifications(int chatId) { - synchronized (lock) { - notificationState.removeNotificationsForChat(chatId); - } - recreateSummaryNotification(); - } - - @Override - public void removeNotifications(int[] chatIds) { - synchronized (lock) { - for (int id : chatIds) { - notificationState.removeNotificationsForChat(id); - } - } - recreateSummaryNotification(); - } - - @Override - void cancelNotifications(List removedItems) { - cancelNotifications(); - } - - @Override - void sendNotifications(DcChat chat, int messageId, boolean signal) { - ApplicationDcContext dcContext = DcHelper.getContext(appContext); - if (signal = isSignalAllowed(signal)) { - lastAudibleNotification = System.currentTimeMillis(); - } - - if (chat.isDeviceTalk()) { - // currently, we just never notify on device chat. - // esp. on first start, this is annoying. - return; - } - - addMessageToNotificationState(dcContext, chat, messageId); - synchronized (lock) { - if (notificationState.hasMultipleChats()) { - sendMultipleChatNotification(appContext, notificationState, signal); - } else { - sendSingleChatNotification(appContext, notificationState, signal, false); - } - } - } - - private void cancelNotifications() { - NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(appContext); - notificationManagerCompat.cancel(SUMMARY_NOTIFICATION_ID); - } - - private void recreateSummaryNotification() { - cancelNotifications(); - synchronized (lock) { - if (notificationState.hasMultipleChats()) { - sendMultipleChatNotification(appContext, notificationState, false); - } else { - sendSingleChatNotification(appContext, notificationState, false, false); - } - } - } -} diff --git a/src/org/thoughtcrime/securesms/notifications/MultipleRecipientNotificationBuilder.java b/src/org/thoughtcrime/securesms/notifications/MultipleRecipientNotificationBuilder.java deleted file mode 100644 index b3769e878..000000000 --- a/src/org/thoughtcrime/securesms/notifications/MultipleRecipientNotificationBuilder.java +++ /dev/null @@ -1,147 +0,0 @@ -package org.thoughtcrime.securesms.notifications; - -import android.app.Notification; -import android.app.PendingIntent; -import android.content.Context; -import android.content.Intent; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.core.app.NotificationCompat; - -import org.thoughtcrime.securesms.ConversationListActivity; -import org.thoughtcrime.securesms.R; -import org.thoughtcrime.securesms.preferences.widgets.NotificationPrivacyPreference; -import org.thoughtcrime.securesms.recipients.Recipient; -import org.thoughtcrime.securesms.util.Prefs; -import org.thoughtcrime.securesms.util.Util; - -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -public class MultipleRecipientNotificationBuilder extends AbstractNotificationBuilder { - - private final LinkedList messageBodies = new LinkedList<>(); - - private static class MessageBody { - final @Nullable Recipient group; - final @NonNull Recipient sender; - final @NonNull CharSequence message; - - MessageBody(@Nullable Recipient group, @NonNull Recipient sender, @NonNull CharSequence message) { - this.group = group; - this.sender = sender; - this.message = message; - } - } - - MultipleRecipientNotificationBuilder(Context context, NotificationPrivacyPreference privacy) { - super(context, privacy); - - setColor(context.getResources().getColor(R.color.delta_primary)); - setSmallIcon(R.drawable.icon_notification); - setContentTitle(context.getString(R.string.app_name)); - setContentIntent(PendingIntent.getActivity(context, 0, new Intent(context, ConversationListActivity.class), 0)); - setCategory(NotificationCompat.CATEGORY_MESSAGE); - setPriority(Prefs.getNotificationPriority(context)); - setGroupSummary(true); - } - - void setMessageCount(int messageCount, int chatCount) { - setSubText(context.getString(R.string.notify_n_messages_in_m_chats, - messageCount, chatCount)); - setContentInfo(String.valueOf(messageCount)); - setNumber(messageCount); // this also sets badges on android8 and newer - } - - void setMostRecentSender(Recipient recipient) { - if (privacy.isDisplayContact()) { - setContentText(context.getString(R.string.notify_most_recent_from, - recipient.toShortString())); - } - } - - void addActions(PendingIntent markAsReadIntent) { - NotificationCompat.Action markAllAsReadAction = new NotificationCompat.Action(R.drawable.check, - context.getString(R.string.notify_mark_all_read), - markAsReadIntent); - addAction(markAllAsReadAction); - extend(new NotificationCompat.WearableExtender().addAction(markAllAsReadAction)); - } - - void addMessageBody(@Nullable Recipient group, @NonNull Recipient sender, @Nullable CharSequence body) { - messageBodies.add(new MessageBody(group, sender, body)); - - if (privacy.isDisplayContact() && sender.getContactUri() != null) { - addPerson(sender.getContactUri().toString()); - } else if (privacy.isDisplayContact() && group != null && group.getContactUri() != null) { - addPerson(group.getContactUri().toString()); - } - } - - @Override - public Notification build() { - if (privacy.isDisplayMessage() || privacy.isDisplayContact()) { - NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle(); - Map> byGroup = new LinkedHashMap<>(); - for (MessageBody body : messageBodies) { - Recipient key = body.group == null ? body.sender : body.group; - if(byGroup.containsKey(key)) { - LinkedList messagebodies = (LinkedList) byGroup.remove(key); - messagebodies.addFirst(body); - byGroup.put(key, messagebodies); - } else { - byGroup.put(key, new LinkedList<>()); - byGroup.get(key).add(body); - } - } - - if (privacy.isDisplayMessage()) { - LinkedList list = new LinkedList<>(byGroup.keySet()); - Iterator iterator = list.descendingIterator(); - while(iterator.hasNext()) { - Recipient nextGroup = iterator.next(); - String groupName = nextGroup.getName(); - List messages = byGroup.get(nextGroup); - String firstMessageSender = messages.get(0).sender.getName(); - if(groupName != null && groupName.equals(firstMessageSender)) { // individual - for (MessageBody body : messages) { - style.addLine(getStyledMessage(body.sender, body.message)); - } - } else { // group chat - style.addLine(Util.getBoldedString(groupName)); - for (MessageBody body : messages) { - style.addLine("- " + getStyledMessage(body.sender, body.message)); - } - } - } - } else if (privacy.isDisplayContact()) { - LinkedList list = new LinkedList<>(byGroup.keySet()); - Iterator iterator = list.descendingIterator(); - while(iterator.hasNext()) { - Recipient nextGroup = iterator.next(); - String groupName = nextGroup.getName(); - List messages = byGroup.get(nextGroup); - String firstMessageSender = messages.get(0).sender.getName(); - if(groupName != null && groupName.equals(firstMessageSender)) { // individual - for (MessageBody body : messages) { - style.addLine(body.sender.getName()); - } - } else { // group chat - style.addLine(Util.getBoldedString(groupName)); - for (MessageBody body : messages) { - style.addLine("- " + body.sender.getName()); - } - } - } - } - - setStyle(style); - } - - return super.build(); - } -} diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationItem.java b/src/org/thoughtcrime/securesms/notifications/NotificationItem.java deleted file mode 100644 index d3e3e60dd..000000000 --- a/src/org/thoughtcrime/securesms/notifications/NotificationItem.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.thoughtcrime.securesms.notifications; - -import android.app.PendingIntent; -import android.content.Context; -import android.content.Intent; -import android.net.Uri; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.core.app.TaskStackBuilder; - -import org.thoughtcrime.securesms.ConversationActivity; -import org.thoughtcrime.securesms.mms.SlideDeck; -import org.thoughtcrime.securesms.recipients.Recipient; - -public class NotificationItem { - - private final int id; - private final @NonNull Recipient threadRecipient; - private final @NonNull Recipient individualRecipient; - private final int chatId; - private final @Nullable CharSequence text; - private final long timestamp; - private final @Nullable SlideDeck slideDeck; - - NotificationItem(int id, - @NonNull Recipient threadRecipient, - @NonNull Recipient individualRecipient, - int chatId, @Nullable CharSequence text, long timestamp, - @Nullable SlideDeck slideDeck) - { - this.id = id; - this.threadRecipient = threadRecipient; - this.individualRecipient = individualRecipient; - this.text = text; - this.chatId = chatId; - this.timestamp = timestamp; - this.slideDeck = slideDeck; - } - - public @NonNull Recipient getRecipient() { - return threadRecipient; - } - - public @Nullable CharSequence getText() { - return text; - } - - public @NonNull CharSequence getText(@NonNull CharSequence defaul) { - return (text == null ? defaul : text); - } - - public long getTimestamp() { - return timestamp; - } - - public int getChatId() { - return chatId; - } - - @NonNull Recipient getIndividualRecipient() { - return individualRecipient; - } - - @Deprecated - public int getThreadId() { - return chatId; - } - - @Nullable SlideDeck getSlideDeck() { - return slideDeck; - } - - @NonNull PendingIntent getPendingIntent(Context context) { - Intent intent = new Intent(context, ConversationActivity.class); - - intent.putExtra(ConversationActivity.CHAT_ID_EXTRA, chatId); - intent.setData((Uri.parse("custom://"+System.currentTimeMillis()))); - - return TaskStackBuilder.create(context) - .addNextIntentWithParentStack(intent) - .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); - } - - public int getId() { - return id; - } -} diff --git a/src/org/thoughtcrime/securesms/notifications/NotificationState.java b/src/org/thoughtcrime/securesms/notifications/NotificationState.java deleted file mode 100644 index 2d3f37825..000000000 --- a/src/org/thoughtcrime/securesms/notifications/NotificationState.java +++ /dev/null @@ -1,142 +0,0 @@ -package org.thoughtcrime.securesms.notifications; - -import android.app.PendingIntent; -import android.content.Context; -import android.content.Intent; -import android.net.Uri; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import android.util.Log; - -import org.thoughtcrime.securesms.recipients.Recipient; -import org.thoughtcrime.securesms.util.Prefs; -import org.thoughtcrime.securesms.util.Prefs.VibrateState; - -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; - -import static org.thoughtcrime.securesms.notifications.MessageNotifierCompat.SUMMARY_NOTIFICATION_ID; - -public class NotificationState { - - private final LinkedList notifications = new LinkedList<>(); - private final LinkedHashSet chats = new LinkedHashSet<>(); - - private int notificationCount = 0; - - NotificationState() {} - - NotificationState(@NonNull List items) { - for (NotificationItem item : items) { - addNotification(item); - } - } - - public void reset() { - notificationCount = 0; - notifications.clear(); - chats.clear(); - } - - void addNotification(NotificationItem item) { - notifications.addFirst(item); - - if (chats.contains(item.getChatId())) { - chats.remove(item.getChatId()); - } - - chats.add(item.getChatId()); - notificationCount++; - } - - @Nullable Uri getRingtone(Context context) { - if (!notifications.isEmpty()) { - Recipient recipient = notifications.iterator().next().getRecipient(); - if (recipient.getAddress().isDcChat()) { - return Prefs.getChatRingtone(context, recipient.getAddress().getDcChatId()); - } - } - - return null; - } - - VibrateState getVibrate(Context context) { - if (!notifications.isEmpty()) { - Recipient recipient = notifications.iterator().next().getRecipient(); - - if (recipient.getAddress().isDcChat()) { - return Prefs.getChatVibrate(context, recipient.getAddress().getDcChatId()); - } - } - - return VibrateState.DEFAULT; - } - - boolean hasMultipleChats() { - return chats.size() > 1; - } - - public LinkedHashSet getChats() { - return chats; - } - - int getChatCount() { - return chats.size(); - } - - int getMessageCount() { - return notificationCount; - } - - public List getNotifications() { - return notifications; - } - - List getNotificationsForChat(int chatId) { - LinkedList list = new LinkedList<>(); - - for (NotificationItem item : notifications) { - if (item.getChatId() == chatId) list.addFirst(item); - } - - return list; - } - - List removeNotificationsForChat(int chatId) { - LinkedList removedItems = new LinkedList<>(); - chats.remove(chatId); - for (Iterator it = notifications.iterator(); it.hasNext();) { - NotificationItem item = it.next(); - if (item.getChatId() == chatId) { - removedItems.add(item); - it.remove(); - } - } - notificationCount -= removedItems.size(); - return removedItems; - } - - PendingIntent getMarkAsReadIntent(Context context, int chatId, int notificationId) { - int index = 0; - int[] chatArray; - if (notificationId == SUMMARY_NOTIFICATION_ID) { - chatArray = new int[chats.size()]; - for (int chat : chats) { - Log.w("NotificationState", "Added chat: " + chat); - chatArray[index++] = chat; - } - } else { - chatArray = new int[]{chatId}; - } - - Intent intent = new Intent(MarkReadReceiver.CLEAR_ACTION); - intent.setClass(context, MarkReadReceiver.class); - intent.setData((Uri.parse("custom://"+System.currentTimeMillis()))); - //intent.putExtra(MarkReadReceiver.CHAT_IDS_EXTRA, chatArray); - //intent.putExtra(MarkReadReceiver.NOTIFICATION_ID_EXTRA, notificationId); - - return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); - } -} diff --git a/src/org/thoughtcrime/securesms/notifications/SingleRecipientNotificationBuilder.java b/src/org/thoughtcrime/securesms/notifications/SingleRecipientNotificationBuilder.java deleted file mode 100644 index b06536102..000000000 --- a/src/org/thoughtcrime/securesms/notifications/SingleRecipientNotificationBuilder.java +++ /dev/null @@ -1,250 +0,0 @@ -package org.thoughtcrime.securesms.notifications; - -import android.app.Notification; -import android.app.PendingIntent; -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.drawable.Drawable; -import android.net.Uri; -import android.os.Build; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.core.app.NotificationCompat; -import androidx.core.app.NotificationCompat.Action; -import androidx.core.app.RemoteInput; -import android.text.SpannableStringBuilder; -import android.util.Log; - -import com.bumptech.glide.load.engine.DiskCacheStrategy; - -import org.thoughtcrime.securesms.R; -import org.thoughtcrime.securesms.contacts.avatars.ContactPhoto; -import org.thoughtcrime.securesms.contacts.avatars.FallbackContactPhoto; -import org.thoughtcrime.securesms.contacts.avatars.GeneratedContactPhoto; -import org.thoughtcrime.securesms.mms.DecryptableStreamUriLoader; -import org.thoughtcrime.securesms.mms.GlideApp; -import org.thoughtcrime.securesms.mms.Slide; -import org.thoughtcrime.securesms.mms.SlideDeck; -import org.thoughtcrime.securesms.preferences.widgets.NotificationPrivacyPreference; -import org.thoughtcrime.securesms.recipients.Recipient; -import org.thoughtcrime.securesms.util.BitmapUtil; -import org.thoughtcrime.securesms.util.Prefs; -import org.thoughtcrime.securesms.util.ThemeUtil; -import org.thoughtcrime.securesms.util.Util; - -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.ExecutionException; - -public class SingleRecipientNotificationBuilder extends AbstractNotificationBuilder { - - private static final String TAG = SingleRecipientNotificationBuilder.class.getSimpleName(); - - private final LinkedList messageBodies = new LinkedList<>(); - - private SlideDeck slideDeck; - private CharSequence contentTitle; - private CharSequence contentText; - - SingleRecipientNotificationBuilder(@NonNull Context context, @NonNull NotificationPrivacyPreference privacy) - { - super(context, privacy); - - setSmallIcon(R.drawable.icon_notification); - setColor(context.getResources().getColor(R.color.delta_primary)); - setPriority(Prefs.getNotificationPriority(context)); - setCategory(NotificationCompat.CATEGORY_MESSAGE); - } - - public void setChat(@NonNull Recipient recipient) { - if (privacy.isDisplayContact()) { - setContentTitle(recipient.toShortString()); - - if (recipient.getContactUri() != null) { - addPerson(recipient.getContactUri().toString()); - } - - ContactPhoto contactPhoto = recipient.getContactPhoto(context); - FallbackContactPhoto fallbackContactPhoto = recipient.getFallbackContactPhoto(); - - if (contactPhoto != null) { - try { - setLargeIcon(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()); - } catch (Exception e) { - Log.w(TAG, e); - setLargeIcon(fallbackContactPhoto.asDrawable(context, recipient.getFallbackAvatarColor(context))); - } - } else { - setLargeIcon(fallbackContactPhoto.asDrawable(context, recipient.getFallbackAvatarColor(context))); - } - - } else { - setContentTitle(context.getString(R.string.app_name)); - setLargeIcon(new GeneratedContactPhoto("Unknown").asDrawable(context, ThemeUtil.getDummyContactColor(context))); - } - } - - public void setMessageCount(int messageCount) { - setContentInfo(String.valueOf(messageCount)); - setNumber(messageCount); // this also sets badges on android8 and newer - } - - public void setPrimaryMessageBody(@NonNull Recipient chatRecipients, - @NonNull Recipient individualRecipient, - @NonNull CharSequence message, - @Nullable SlideDeck slideDeck) - { - SpannableStringBuilder stringBuilder = new SpannableStringBuilder(); - - if (privacy.isDisplayContact() && chatRecipients.isGroupRecipient()) { - stringBuilder.append(Util.getBoldedString(individualRecipient.toShortString() + ": ")); - } - - if (privacy.isDisplayMessage()) { - setContentText(stringBuilder.append(message)); - this.slideDeck = slideDeck; - } else { - setContentText(stringBuilder.append(context.getString(R.string.notify_new_message))); - } - } - - void addActions(@NonNull PendingIntent markReadIntent, - @NonNull PendingIntent inNotificationReplyIntent) - { - Action markAsReadAction = new Action(R.drawable.check, - context.getString(R.string.notify_mark_read), - markReadIntent); - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - Action replyAction = new Action.Builder(R.drawable.ic_reply_white_36dp, - context.getString(R.string.notify_reply_button), - inNotificationReplyIntent) - .addRemoteInput(new RemoteInput.Builder(MessageNotifierCompat.EXTRA_REMOTE_REPLY) - .setLabel(context.getString(R.string.notify_reply_button)).build()) - .build(); - addAction(replyAction); - } - - Action wearableReplyAction = new Action.Builder(R.drawable.ic_reply, - context.getString(R.string.notify_reply_button), - inNotificationReplyIntent) - .addRemoteInput(new RemoteInput.Builder(MessageNotifierCompat.EXTRA_REMOTE_REPLY) - .setLabel(context.getString(R.string.notify_reply_button)).build()) - .build(); - - addAction(markAsReadAction); - - extend(new NotificationCompat.WearableExtender().addAction(markAsReadAction) - .addAction(wearableReplyAction)); - } - - void addMessageBody(@NonNull Recipient chatRecipient, - @NonNull Recipient individualRecipient, - @Nullable CharSequence messageBody) - { - SpannableStringBuilder stringBuilder = new SpannableStringBuilder(); - - if (privacy.isDisplayContact() && chatRecipient.isGroupRecipient()) { - stringBuilder.append(Util.getBoldedString(individualRecipient.toShortString() + ": ")); - } - - if (privacy.isDisplayMessage()) { - messageBodies.addFirst(stringBuilder.append(messageBody == null ? "" : messageBody)); - } else { - messageBodies.addFirst(stringBuilder.append(context.getString(R.string.notify_new_message))); - } - } - - @Override - public Notification build() { - // the filtering whether or not to display messages and contacts is done in addMessageBody - // and setPrimaryMessageBody, no need to do it here again. - NotificationCompat.Style style; - if (Build.VERSION.SDK_INT < 23) { - style = new NotificationCompat.InboxStyle(); - for (CharSequence messageBody : messageBodies) { - ((NotificationCompat.InboxStyle) style).addLine(messageBody); - } - } else if (messageBodies.size() == 1 && hasBigPictureSlide(slideDeck)) { - style = new NotificationCompat.BigPictureStyle() - .bigPicture(getBigPicture(slideDeck)) - .setSummaryText(getBigText(messageBodies)); - } else { - style = new NotificationCompat.BigTextStyle().bigText(getBigText(messageBodies)); - } - - setStyle(style); - return super.build(); - } - - private void setLargeIcon(@Nullable Drawable drawable) { - if (drawable != null) { - int largeIconTargetSize = context.getResources().getDimensionPixelSize(R.dimen.contact_photo_target_size); - Bitmap recipientPhotoBitmap = BitmapUtil.createFromDrawable(drawable, largeIconTargetSize, largeIconTargetSize); - - if (recipientPhotoBitmap != null) { - setLargeIcon(recipientPhotoBitmap); - } - } - } - - private boolean hasBigPictureSlide(@Nullable SlideDeck slideDeck) { - if (slideDeck == null || Build.VERSION.SDK_INT < 16) { - return false; - } - - Slide thumbnailSlide = slideDeck.getThumbnailSlide(); - - return thumbnailSlide != null && - thumbnailSlide.hasImage() && - thumbnailSlide.getThumbnailUri() != null; - } - - private Bitmap getBigPicture(@NonNull SlideDeck slideDeck) - { - try { - @SuppressWarnings("ConstantConditions") - Uri uri = slideDeck.getThumbnailSlide().getThumbnailUri(); - - return GlideApp.with(context.getApplicationContext()) - .asBitmap() - .load(new DecryptableStreamUriLoader.DecryptableUri(uri)) - .diskCacheStrategy(DiskCacheStrategy.NONE) - .submit(500, 500) - .get(); - } catch (InterruptedException | ExecutionException e) { - Log.w(TAG, e); - return Bitmap.createBitmap(500, 500, Bitmap.Config.RGB_565); - } - } - - @Override - public NotificationCompat.Builder setContentTitle(CharSequence contentTitle) { - this.contentTitle = contentTitle; - return super.setContentTitle(contentTitle); - } - - public NotificationCompat.Builder setContentText(CharSequence contentText) { - this.contentText = contentText; - return super.setContentText(contentText); - } - - private CharSequence getBigText(List messageBodies) { - SpannableStringBuilder content = new SpannableStringBuilder(); - - for (CharSequence message : messageBodies) { - content.append(message); - content.append('\n'); - } - - return content; - } - - -}