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