NotificationService.java

   1package eu.siacs.conversations.services;
   2
   3import android.app.Notification;
   4import android.app.NotificationChannel;
   5import android.app.NotificationChannelGroup;
   6import android.app.NotificationManager;
   7import android.app.PendingIntent;
   8import android.content.Context;
   9import android.content.Intent;
  10import android.content.SharedPreferences;
  11import android.content.res.Resources;
  12import android.graphics.Bitmap;
  13import android.graphics.Typeface;
  14import android.media.AudioAttributes;
  15import android.media.RingtoneManager;
  16import android.net.Uri;
  17import android.os.Build;
  18import android.os.SystemClock;
  19import android.preference.PreferenceManager;
  20import android.support.annotation.RequiresApi;
  21import android.support.v4.app.NotificationCompat;
  22import android.support.v4.app.NotificationCompat.BigPictureStyle;
  23import android.support.v4.app.NotificationCompat.Builder;
  24import android.support.v4.app.NotificationManagerCompat;
  25import android.support.v4.app.Person;
  26import android.support.v4.app.RemoteInput;
  27import android.support.v4.content.ContextCompat;
  28import android.support.v4.graphics.drawable.IconCompat;
  29import android.text.SpannableString;
  30import android.text.style.StyleSpan;
  31import android.util.DisplayMetrics;
  32import android.util.Log;
  33
  34import java.io.File;
  35import java.io.IOException;
  36import java.util.ArrayList;
  37import java.util.Calendar;
  38import java.util.Collections;
  39import java.util.HashMap;
  40import java.util.Iterator;
  41import java.util.LinkedHashMap;
  42import java.util.List;
  43import java.util.Map;
  44import java.util.Set;
  45import java.util.concurrent.atomic.AtomicInteger;
  46import java.util.regex.Matcher;
  47import java.util.regex.Pattern;
  48
  49import eu.siacs.conversations.Config;
  50import eu.siacs.conversations.R;
  51import eu.siacs.conversations.entities.Account;
  52import eu.siacs.conversations.entities.Contact;
  53import eu.siacs.conversations.entities.Conversation;
  54import eu.siacs.conversations.entities.Conversational;
  55import eu.siacs.conversations.entities.Message;
  56import eu.siacs.conversations.persistance.FileBackend;
  57import eu.siacs.conversations.ui.ConversationsActivity;
  58import eu.siacs.conversations.ui.EditAccountActivity;
  59import eu.siacs.conversations.ui.RtpSessionActivity;
  60import eu.siacs.conversations.ui.TimePreference;
  61import eu.siacs.conversations.utils.AccountUtils;
  62import eu.siacs.conversations.utils.Compatibility;
  63import eu.siacs.conversations.utils.GeoHelper;
  64import eu.siacs.conversations.utils.UIHelper;
  65import eu.siacs.conversations.xmpp.XmppConnection;
  66import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
  67import eu.siacs.conversations.xmpp.jingle.Media;
  68
  69public class NotificationService {
  70
  71    public static final Object CATCHUP_LOCK = new Object();
  72
  73    private static final int LED_COLOR = 0xff00ff00;
  74
  75    private static final String CONVERSATIONS_GROUP = "eu.siacs.conversations";
  76    private static final int NOTIFICATION_ID_MULTIPLIER = 1024 * 1024;
  77    static final int FOREGROUND_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 4;
  78    private static final int NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 2;
  79    private static final int ERROR_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 6;
  80    private static final int INCOMING_CALL_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 8;
  81    public static final int ONGOING_CALL_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 10;
  82    private final XmppConnectionService mXmppConnectionService;
  83    private final LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<>();
  84    private final HashMap<Conversation, AtomicInteger> mBacklogMessageCounter = new HashMap<>();
  85    private Conversation mOpenConversation;
  86    private boolean mIsInForeground;
  87    private long mLastNotification;
  88
  89    NotificationService(final XmppConnectionService service) {
  90        this.mXmppConnectionService = service;
  91    }
  92
  93    private static boolean displaySnoozeAction(List<Message> messages) {
  94        int numberOfMessagesWithoutReply = 0;
  95        for (Message message : messages) {
  96            if (message.getStatus() == Message.STATUS_RECEIVED) {
  97                ++numberOfMessagesWithoutReply;
  98            } else {
  99                return false;
 100            }
 101        }
 102        return numberOfMessagesWithoutReply >= 3;
 103    }
 104
 105    public static Pattern generateNickHighlightPattern(final String nick) {
 106        return Pattern.compile("(?<=(^|\\s))" + Pattern.quote(nick) + "(?=\\s|$|\\p{Punct})");
 107    }
 108
 109    private static boolean isImageMessage(Message message) {
 110        return message.getType() != Message.TYPE_TEXT
 111                && message.getTransferable() == null
 112                && !message.isDeleted()
 113                && message.getEncryption() != Message.ENCRYPTION_PGP
 114                && message.getFileParams().height > 0;
 115    }
 116
 117    @RequiresApi(api = Build.VERSION_CODES.O)
 118    void initializeChannels() {
 119        final Context c = mXmppConnectionService;
 120        final NotificationManager notificationManager = c.getSystemService(NotificationManager.class);
 121        if (notificationManager == null) {
 122            return;
 123        }
 124
 125        notificationManager.deleteNotificationChannel("export");
 126
 127        notificationManager.createNotificationChannelGroup(new NotificationChannelGroup("status", c.getString(R.string.notification_group_status_information)));
 128        notificationManager.createNotificationChannelGroup(new NotificationChannelGroup("chats", c.getString(R.string.notification_group_messages)));
 129        notificationManager.createNotificationChannelGroup(new NotificationChannelGroup("calls", c.getString(R.string.notification_group_calls)));
 130        final NotificationChannel foregroundServiceChannel = new NotificationChannel("foreground",
 131                c.getString(R.string.foreground_service_channel_name),
 132                NotificationManager.IMPORTANCE_MIN);
 133        foregroundServiceChannel.setDescription(c.getString(R.string.foreground_service_channel_description));
 134        foregroundServiceChannel.setShowBadge(false);
 135        foregroundServiceChannel.setGroup("status");
 136        notificationManager.createNotificationChannel(foregroundServiceChannel);
 137        final NotificationChannel errorChannel = new NotificationChannel("error",
 138                c.getString(R.string.error_channel_name),
 139                NotificationManager.IMPORTANCE_LOW);
 140        errorChannel.setDescription(c.getString(R.string.error_channel_description));
 141        errorChannel.setShowBadge(false);
 142        errorChannel.setGroup("status");
 143        notificationManager.createNotificationChannel(errorChannel);
 144
 145        final NotificationChannel videoCompressionChannel = new NotificationChannel("compression",
 146                c.getString(R.string.video_compression_channel_name),
 147                NotificationManager.IMPORTANCE_LOW);
 148        videoCompressionChannel.setShowBadge(false);
 149        videoCompressionChannel.setGroup("status");
 150        notificationManager.createNotificationChannel(videoCompressionChannel);
 151
 152        final NotificationChannel exportChannel = new NotificationChannel("backup",
 153                c.getString(R.string.backup_channel_name),
 154                NotificationManager.IMPORTANCE_LOW);
 155        exportChannel.setShowBadge(false);
 156        exportChannel.setGroup("status");
 157        notificationManager.createNotificationChannel(exportChannel);
 158
 159        final NotificationChannel incomingCallsChannel = new NotificationChannel("incoming_calls",
 160                c.getString(R.string.incoming_calls_channel_name),
 161                NotificationManager.IMPORTANCE_HIGH);
 162        incomingCallsChannel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE), new AudioAttributes.Builder()
 163                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
 164                .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
 165                .build());
 166        incomingCallsChannel.setShowBadge(false);
 167        incomingCallsChannel.setLightColor(LED_COLOR);
 168        incomingCallsChannel.enableLights(true);
 169        incomingCallsChannel.setGroup("calls");
 170        notificationManager.createNotificationChannel(incomingCallsChannel);
 171
 172        final NotificationChannel ongoingCallsChannel = new NotificationChannel("ongoing_calls",
 173                c.getString(R.string.ongoing_calls_channel_name),
 174                NotificationManager.IMPORTANCE_LOW);
 175        ongoingCallsChannel.setShowBadge(false);
 176        ongoingCallsChannel.setGroup("calls");
 177        notificationManager.createNotificationChannel(ongoingCallsChannel);
 178
 179
 180        final NotificationChannel messagesChannel = new NotificationChannel("messages",
 181                c.getString(R.string.messages_channel_name),
 182                NotificationManager.IMPORTANCE_HIGH);
 183        messagesChannel.setShowBadge(true);
 184        messagesChannel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), new AudioAttributes.Builder()
 185                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
 186                .setUsage(AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT)
 187                .build());
 188        messagesChannel.setLightColor(LED_COLOR);
 189        final int dat = 70;
 190        final long[] pattern = {0, 3 * dat, dat, dat};
 191        messagesChannel.setVibrationPattern(pattern);
 192        messagesChannel.enableVibration(true);
 193        messagesChannel.enableLights(true);
 194        messagesChannel.setGroup("chats");
 195        notificationManager.createNotificationChannel(messagesChannel);
 196        final NotificationChannel silentMessagesChannel = new NotificationChannel("silent_messages",
 197                c.getString(R.string.silent_messages_channel_name),
 198                NotificationManager.IMPORTANCE_LOW);
 199        silentMessagesChannel.setDescription(c.getString(R.string.silent_messages_channel_description));
 200        silentMessagesChannel.setShowBadge(true);
 201        silentMessagesChannel.setLightColor(LED_COLOR);
 202        silentMessagesChannel.enableLights(true);
 203        silentMessagesChannel.setGroup("chats");
 204        notificationManager.createNotificationChannel(silentMessagesChannel);
 205
 206        final NotificationChannel quietHoursChannel = new NotificationChannel("quiet_hours",
 207                c.getString(R.string.title_pref_quiet_hours),
 208                NotificationManager.IMPORTANCE_LOW);
 209        quietHoursChannel.setShowBadge(true);
 210        quietHoursChannel.setLightColor(LED_COLOR);
 211        quietHoursChannel.enableLights(true);
 212        quietHoursChannel.setGroup("chats");
 213        quietHoursChannel.enableVibration(false);
 214        quietHoursChannel.setSound(null, null);
 215
 216        notificationManager.createNotificationChannel(quietHoursChannel);
 217    }
 218
 219    public boolean notify(final Message message) {
 220        final Conversation conversation = (Conversation) message.getConversation();
 221        return message.getStatus() == Message.STATUS_RECEIVED
 222                && !conversation.isMuted()
 223                && (conversation.alwaysNotify() || wasHighlightedOrPrivate(message))
 224                && (!conversation.isWithStranger() || notificationsFromStrangers());
 225    }
 226
 227    private boolean notificationsFromStrangers() {
 228        return mXmppConnectionService.getBooleanPreference("notifications_from_strangers", R.bool.notifications_from_strangers);
 229    }
 230
 231    private boolean isQuietHours() {
 232        if (!mXmppConnectionService.getBooleanPreference("enable_quiet_hours", R.bool.enable_quiet_hours)) {
 233            return false;
 234        }
 235        final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
 236        final long startTime = TimePreference.minutesToTimestamp(preferences.getLong("quiet_hours_start", TimePreference.DEFAULT_VALUE));
 237        final long endTime = TimePreference.minutesToTimestamp(preferences.getLong("quiet_hours_end", TimePreference.DEFAULT_VALUE));
 238        final long nowTime = Calendar.getInstance().getTimeInMillis();
 239
 240        if (endTime < startTime) {
 241            return nowTime > startTime || nowTime < endTime;
 242        } else {
 243            return nowTime > startTime && nowTime < endTime;
 244        }
 245    }
 246
 247    public void pushFromBacklog(final Message message) {
 248        if (notify(message)) {
 249            synchronized (notifications) {
 250                getBacklogMessageCounter((Conversation) message.getConversation()).incrementAndGet();
 251                pushToStack(message);
 252            }
 253        }
 254    }
 255
 256    private AtomicInteger getBacklogMessageCounter(Conversation conversation) {
 257        synchronized (mBacklogMessageCounter) {
 258            if (!mBacklogMessageCounter.containsKey(conversation)) {
 259                mBacklogMessageCounter.put(conversation, new AtomicInteger(0));
 260            }
 261            return mBacklogMessageCounter.get(conversation);
 262        }
 263    }
 264
 265    void pushFromDirectReply(final Message message) {
 266        synchronized (notifications) {
 267            pushToStack(message);
 268            updateNotification(false);
 269        }
 270    }
 271
 272    public void finishBacklog(boolean notify, Account account) {
 273        synchronized (notifications) {
 274            mXmppConnectionService.updateUnreadCountBadge();
 275            if (account == null || !notify) {
 276                updateNotification(notify);
 277            } else {
 278                final int count;
 279                final List<String> conversations;
 280                synchronized (this.mBacklogMessageCounter) {
 281                    conversations = getBacklogConversations(account);
 282                    count = getBacklogMessageCount(account);
 283                }
 284                updateNotification(count > 0, conversations);
 285            }
 286        }
 287    }
 288
 289    private List<String> getBacklogConversations(Account account) {
 290        final List<String> conversations = new ArrayList<>();
 291        for (Map.Entry<Conversation, AtomicInteger> entry : mBacklogMessageCounter.entrySet()) {
 292            if (entry.getKey().getAccount() == account) {
 293                conversations.add(entry.getKey().getUuid());
 294            }
 295        }
 296        return conversations;
 297    }
 298
 299    private int getBacklogMessageCount(Account account) {
 300        int count = 0;
 301        for (Iterator<Map.Entry<Conversation, AtomicInteger>> it = mBacklogMessageCounter.entrySet().iterator(); it.hasNext(); ) {
 302            Map.Entry<Conversation, AtomicInteger> entry = it.next();
 303            if (entry.getKey().getAccount() == account) {
 304                count += entry.getValue().get();
 305                it.remove();
 306            }
 307        }
 308        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": backlog message count=" + count);
 309        return count;
 310    }
 311
 312    void finishBacklog(boolean notify) {
 313        finishBacklog(notify, null);
 314    }
 315
 316    private void pushToStack(final Message message) {
 317        final String conversationUuid = message.getConversationUuid();
 318        if (notifications.containsKey(conversationUuid)) {
 319            notifications.get(conversationUuid).add(message);
 320        } else {
 321            final ArrayList<Message> mList = new ArrayList<>();
 322            mList.add(message);
 323            notifications.put(conversationUuid, mList);
 324        }
 325    }
 326
 327    public void push(final Message message) {
 328        synchronized (CATCHUP_LOCK) {
 329            final XmppConnection connection = message.getConversation().getAccount().getXmppConnection();
 330            if (connection != null && connection.isWaitingForSmCatchup()) {
 331                connection.incrementSmCatchupMessageCounter();
 332                pushFromBacklog(message);
 333            } else {
 334                pushNow(message);
 335            }
 336        }
 337    }
 338
 339    public void showIncomingCallNotification(final AbstractJingleConnection.Id id, final Set<Media> media) {
 340        final Intent fullScreenIntent = new Intent(mXmppConnectionService, RtpSessionActivity.class);
 341        fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, id.account.getJid().asBareJid().toEscapedString());
 342        fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_WITH, id.with.toEscapedString());
 343        fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.sessionId);
 344        fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 345        fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 346        final NotificationCompat.Builder builder = new NotificationCompat.Builder(mXmppConnectionService, "incoming_calls");
 347        if (media.contains(Media.VIDEO)) {
 348            builder.setSmallIcon(R.drawable.ic_videocam_white_24dp);
 349            builder.setContentTitle(mXmppConnectionService.getString(R.string.rtp_state_incoming_video_call));
 350        } else {
 351            builder.setSmallIcon(R.drawable.ic_call_white_24dp);
 352            builder.setContentTitle(mXmppConnectionService.getString(R.string.rtp_state_incoming_call));
 353        }
 354        builder.setContentText(id.account.getRoster().getContact(id.with).getDisplayName());
 355        builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
 356        builder.setPriority(NotificationCompat.PRIORITY_HIGH);
 357        builder.setCategory(NotificationCompat.CATEGORY_CALL);
 358        PendingIntent pendingIntent = createPendingRtpSession(id, Intent.ACTION_VIEW, 101);
 359        builder.setFullScreenIntent(pendingIntent, true);
 360        builder.setContentIntent(pendingIntent); //old androids need this?
 361        builder.setOngoing(true);
 362        builder.addAction(new NotificationCompat.Action.Builder(
 363                R.drawable.ic_call_end_white_48dp,
 364                mXmppConnectionService.getString(R.string.dismiss_call),
 365                createCallAction(id.sessionId, XmppConnectionService.ACTION_DISMISS_CALL, 102))
 366                .build());
 367        builder.addAction(new NotificationCompat.Action.Builder(
 368                R.drawable.ic_call_white_24dp,
 369                mXmppConnectionService.getString(R.string.answer_call),
 370                createPendingRtpSession(id, RtpSessionActivity.ACTION_ACCEPT_CALL, 103))
 371                .build());
 372        modifyIncomingCall(builder);
 373        final Notification notification = builder.build();
 374        notification.flags = notification.flags | Notification.FLAG_INSISTENT;
 375        notify(INCOMING_CALL_NOTIFICATION_ID, notification);
 376    }
 377
 378    public Notification getOngoingCallNotification(final AbstractJingleConnection.Id id, final Set<Media> media) {
 379        final NotificationCompat.Builder builder = new NotificationCompat.Builder(mXmppConnectionService, "ongoing_calls");
 380        if (media.contains(Media.VIDEO)) {
 381            builder.setSmallIcon(R.drawable.ic_videocam_white_24dp);
 382            builder.setContentTitle(mXmppConnectionService.getString(R.string.ongoing_video_call));
 383        } else {
 384            builder.setSmallIcon(R.drawable.ic_call_white_24dp);
 385            builder.setContentTitle(mXmppConnectionService.getString(R.string.ongoing_call));
 386        }
 387        builder.setContentText(id.account.getRoster().getContact(id.with).getDisplayName());
 388        builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
 389        builder.setPriority(NotificationCompat.PRIORITY_HIGH);
 390        builder.setCategory(NotificationCompat.CATEGORY_CALL);
 391        builder.setContentIntent(createPendingRtpSession(id, Intent.ACTION_VIEW, 101));
 392        builder.setOngoing(true);
 393        builder.addAction(new NotificationCompat.Action.Builder(
 394                R.drawable.ic_call_end_white_48dp,
 395                mXmppConnectionService.getString(R.string.hang_up),
 396                createCallAction(id.sessionId, XmppConnectionService.ACTION_END_CALL, 104))
 397                .build());
 398        return builder.build();
 399    }
 400
 401    private PendingIntent createPendingRtpSession(final AbstractJingleConnection.Id id, final String action, final int requestCode) {
 402        final Intent fullScreenIntent = new Intent(mXmppConnectionService, RtpSessionActivity.class);
 403        fullScreenIntent.setAction(action);
 404        fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, id.account.getJid().asBareJid().toEscapedString());
 405        fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_WITH, id.with.toEscapedString());
 406        fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.sessionId);
 407        return PendingIntent.getActivity(mXmppConnectionService, requestCode, fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);
 408    }
 409
 410    public void cancelIncomingCallNotification() {
 411        cancel(INCOMING_CALL_NOTIFICATION_ID);
 412    }
 413
 414    public void cancelOngoingCallNotification() {
 415        cancel(ONGOING_CALL_NOTIFICATION_ID);
 416    }
 417
 418    private void pushNow(final Message message) {
 419        mXmppConnectionService.updateUnreadCountBadge();
 420        if (!notify(message)) {
 421            Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because turned off");
 422            return;
 423        }
 424        final boolean isScreenOn = mXmppConnectionService.isInteractive();
 425        if (this.mIsInForeground && isScreenOn && this.mOpenConversation == message.getConversation()) {
 426            Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because conversation is open");
 427            return;
 428        }
 429        synchronized (notifications) {
 430            pushToStack(message);
 431            final Conversational conversation = message.getConversation();
 432            final Account account = conversation.getAccount();
 433            final boolean doNotify = (!(this.mIsInForeground && this.mOpenConversation == null) || !isScreenOn)
 434                    && !account.inGracePeriod()
 435                    && !this.inMiniGracePeriod(account);
 436            updateNotification(doNotify, Collections.singletonList(conversation.getUuid()));
 437        }
 438    }
 439
 440    public void clear() {
 441        synchronized (notifications) {
 442            for (ArrayList<Message> messages : notifications.values()) {
 443                markAsReadIfHasDirectReply(messages);
 444            }
 445            notifications.clear();
 446            updateNotification(false);
 447        }
 448    }
 449
 450    public void clear(final Conversation conversation) {
 451        synchronized (this.mBacklogMessageCounter) {
 452            this.mBacklogMessageCounter.remove(conversation);
 453        }
 454        synchronized (notifications) {
 455            markAsReadIfHasDirectReply(conversation);
 456            if (notifications.remove(conversation.getUuid()) != null) {
 457                cancel(conversation.getUuid(), NOTIFICATION_ID);
 458                updateNotification(false, null, true);
 459            }
 460        }
 461    }
 462
 463    private void markAsReadIfHasDirectReply(final Conversation conversation) {
 464        markAsReadIfHasDirectReply(notifications.get(conversation.getUuid()));
 465    }
 466
 467    private void markAsReadIfHasDirectReply(final ArrayList<Message> messages) {
 468        if (messages != null && messages.size() > 0) {
 469            Message last = messages.get(messages.size() - 1);
 470            if (last.getStatus() != Message.STATUS_RECEIVED) {
 471                if (mXmppConnectionService.markRead((Conversation) last.getConversation(), false)) {
 472                    mXmppConnectionService.updateConversationUi();
 473                }
 474            }
 475        }
 476    }
 477
 478    private void setNotificationColor(final Builder mBuilder) {
 479        mBuilder.setColor(ContextCompat.getColor(mXmppConnectionService, R.color.green600));
 480    }
 481
 482    public void updateNotification() {
 483        synchronized (notifications) {
 484            updateNotification(false);
 485        }
 486    }
 487
 488    private void updateNotification(final boolean notify) {
 489        updateNotification(notify, null, false);
 490    }
 491
 492    private void updateNotification(final boolean notify, final List<String> conversations) {
 493        updateNotification(notify, conversations, false);
 494    }
 495
 496    private void updateNotification(final boolean notify, final List<String> conversations, final boolean summaryOnly) {
 497        final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
 498
 499        final boolean quiteHours = isQuietHours();
 500
 501        final boolean notifyOnlyOneChild = notify && conversations != null && conversations.size() == 1; //if this check is changed to > 0 catchup messages will create one notification per conversation
 502
 503
 504        if (notifications.size() == 0) {
 505            cancel(NOTIFICATION_ID);
 506        } else {
 507            if (notify) {
 508                this.markLastNotification();
 509            }
 510            final Builder mBuilder;
 511            if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
 512                mBuilder = buildSingleConversations(notifications.values().iterator().next(), notify, quiteHours);
 513                modifyForSoundVibrationAndLight(mBuilder, notify, quiteHours, preferences);
 514                notify(NOTIFICATION_ID, mBuilder.build());
 515            } else {
 516                mBuilder = buildMultipleConversation(notify, quiteHours);
 517                if (notifyOnlyOneChild) {
 518                    mBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
 519                }
 520                modifyForSoundVibrationAndLight(mBuilder, notify, quiteHours, preferences);
 521                if (!summaryOnly) {
 522                    for (Map.Entry<String, ArrayList<Message>> entry : notifications.entrySet()) {
 523                        String uuid = entry.getKey();
 524                        final boolean notifyThis = notifyOnlyOneChild ? conversations.contains(uuid) : notify;
 525                        Builder singleBuilder = buildSingleConversations(entry.getValue(), notifyThis, quiteHours);
 526                        if (!notifyOnlyOneChild) {
 527                            singleBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY);
 528                        }
 529                        modifyForSoundVibrationAndLight(singleBuilder, notifyThis, quiteHours, preferences);
 530                        singleBuilder.setGroup(CONVERSATIONS_GROUP);
 531                        setNotificationColor(singleBuilder);
 532                        notify(entry.getKey(), NOTIFICATION_ID, singleBuilder.build());
 533                    }
 534                }
 535                notify(NOTIFICATION_ID, mBuilder.build());
 536            }
 537        }
 538    }
 539
 540    private void modifyForSoundVibrationAndLight(Builder mBuilder, boolean notify, boolean quietHours, SharedPreferences preferences) {
 541        final Resources resources = mXmppConnectionService.getResources();
 542        final String ringtone = preferences.getString("notification_ringtone", resources.getString(R.string.notification_ringtone));
 543        final boolean vibrate = preferences.getBoolean("vibrate_on_notification", resources.getBoolean(R.bool.vibrate_on_notification));
 544        final boolean led = preferences.getBoolean("led", resources.getBoolean(R.bool.led));
 545        final boolean headsup = preferences.getBoolean("notification_headsup", resources.getBoolean(R.bool.headsup_notifications));
 546        if (notify && !quietHours) {
 547            if (vibrate) {
 548                final int dat = 70;
 549                final long[] pattern = {0, 3 * dat, dat, dat};
 550                mBuilder.setVibrate(pattern);
 551            } else {
 552                mBuilder.setVibrate(new long[]{0});
 553            }
 554            Uri uri = Uri.parse(ringtone);
 555            try {
 556                mBuilder.setSound(fixRingtoneUri(uri));
 557            } catch (SecurityException e) {
 558                Log.d(Config.LOGTAG, "unable to use custom notification sound " + uri.toString());
 559            }
 560        } else {
 561            mBuilder.setLocalOnly(true);
 562        }
 563        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 564            mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
 565        }
 566        mBuilder.setPriority(notify ? (headsup ? NotificationCompat.PRIORITY_HIGH : NotificationCompat.PRIORITY_DEFAULT) : NotificationCompat.PRIORITY_LOW);
 567        setNotificationColor(mBuilder);
 568        mBuilder.setDefaults(0);
 569        if (led) {
 570            mBuilder.setLights(LED_COLOR, 2000, 3000);
 571        }
 572    }
 573
 574    private void modifyIncomingCall(Builder mBuilder) {
 575        final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
 576        final Resources resources = mXmppConnectionService.getResources();
 577        final String ringtone = preferences.getString("call_ringtone", resources.getString(R.string.incoming_call_ringtone));
 578        final int dat = 70;
 579        final long[] pattern = {0, 3 * dat, dat, dat, 3 * dat, dat, dat};
 580        mBuilder.setVibrate(pattern);
 581        Uri uri = Uri.parse(ringtone);
 582        try {
 583            mBuilder.setSound(fixRingtoneUri(uri));
 584        } catch (SecurityException e) {
 585            Log.d(Config.LOGTAG, "unable to use custom notification sound " + uri.toString());
 586        }
 587        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 588            mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
 589        }
 590        mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
 591        setNotificationColor(mBuilder);
 592        mBuilder.setLights(LED_COLOR, 2000, 3000);
 593    }
 594
 595    private Uri fixRingtoneUri(Uri uri) {
 596        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && "file".equals(uri.getScheme())) {
 597            return FileBackend.getUriForFile(mXmppConnectionService, new File(uri.getPath()));
 598        } else {
 599            return uri;
 600        }
 601    }
 602
 603    private Builder buildMultipleConversation(final boolean notify, final boolean quietHours) {
 604        final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService, quietHours ? "quiet_hours" : (notify ? "messages" : "silent_messages"));
 605        final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
 606        style.setBigContentTitle(mXmppConnectionService.getString(R.string.x_unread_conversations, notifications.size()));
 607        final StringBuilder names = new StringBuilder();
 608        Conversation conversation = null;
 609        for (final ArrayList<Message> messages : notifications.values()) {
 610            if (messages.size() > 0) {
 611                conversation = (Conversation) messages.get(0).getConversation();
 612                final String name = conversation.getName().toString();
 613                SpannableString styledString;
 614                if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
 615                    int count = messages.size();
 616                    styledString = new SpannableString(name + ": " + mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
 617                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
 618                    style.addLine(styledString);
 619                } else {
 620                    styledString = new SpannableString(name + ": " + UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
 621                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
 622                    style.addLine(styledString);
 623                }
 624                names.append(name);
 625                names.append(", ");
 626            }
 627        }
 628        if (names.length() >= 2) {
 629            names.delete(names.length() - 2, names.length());
 630        }
 631        mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.x_unread_conversations, notifications.size()));
 632        mBuilder.setTicker(mXmppConnectionService.getString(R.string.x_unread_conversations, notifications.size()));
 633        mBuilder.setContentText(names.toString());
 634        mBuilder.setStyle(style);
 635        if (conversation != null) {
 636            mBuilder.setContentIntent(createContentIntent(conversation));
 637        }
 638        mBuilder.setGroupSummary(true);
 639        mBuilder.setGroup(CONVERSATIONS_GROUP);
 640        mBuilder.setDeleteIntent(createDeleteIntent(null));
 641        mBuilder.setSmallIcon(R.drawable.ic_notification);
 642        return mBuilder;
 643    }
 644
 645    private Builder buildSingleConversations(final ArrayList<Message> messages, final boolean notify, final boolean quietHours) {
 646        final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService, quietHours ? "quiet_hours" : (notify ? "messages" : "silent_messages"));
 647        if (messages.size() >= 1) {
 648            final Conversation conversation = (Conversation) messages.get(0).getConversation();
 649            mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
 650                    .get(conversation, AvatarService.getSystemUiAvatarSize(mXmppConnectionService)));
 651            mBuilder.setContentTitle(conversation.getName());
 652            if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
 653                int count = messages.size();
 654                mBuilder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
 655            } else {
 656                Message message;
 657                //TODO starting with Android 9 we might want to put images in MessageStyle
 658                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P && (message = getImage(messages)) != null) {
 659                    modifyForImage(mBuilder, message, messages);
 660                } else {
 661                    modifyForTextOnly(mBuilder, messages);
 662                }
 663                RemoteInput remoteInput = new RemoteInput.Builder("text_reply").setLabel(UIHelper.getMessageHint(mXmppConnectionService, conversation)).build();
 664                PendingIntent markAsReadPendingIntent = createReadPendingIntent(conversation);
 665                NotificationCompat.Action markReadAction = new NotificationCompat.Action.Builder(
 666                        R.drawable.ic_drafts_white_24dp,
 667                        mXmppConnectionService.getString(R.string.mark_as_read),
 668                        markAsReadPendingIntent)
 669                        .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ)
 670                        .setShowsUserInterface(false)
 671                        .build();
 672                String replyLabel = mXmppConnectionService.getString(R.string.reply);
 673                NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
 674                        R.drawable.ic_send_text_offline,
 675                        replyLabel,
 676                        createReplyIntent(conversation, false))
 677                        .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY)
 678                        .setShowsUserInterface(false)
 679                        .addRemoteInput(remoteInput).build();
 680                NotificationCompat.Action wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_wear_reply,
 681                        replyLabel,
 682                        createReplyIntent(conversation, true)).addRemoteInput(remoteInput).build();
 683                mBuilder.extend(new NotificationCompat.WearableExtender().addAction(wearReplyAction));
 684                int addedActionsCount = 1;
 685                mBuilder.addAction(markReadAction);
 686                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 687                    mBuilder.addAction(replyAction);
 688                    ++addedActionsCount;
 689                }
 690
 691                if (displaySnoozeAction(messages)) {
 692                    String label = mXmppConnectionService.getString(R.string.snooze);
 693                    PendingIntent pendingSnoozeIntent = createSnoozeIntent(conversation);
 694                    NotificationCompat.Action snoozeAction = new NotificationCompat.Action.Builder(
 695                            R.drawable.ic_notifications_paused_white_24dp,
 696                            label,
 697                            pendingSnoozeIntent).build();
 698                    mBuilder.addAction(snoozeAction);
 699                    ++addedActionsCount;
 700                }
 701                if (addedActionsCount < 3) {
 702                    final Message firstLocationMessage = getFirstLocationMessage(messages);
 703                    if (firstLocationMessage != null) {
 704                        final PendingIntent pendingShowLocationIntent = createShowLocationIntent(firstLocationMessage);
 705                        if (pendingShowLocationIntent != null) {
 706                            final String label = mXmppConnectionService.getResources().getString(R.string.show_location);
 707                            NotificationCompat.Action locationAction = new NotificationCompat.Action.Builder(
 708                                    R.drawable.ic_room_white_24dp,
 709                                    label,
 710                                    pendingShowLocationIntent).build();
 711                            mBuilder.addAction(locationAction);
 712                            ++addedActionsCount;
 713                        }
 714                    }
 715                }
 716                if (addedActionsCount < 3) {
 717                    Message firstDownloadableMessage = getFirstDownloadableMessage(messages);
 718                    if (firstDownloadableMessage != null) {
 719                        String label = mXmppConnectionService.getResources().getString(R.string.download_x_file, UIHelper.getFileDescriptionString(mXmppConnectionService, firstDownloadableMessage));
 720                        PendingIntent pendingDownloadIntent = createDownloadIntent(firstDownloadableMessage);
 721                        NotificationCompat.Action downloadAction = new NotificationCompat.Action.Builder(
 722                                R.drawable.ic_file_download_white_24dp,
 723                                label,
 724                                pendingDownloadIntent).build();
 725                        mBuilder.addAction(downloadAction);
 726                        ++addedActionsCount;
 727                    }
 728                }
 729            }
 730            if (conversation.getMode() == Conversation.MODE_SINGLE) {
 731                Contact contact = conversation.getContact();
 732                Uri systemAccount = contact.getSystemAccount();
 733                if (systemAccount != null) {
 734                    mBuilder.addPerson(systemAccount.toString());
 735                }
 736            }
 737            mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
 738            mBuilder.setSmallIcon(R.drawable.ic_notification);
 739            mBuilder.setDeleteIntent(createDeleteIntent(conversation));
 740            mBuilder.setContentIntent(createContentIntent(conversation));
 741        }
 742        return mBuilder;
 743    }
 744
 745    private void modifyForImage(final Builder builder, final Message message, final ArrayList<Message> messages) {
 746        try {
 747            final Bitmap bitmap = mXmppConnectionService.getFileBackend().getThumbnail(message, getPixel(288), false);
 748            final ArrayList<Message> tmp = new ArrayList<>();
 749            for (final Message msg : messages) {
 750                if (msg.getType() == Message.TYPE_TEXT
 751                        && msg.getTransferable() == null) {
 752                    tmp.add(msg);
 753                }
 754            }
 755            final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
 756            bigPictureStyle.bigPicture(bitmap);
 757            if (tmp.size() > 0) {
 758                CharSequence text = getMergedBodies(tmp);
 759                bigPictureStyle.setSummaryText(text);
 760                builder.setContentText(text);
 761                builder.setTicker(text);
 762            } else {
 763                final String description = UIHelper.getFileDescriptionString(mXmppConnectionService, message);
 764                builder.setContentText(description);
 765                builder.setTicker(description);
 766            }
 767            builder.setStyle(bigPictureStyle);
 768        } catch (final IOException e) {
 769            modifyForTextOnly(builder, messages);
 770        }
 771    }
 772
 773    private Person getPerson(Message message) {
 774        final Contact contact = message.getContact();
 775        final Person.Builder builder = new Person.Builder();
 776        if (contact != null) {
 777            builder.setName(contact.getDisplayName());
 778            final Uri uri = contact.getSystemAccount();
 779            if (uri != null) {
 780                builder.setUri(uri.toString());
 781            }
 782        } else {
 783            builder.setName(UIHelper.getMessageDisplayName(message));
 784        }
 785        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
 786            builder.setIcon(IconCompat.createWithBitmap(mXmppConnectionService.getAvatarService().get(message, AvatarService.getSystemUiAvatarSize(mXmppConnectionService), false)));
 787        }
 788        return builder.build();
 789    }
 790
 791    private void modifyForTextOnly(final Builder builder, final ArrayList<Message> messages) {
 792        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 793            final Conversation conversation = (Conversation) messages.get(0).getConversation();
 794            final Person.Builder meBuilder = new Person.Builder().setName(mXmppConnectionService.getString(R.string.me));
 795            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
 796                meBuilder.setIcon(IconCompat.createWithBitmap(mXmppConnectionService.getAvatarService().get(conversation.getAccount(), AvatarService.getSystemUiAvatarSize(mXmppConnectionService))));
 797            }
 798            final Person me = meBuilder.build();
 799            NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(me);
 800            final boolean multiple = conversation.getMode() == Conversation.MODE_MULTI;
 801            if (multiple) {
 802                messagingStyle.setConversationTitle(conversation.getName());
 803            }
 804            for (Message message : messages) {
 805                final Person sender = message.getStatus() == Message.STATUS_RECEIVED ? getPerson(message) : null;
 806                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && isImageMessage(message)) {
 807                    final Uri dataUri = FileBackend.getMediaUri(mXmppConnectionService, mXmppConnectionService.getFileBackend().getFile(message));
 808                    NotificationCompat.MessagingStyle.Message imageMessage = new NotificationCompat.MessagingStyle.Message(UIHelper.getMessagePreview(mXmppConnectionService, message).first, message.getTimeSent(), sender);
 809                    if (dataUri != null) {
 810                        imageMessage.setData(message.getMimeType(), dataUri);
 811                    }
 812                    messagingStyle.addMessage(imageMessage);
 813                } else {
 814                    messagingStyle.addMessage(UIHelper.getMessagePreview(mXmppConnectionService, message).first, message.getTimeSent(), sender);
 815                }
 816            }
 817            messagingStyle.setGroupConversation(multiple);
 818            builder.setStyle(messagingStyle);
 819        } else {
 820            if (messages.get(0).getConversation().getMode() == Conversation.MODE_SINGLE) {
 821                builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
 822                final CharSequence preview = UIHelper.getMessagePreview(mXmppConnectionService, messages.get(messages.size() - 1)).first;
 823                builder.setContentText(preview);
 824                builder.setTicker(preview);
 825                builder.setNumber(messages.size());
 826            } else {
 827                final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
 828                SpannableString styledString;
 829                for (Message message : messages) {
 830                    final String name = UIHelper.getMessageDisplayName(message);
 831                    styledString = new SpannableString(name + ": " + message.getBody());
 832                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
 833                    style.addLine(styledString);
 834                }
 835                builder.setStyle(style);
 836                int count = messages.size();
 837                if (count == 1) {
 838                    final String name = UIHelper.getMessageDisplayName(messages.get(0));
 839                    styledString = new SpannableString(name + ": " + messages.get(0).getBody());
 840                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
 841                    builder.setContentText(styledString);
 842                    builder.setTicker(styledString);
 843                } else {
 844                    final String text = mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count);
 845                    builder.setContentText(text);
 846                    builder.setTicker(text);
 847                }
 848            }
 849        }
 850    }
 851
 852    private Message getImage(final Iterable<Message> messages) {
 853        Message image = null;
 854        for (final Message message : messages) {
 855            if (message.getStatus() != Message.STATUS_RECEIVED) {
 856                return null;
 857            }
 858            if (isImageMessage(message)) {
 859                image = message;
 860            }
 861        }
 862        return image;
 863    }
 864
 865    private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
 866        for (final Message message : messages) {
 867            if (message.getTransferable() != null || (message.getType() == Message.TYPE_TEXT && message.treatAsDownloadable())) {
 868                return message;
 869            }
 870        }
 871        return null;
 872    }
 873
 874    private Message getFirstLocationMessage(final Iterable<Message> messages) {
 875        for (final Message message : messages) {
 876            if (message.isGeoUri()) {
 877                return message;
 878            }
 879        }
 880        return null;
 881    }
 882
 883    private CharSequence getMergedBodies(final ArrayList<Message> messages) {
 884        final StringBuilder text = new StringBuilder();
 885        for (Message message : messages) {
 886            if (text.length() != 0) {
 887                text.append("\n");
 888            }
 889            text.append(UIHelper.getMessagePreview(mXmppConnectionService, message).first);
 890        }
 891        return text.toString();
 892    }
 893
 894    private PendingIntent createShowLocationIntent(final Message message) {
 895        Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(mXmppConnectionService, message);
 896        for (Intent intent : intents) {
 897            if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
 898                return PendingIntent.getActivity(mXmppConnectionService, generateRequestCode(message.getConversation(), 18), intent, PendingIntent.FLAG_UPDATE_CURRENT);
 899            }
 900        }
 901        return null;
 902    }
 903
 904    private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
 905        final Intent viewConversationIntent = new Intent(mXmppConnectionService, ConversationsActivity.class);
 906        viewConversationIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
 907        viewConversationIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversationUuid);
 908        if (downloadMessageUuid != null) {
 909            viewConversationIntent.putExtra(ConversationsActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
 910            return PendingIntent.getActivity(mXmppConnectionService,
 911                    generateRequestCode(conversationUuid, 8),
 912                    viewConversationIntent,
 913                    PendingIntent.FLAG_UPDATE_CURRENT);
 914        } else {
 915            return PendingIntent.getActivity(mXmppConnectionService,
 916                    generateRequestCode(conversationUuid, 10),
 917                    viewConversationIntent,
 918                    PendingIntent.FLAG_UPDATE_CURRENT);
 919        }
 920    }
 921
 922    private int generateRequestCode(String uuid, int actionId) {
 923        return (actionId * NOTIFICATION_ID_MULTIPLIER) + (uuid.hashCode() % NOTIFICATION_ID_MULTIPLIER);
 924    }
 925
 926    private int generateRequestCode(Conversational conversation, int actionId) {
 927        return generateRequestCode(conversation.getUuid(), actionId);
 928    }
 929
 930    private PendingIntent createDownloadIntent(final Message message) {
 931        return createContentIntent(message.getConversationUuid(), message.getUuid());
 932    }
 933
 934    private PendingIntent createContentIntent(final Conversational conversation) {
 935        return createContentIntent(conversation.getUuid(), null);
 936    }
 937
 938    private PendingIntent createDeleteIntent(Conversation conversation) {
 939        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
 940        intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
 941        if (conversation != null) {
 942            intent.putExtra("uuid", conversation.getUuid());
 943            return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 20), intent, 0);
 944        }
 945        return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
 946    }
 947
 948    private PendingIntent createReplyIntent(Conversation conversation, boolean dismissAfterReply) {
 949        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
 950        intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
 951        intent.putExtra("uuid", conversation.getUuid());
 952        intent.putExtra("dismiss_notification", dismissAfterReply);
 953        final int id = generateRequestCode(conversation, dismissAfterReply ? 12 : 14);
 954        return PendingIntent.getService(mXmppConnectionService, id, intent, 0);
 955    }
 956
 957    private PendingIntent createReadPendingIntent(Conversation conversation) {
 958        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
 959        intent.setAction(XmppConnectionService.ACTION_MARK_AS_READ);
 960        intent.putExtra("uuid", conversation.getUuid());
 961        intent.setPackage(mXmppConnectionService.getPackageName());
 962        return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 16), intent, PendingIntent.FLAG_UPDATE_CURRENT);
 963    }
 964
 965    private PendingIntent createCallAction(String sessionId, final String action, int requestCode) {
 966        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
 967        intent.setAction(action);
 968        intent.setPackage(mXmppConnectionService.getPackageName());
 969        intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, sessionId);
 970        return PendingIntent.getService(mXmppConnectionService, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
 971    }
 972
 973    private PendingIntent createSnoozeIntent(Conversation conversation) {
 974        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
 975        intent.setAction(XmppConnectionService.ACTION_SNOOZE);
 976        intent.putExtra("uuid", conversation.getUuid());
 977        intent.setPackage(mXmppConnectionService.getPackageName());
 978        return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 22), intent, PendingIntent.FLAG_UPDATE_CURRENT);
 979    }
 980
 981    private PendingIntent createTryAgainIntent() {
 982        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
 983        intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
 984        return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
 985    }
 986
 987    private PendingIntent createDismissErrorIntent() {
 988        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
 989        intent.setAction(XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS);
 990        return PendingIntent.getService(mXmppConnectionService, 69, intent, 0);
 991    }
 992
 993    private boolean wasHighlightedOrPrivate(final Message message) {
 994        if (message.getConversation() instanceof Conversation) {
 995            Conversation conversation = (Conversation) message.getConversation();
 996            final String nick = conversation.getMucOptions().getActualNick();
 997            final Pattern highlight = generateNickHighlightPattern(nick);
 998            if (message.getBody() == null || nick == null) {
 999                return false;
1000            }
1001            final Matcher m = highlight.matcher(message.getBody());
1002            return (m.find() || message.isPrivateMessage());
1003        } else {
1004            return false;
1005        }
1006    }
1007
1008    public void setOpenConversation(final Conversation conversation) {
1009        this.mOpenConversation = conversation;
1010    }
1011
1012    public void setIsInForeground(final boolean foreground) {
1013        this.mIsInForeground = foreground;
1014    }
1015
1016    private int getPixel(final int dp) {
1017        final DisplayMetrics metrics = mXmppConnectionService.getResources()
1018                .getDisplayMetrics();
1019        return ((int) (dp * metrics.density));
1020    }
1021
1022    private void markLastNotification() {
1023        this.mLastNotification = SystemClock.elapsedRealtime();
1024    }
1025
1026    private boolean inMiniGracePeriod(final Account account) {
1027        final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
1028                : Config.MINI_GRACE_PERIOD * 2;
1029        return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
1030    }
1031
1032    Notification createForegroundNotification() {
1033        final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1034        mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.app_name));
1035        final List<Account> accounts = mXmppConnectionService.getAccounts();
1036        int enabled = 0;
1037        int connected = 0;
1038        if (accounts != null) {
1039            for (Account account : accounts) {
1040                if (account.isOnlineAndConnected()) {
1041                    connected++;
1042                    enabled++;
1043                } else if (account.isEnabled()) {
1044                    enabled++;
1045                }
1046            }
1047        }
1048        mBuilder.setContentText(mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
1049        final PendingIntent openIntent = createOpenConversationsIntent();
1050        if (openIntent != null) {
1051            mBuilder.setContentIntent(openIntent);
1052        }
1053        mBuilder.setWhen(0);
1054        mBuilder.setPriority(Notification.PRIORITY_MIN);
1055        mBuilder.setSmallIcon(connected > 0 ? R.drawable.ic_link_white_24dp : R.drawable.ic_link_off_white_24dp);
1056
1057        if (Compatibility.runsTwentySix()) {
1058            mBuilder.setChannelId("foreground");
1059        }
1060
1061
1062        return mBuilder.build();
1063    }
1064
1065    private PendingIntent createOpenConversationsIntent() {
1066        try {
1067            return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService, ConversationsActivity.class), 0);
1068        } catch (RuntimeException e) {
1069            return null;
1070        }
1071    }
1072
1073    void updateErrorNotification() {
1074        if (Config.SUPPRESS_ERROR_NOTIFICATION) {
1075            cancel(ERROR_NOTIFICATION_ID);
1076            return;
1077        }
1078        final boolean showAllErrors = QuickConversationsService.isConversations();
1079        final List<Account> errors = new ArrayList<>();
1080        for (final Account account : mXmppConnectionService.getAccounts()) {
1081            if (account.hasErrorStatus() && account.showErrorNotification() && (showAllErrors || account.getLastErrorStatus() == Account.State.UNAUTHORIZED)) {
1082                errors.add(account);
1083            }
1084        }
1085        if (mXmppConnectionService.foregroundNotificationNeedsUpdatingWhenErrorStateChanges()) {
1086            notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
1087        }
1088        final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1089        if (errors.size() == 0) {
1090            cancel(ERROR_NOTIFICATION_ID);
1091            return;
1092        } else if (errors.size() == 1) {
1093            mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
1094            mBuilder.setContentText(errors.get(0).getJid().asBareJid().toString());
1095        } else {
1096            mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
1097            mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
1098        }
1099        mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
1100                mXmppConnectionService.getString(R.string.try_again),
1101                createTryAgainIntent());
1102        mBuilder.setDeleteIntent(createDismissErrorIntent());
1103        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
1104            mBuilder.setVisibility(Notification.VISIBILITY_PRIVATE);
1105            mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
1106        } else {
1107            mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
1108        }
1109        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
1110            mBuilder.setLocalOnly(true);
1111        }
1112        mBuilder.setPriority(Notification.PRIORITY_LOW);
1113        final Intent intent;
1114        if (AccountUtils.MANAGE_ACCOUNT_ACTIVITY != null) {
1115            intent = new Intent(mXmppConnectionService, AccountUtils.MANAGE_ACCOUNT_ACTIVITY);
1116        } else {
1117            intent = new Intent(mXmppConnectionService, EditAccountActivity.class);
1118            intent.putExtra("jid", errors.get(0).getJid().asBareJid().toEscapedString());
1119            intent.putExtra(EditAccountActivity.EXTRA_OPENED_FROM_NOTIFICATION, true);
1120        }
1121        mBuilder.setContentIntent(PendingIntent.getActivity(mXmppConnectionService, 145, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1122        if (Compatibility.runsTwentySix()) {
1123            mBuilder.setChannelId("error");
1124        }
1125        notify(ERROR_NOTIFICATION_ID, mBuilder.build());
1126    }
1127
1128    void updateFileAddingNotification(int current, Message message) {
1129        Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1130        mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.transcoding_video));
1131        mBuilder.setProgress(100, current, false);
1132        mBuilder.setSmallIcon(R.drawable.ic_hourglass_empty_white_24dp);
1133        mBuilder.setContentIntent(createContentIntent(message.getConversation()));
1134        mBuilder.setOngoing(true);
1135        if (Compatibility.runsTwentySix()) {
1136            mBuilder.setChannelId("compression");
1137        }
1138        Notification notification = mBuilder.build();
1139        notify(FOREGROUND_NOTIFICATION_ID, notification);
1140    }
1141
1142    private void notify(String tag, int id, Notification notification) {
1143        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1144        try {
1145            notificationManager.notify(tag, id, notification);
1146        } catch (RuntimeException e) {
1147            Log.d(Config.LOGTAG, "unable to make notification", e);
1148        }
1149    }
1150
1151    public void notify(int id, Notification notification) {
1152        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1153        try {
1154            notificationManager.notify(id, notification);
1155        } catch (RuntimeException e) {
1156            Log.d(Config.LOGTAG, "unable to make notification", e);
1157        }
1158    }
1159
1160    public void cancel(int id) {
1161        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1162        try {
1163            notificationManager.cancel(id);
1164        } catch (RuntimeException e) {
1165            Log.d(Config.LOGTAG, "unable to cancel notification", e);
1166        }
1167    }
1168
1169    private void cancel(String tag, int id) {
1170        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1171        try {
1172            notificationManager.cancel(tag, id);
1173        } catch (RuntimeException e) {
1174            Log.d(Config.LOGTAG, "unable to cancel notification", e);
1175        }
1176    }
1177}