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        //fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 408        //fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 409        return PendingIntent.getActivity(mXmppConnectionService, requestCode, fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);
 410    }
 411
 412    public void cancelIncomingCallNotification() {
 413        cancel(INCOMING_CALL_NOTIFICATION_ID);
 414    }
 415
 416    public void cancelOngoingCallNotification() {
 417        cancel(ONGOING_CALL_NOTIFICATION_ID);
 418    }
 419
 420    private void pushNow(final Message message) {
 421        mXmppConnectionService.updateUnreadCountBadge();
 422        if (!notify(message)) {
 423            Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because turned off");
 424            return;
 425        }
 426        final boolean isScreenOn = mXmppConnectionService.isInteractive();
 427        if (this.mIsInForeground && isScreenOn && this.mOpenConversation == message.getConversation()) {
 428            Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because conversation is open");
 429            return;
 430        }
 431        synchronized (notifications) {
 432            pushToStack(message);
 433            final Conversational conversation = message.getConversation();
 434            final Account account = conversation.getAccount();
 435            final boolean doNotify = (!(this.mIsInForeground && this.mOpenConversation == null) || !isScreenOn)
 436                    && !account.inGracePeriod()
 437                    && !this.inMiniGracePeriod(account);
 438            updateNotification(doNotify, Collections.singletonList(conversation.getUuid()));
 439        }
 440    }
 441
 442    public void clear() {
 443        synchronized (notifications) {
 444            for (ArrayList<Message> messages : notifications.values()) {
 445                markAsReadIfHasDirectReply(messages);
 446            }
 447            notifications.clear();
 448            updateNotification(false);
 449        }
 450    }
 451
 452    public void clear(final Conversation conversation) {
 453        synchronized (this.mBacklogMessageCounter) {
 454            this.mBacklogMessageCounter.remove(conversation);
 455        }
 456        synchronized (notifications) {
 457            markAsReadIfHasDirectReply(conversation);
 458            if (notifications.remove(conversation.getUuid()) != null) {
 459                cancel(conversation.getUuid(), NOTIFICATION_ID);
 460                updateNotification(false, null, true);
 461            }
 462        }
 463    }
 464
 465    private void markAsReadIfHasDirectReply(final Conversation conversation) {
 466        markAsReadIfHasDirectReply(notifications.get(conversation.getUuid()));
 467    }
 468
 469    private void markAsReadIfHasDirectReply(final ArrayList<Message> messages) {
 470        if (messages != null && messages.size() > 0) {
 471            Message last = messages.get(messages.size() - 1);
 472            if (last.getStatus() != Message.STATUS_RECEIVED) {
 473                if (mXmppConnectionService.markRead((Conversation) last.getConversation(), false)) {
 474                    mXmppConnectionService.updateConversationUi();
 475                }
 476            }
 477        }
 478    }
 479
 480    private void setNotificationColor(final Builder mBuilder) {
 481        mBuilder.setColor(ContextCompat.getColor(mXmppConnectionService, R.color.green600));
 482    }
 483
 484    public void updateNotification() {
 485        synchronized (notifications) {
 486            updateNotification(false);
 487        }
 488    }
 489
 490    private void updateNotification(final boolean notify) {
 491        updateNotification(notify, null, false);
 492    }
 493
 494    private void updateNotification(final boolean notify, final List<String> conversations) {
 495        updateNotification(notify, conversations, false);
 496    }
 497
 498    private void updateNotification(final boolean notify, final List<String> conversations, final boolean summaryOnly) {
 499        final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
 500
 501        final boolean quiteHours = isQuietHours();
 502
 503        final boolean notifyOnlyOneChild = notify && conversations != null && conversations.size() == 1; //if this check is changed to > 0 catchup messages will create one notification per conversation
 504
 505
 506        if (notifications.size() == 0) {
 507            cancel(NOTIFICATION_ID);
 508        } else {
 509            if (notify) {
 510                this.markLastNotification();
 511            }
 512            final Builder mBuilder;
 513            if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
 514                mBuilder = buildSingleConversations(notifications.values().iterator().next(), notify, quiteHours);
 515                modifyForSoundVibrationAndLight(mBuilder, notify, quiteHours, preferences);
 516                notify(NOTIFICATION_ID, mBuilder.build());
 517            } else {
 518                mBuilder = buildMultipleConversation(notify, quiteHours);
 519                if (notifyOnlyOneChild) {
 520                    mBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
 521                }
 522                modifyForSoundVibrationAndLight(mBuilder, notify, quiteHours, preferences);
 523                if (!summaryOnly) {
 524                    for (Map.Entry<String, ArrayList<Message>> entry : notifications.entrySet()) {
 525                        String uuid = entry.getKey();
 526                        final boolean notifyThis = notifyOnlyOneChild ? conversations.contains(uuid) : notify;
 527                        Builder singleBuilder = buildSingleConversations(entry.getValue(), notifyThis, quiteHours);
 528                        if (!notifyOnlyOneChild) {
 529                            singleBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY);
 530                        }
 531                        modifyForSoundVibrationAndLight(singleBuilder, notifyThis, quiteHours, preferences);
 532                        singleBuilder.setGroup(CONVERSATIONS_GROUP);
 533                        setNotificationColor(singleBuilder);
 534                        notify(entry.getKey(), NOTIFICATION_ID, singleBuilder.build());
 535                    }
 536                }
 537                notify(NOTIFICATION_ID, mBuilder.build());
 538            }
 539        }
 540    }
 541
 542    private void modifyForSoundVibrationAndLight(Builder mBuilder, boolean notify, boolean quietHours, SharedPreferences preferences) {
 543        final Resources resources = mXmppConnectionService.getResources();
 544        final String ringtone = preferences.getString("notification_ringtone", resources.getString(R.string.notification_ringtone));
 545        final boolean vibrate = preferences.getBoolean("vibrate_on_notification", resources.getBoolean(R.bool.vibrate_on_notification));
 546        final boolean led = preferences.getBoolean("led", resources.getBoolean(R.bool.led));
 547        final boolean headsup = preferences.getBoolean("notification_headsup", resources.getBoolean(R.bool.headsup_notifications));
 548        if (notify && !quietHours) {
 549            if (vibrate) {
 550                final int dat = 70;
 551                final long[] pattern = {0, 3 * dat, dat, dat};
 552                mBuilder.setVibrate(pattern);
 553            } else {
 554                mBuilder.setVibrate(new long[]{0});
 555            }
 556            Uri uri = Uri.parse(ringtone);
 557            try {
 558                mBuilder.setSound(fixRingtoneUri(uri));
 559            } catch (SecurityException e) {
 560                Log.d(Config.LOGTAG, "unable to use custom notification sound " + uri.toString());
 561            }
 562        } else {
 563            mBuilder.setLocalOnly(true);
 564        }
 565        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 566            mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
 567        }
 568        mBuilder.setPriority(notify ? (headsup ? NotificationCompat.PRIORITY_HIGH : NotificationCompat.PRIORITY_DEFAULT) : NotificationCompat.PRIORITY_LOW);
 569        setNotificationColor(mBuilder);
 570        mBuilder.setDefaults(0);
 571        if (led) {
 572            mBuilder.setLights(LED_COLOR, 2000, 3000);
 573        }
 574    }
 575
 576    private void modifyIncomingCall(Builder mBuilder) {
 577        final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
 578        final Resources resources = mXmppConnectionService.getResources();
 579        final String ringtone = preferences.getString("call_ringtone", resources.getString(R.string.incoming_call_ringtone));
 580        final int dat = 70;
 581        final long[] pattern = {0, 3 * dat, dat, dat, 3 * dat, dat, dat};
 582        mBuilder.setVibrate(pattern);
 583        Uri uri = Uri.parse(ringtone);
 584        try {
 585            mBuilder.setSound(fixRingtoneUri(uri));
 586        } catch (SecurityException e) {
 587            Log.d(Config.LOGTAG, "unable to use custom notification sound " + uri.toString());
 588        }
 589        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 590            mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
 591        }
 592        mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
 593        setNotificationColor(mBuilder);
 594        mBuilder.setLights(LED_COLOR, 2000, 3000);
 595    }
 596
 597    private Uri fixRingtoneUri(Uri uri) {
 598        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && "file".equals(uri.getScheme())) {
 599            return FileBackend.getUriForFile(mXmppConnectionService, new File(uri.getPath()));
 600        } else {
 601            return uri;
 602        }
 603    }
 604
 605    private Builder buildMultipleConversation(final boolean notify, final boolean quietHours) {
 606        final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService, quietHours ? "quiet_hours" : (notify ? "messages" : "silent_messages"));
 607        final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
 608        style.setBigContentTitle(mXmppConnectionService.getString(R.string.x_unread_conversations, notifications.size()));
 609        final StringBuilder names = new StringBuilder();
 610        Conversation conversation = null;
 611        for (final ArrayList<Message> messages : notifications.values()) {
 612            if (messages.size() > 0) {
 613                conversation = (Conversation) messages.get(0).getConversation();
 614                final String name = conversation.getName().toString();
 615                SpannableString styledString;
 616                if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
 617                    int count = messages.size();
 618                    styledString = new SpannableString(name + ": " + mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
 619                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
 620                    style.addLine(styledString);
 621                } else {
 622                    styledString = new SpannableString(name + ": " + UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
 623                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
 624                    style.addLine(styledString);
 625                }
 626                names.append(name);
 627                names.append(", ");
 628            }
 629        }
 630        if (names.length() >= 2) {
 631            names.delete(names.length() - 2, names.length());
 632        }
 633        mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.x_unread_conversations, notifications.size()));
 634        mBuilder.setTicker(mXmppConnectionService.getString(R.string.x_unread_conversations, notifications.size()));
 635        mBuilder.setContentText(names.toString());
 636        mBuilder.setStyle(style);
 637        if (conversation != null) {
 638            mBuilder.setContentIntent(createContentIntent(conversation));
 639        }
 640        mBuilder.setGroupSummary(true);
 641        mBuilder.setGroup(CONVERSATIONS_GROUP);
 642        mBuilder.setDeleteIntent(createDeleteIntent(null));
 643        mBuilder.setSmallIcon(R.drawable.ic_notification);
 644        return mBuilder;
 645    }
 646
 647    private Builder buildSingleConversations(final ArrayList<Message> messages, final boolean notify, final boolean quietHours) {
 648        final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService, quietHours ? "quiet_hours" : (notify ? "messages" : "silent_messages"));
 649        if (messages.size() >= 1) {
 650            final Conversation conversation = (Conversation) messages.get(0).getConversation();
 651            mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
 652                    .get(conversation, AvatarService.getSystemUiAvatarSize(mXmppConnectionService)));
 653            mBuilder.setContentTitle(conversation.getName());
 654            if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
 655                int count = messages.size();
 656                mBuilder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
 657            } else {
 658                Message message;
 659                //TODO starting with Android 9 we might want to put images in MessageStyle
 660                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P && (message = getImage(messages)) != null) {
 661                    modifyForImage(mBuilder, message, messages);
 662                } else {
 663                    modifyForTextOnly(mBuilder, messages);
 664                }
 665                RemoteInput remoteInput = new RemoteInput.Builder("text_reply").setLabel(UIHelper.getMessageHint(mXmppConnectionService, conversation)).build();
 666                PendingIntent markAsReadPendingIntent = createReadPendingIntent(conversation);
 667                NotificationCompat.Action markReadAction = new NotificationCompat.Action.Builder(
 668                        R.drawable.ic_drafts_white_24dp,
 669                        mXmppConnectionService.getString(R.string.mark_as_read),
 670                        markAsReadPendingIntent)
 671                        .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ)
 672                        .setShowsUserInterface(false)
 673                        .build();
 674                String replyLabel = mXmppConnectionService.getString(R.string.reply);
 675                NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
 676                        R.drawable.ic_send_text_offline,
 677                        replyLabel,
 678                        createReplyIntent(conversation, false))
 679                        .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY)
 680                        .setShowsUserInterface(false)
 681                        .addRemoteInput(remoteInput).build();
 682                NotificationCompat.Action wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_wear_reply,
 683                        replyLabel,
 684                        createReplyIntent(conversation, true)).addRemoteInput(remoteInput).build();
 685                mBuilder.extend(new NotificationCompat.WearableExtender().addAction(wearReplyAction));
 686                int addedActionsCount = 1;
 687                mBuilder.addAction(markReadAction);
 688                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 689                    mBuilder.addAction(replyAction);
 690                    ++addedActionsCount;
 691                }
 692
 693                if (displaySnoozeAction(messages)) {
 694                    String label = mXmppConnectionService.getString(R.string.snooze);
 695                    PendingIntent pendingSnoozeIntent = createSnoozeIntent(conversation);
 696                    NotificationCompat.Action snoozeAction = new NotificationCompat.Action.Builder(
 697                            R.drawable.ic_notifications_paused_white_24dp,
 698                            label,
 699                            pendingSnoozeIntent).build();
 700                    mBuilder.addAction(snoozeAction);
 701                    ++addedActionsCount;
 702                }
 703                if (addedActionsCount < 3) {
 704                    final Message firstLocationMessage = getFirstLocationMessage(messages);
 705                    if (firstLocationMessage != null) {
 706                        final PendingIntent pendingShowLocationIntent = createShowLocationIntent(firstLocationMessage);
 707                        if (pendingShowLocationIntent != null) {
 708                            final String label = mXmppConnectionService.getResources().getString(R.string.show_location);
 709                            NotificationCompat.Action locationAction = new NotificationCompat.Action.Builder(
 710                                    R.drawable.ic_room_white_24dp,
 711                                    label,
 712                                    pendingShowLocationIntent).build();
 713                            mBuilder.addAction(locationAction);
 714                            ++addedActionsCount;
 715                        }
 716                    }
 717                }
 718                if (addedActionsCount < 3) {
 719                    Message firstDownloadableMessage = getFirstDownloadableMessage(messages);
 720                    if (firstDownloadableMessage != null) {
 721                        String label = mXmppConnectionService.getResources().getString(R.string.download_x_file, UIHelper.getFileDescriptionString(mXmppConnectionService, firstDownloadableMessage));
 722                        PendingIntent pendingDownloadIntent = createDownloadIntent(firstDownloadableMessage);
 723                        NotificationCompat.Action downloadAction = new NotificationCompat.Action.Builder(
 724                                R.drawable.ic_file_download_white_24dp,
 725                                label,
 726                                pendingDownloadIntent).build();
 727                        mBuilder.addAction(downloadAction);
 728                        ++addedActionsCount;
 729                    }
 730                }
 731            }
 732            if (conversation.getMode() == Conversation.MODE_SINGLE) {
 733                Contact contact = conversation.getContact();
 734                Uri systemAccount = contact.getSystemAccount();
 735                if (systemAccount != null) {
 736                    mBuilder.addPerson(systemAccount.toString());
 737                }
 738            }
 739            mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
 740            mBuilder.setSmallIcon(R.drawable.ic_notification);
 741            mBuilder.setDeleteIntent(createDeleteIntent(conversation));
 742            mBuilder.setContentIntent(createContentIntent(conversation));
 743        }
 744        return mBuilder;
 745    }
 746
 747    private void modifyForImage(final Builder builder, final Message message, final ArrayList<Message> messages) {
 748        try {
 749            final Bitmap bitmap = mXmppConnectionService.getFileBackend().getThumbnail(message, getPixel(288), false);
 750            final ArrayList<Message> tmp = new ArrayList<>();
 751            for (final Message msg : messages) {
 752                if (msg.getType() == Message.TYPE_TEXT
 753                        && msg.getTransferable() == null) {
 754                    tmp.add(msg);
 755                }
 756            }
 757            final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
 758            bigPictureStyle.bigPicture(bitmap);
 759            if (tmp.size() > 0) {
 760                CharSequence text = getMergedBodies(tmp);
 761                bigPictureStyle.setSummaryText(text);
 762                builder.setContentText(text);
 763                builder.setTicker(text);
 764            } else {
 765                final String description = UIHelper.getFileDescriptionString(mXmppConnectionService, message);
 766                builder.setContentText(description);
 767                builder.setTicker(description);
 768            }
 769            builder.setStyle(bigPictureStyle);
 770        } catch (final IOException e) {
 771            modifyForTextOnly(builder, messages);
 772        }
 773    }
 774
 775    private Person getPerson(Message message) {
 776        final Contact contact = message.getContact();
 777        final Person.Builder builder = new Person.Builder();
 778        if (contact != null) {
 779            builder.setName(contact.getDisplayName());
 780            final Uri uri = contact.getSystemAccount();
 781            if (uri != null) {
 782                builder.setUri(uri.toString());
 783            }
 784        } else {
 785            builder.setName(UIHelper.getMessageDisplayName(message));
 786        }
 787        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
 788            builder.setIcon(IconCompat.createWithBitmap(mXmppConnectionService.getAvatarService().get(message, AvatarService.getSystemUiAvatarSize(mXmppConnectionService), false)));
 789        }
 790        return builder.build();
 791    }
 792
 793    private void modifyForTextOnly(final Builder builder, final ArrayList<Message> messages) {
 794        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 795            final Conversation conversation = (Conversation) messages.get(0).getConversation();
 796            final Person.Builder meBuilder = new Person.Builder().setName(mXmppConnectionService.getString(R.string.me));
 797            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
 798                meBuilder.setIcon(IconCompat.createWithBitmap(mXmppConnectionService.getAvatarService().get(conversation.getAccount(), AvatarService.getSystemUiAvatarSize(mXmppConnectionService))));
 799            }
 800            final Person me = meBuilder.build();
 801            NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(me);
 802            final boolean multiple = conversation.getMode() == Conversation.MODE_MULTI;
 803            if (multiple) {
 804                messagingStyle.setConversationTitle(conversation.getName());
 805            }
 806            for (Message message : messages) {
 807                final Person sender = message.getStatus() == Message.STATUS_RECEIVED ? getPerson(message) : null;
 808                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && isImageMessage(message)) {
 809                    final Uri dataUri = FileBackend.getMediaUri(mXmppConnectionService, mXmppConnectionService.getFileBackend().getFile(message));
 810                    NotificationCompat.MessagingStyle.Message imageMessage = new NotificationCompat.MessagingStyle.Message(UIHelper.getMessagePreview(mXmppConnectionService, message).first, message.getTimeSent(), sender);
 811                    if (dataUri != null) {
 812                        imageMessage.setData(message.getMimeType(), dataUri);
 813                    }
 814                    messagingStyle.addMessage(imageMessage);
 815                } else {
 816                    messagingStyle.addMessage(UIHelper.getMessagePreview(mXmppConnectionService, message).first, message.getTimeSent(), sender);
 817                }
 818            }
 819            messagingStyle.setGroupConversation(multiple);
 820            builder.setStyle(messagingStyle);
 821        } else {
 822            if (messages.get(0).getConversation().getMode() == Conversation.MODE_SINGLE) {
 823                builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
 824                final CharSequence preview = UIHelper.getMessagePreview(mXmppConnectionService, messages.get(messages.size() - 1)).first;
 825                builder.setContentText(preview);
 826                builder.setTicker(preview);
 827                builder.setNumber(messages.size());
 828            } else {
 829                final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
 830                SpannableString styledString;
 831                for (Message message : messages) {
 832                    final String name = UIHelper.getMessageDisplayName(message);
 833                    styledString = new SpannableString(name + ": " + message.getBody());
 834                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
 835                    style.addLine(styledString);
 836                }
 837                builder.setStyle(style);
 838                int count = messages.size();
 839                if (count == 1) {
 840                    final String name = UIHelper.getMessageDisplayName(messages.get(0));
 841                    styledString = new SpannableString(name + ": " + messages.get(0).getBody());
 842                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
 843                    builder.setContentText(styledString);
 844                    builder.setTicker(styledString);
 845                } else {
 846                    final String text = mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count);
 847                    builder.setContentText(text);
 848                    builder.setTicker(text);
 849                }
 850            }
 851        }
 852    }
 853
 854    private Message getImage(final Iterable<Message> messages) {
 855        Message image = null;
 856        for (final Message message : messages) {
 857            if (message.getStatus() != Message.STATUS_RECEIVED) {
 858                return null;
 859            }
 860            if (isImageMessage(message)) {
 861                image = message;
 862            }
 863        }
 864        return image;
 865    }
 866
 867    private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
 868        for (final Message message : messages) {
 869            if (message.getTransferable() != null || (message.getType() == Message.TYPE_TEXT && message.treatAsDownloadable())) {
 870                return message;
 871            }
 872        }
 873        return null;
 874    }
 875
 876    private Message getFirstLocationMessage(final Iterable<Message> messages) {
 877        for (final Message message : messages) {
 878            if (message.isGeoUri()) {
 879                return message;
 880            }
 881        }
 882        return null;
 883    }
 884
 885    private CharSequence getMergedBodies(final ArrayList<Message> messages) {
 886        final StringBuilder text = new StringBuilder();
 887        for (Message message : messages) {
 888            if (text.length() != 0) {
 889                text.append("\n");
 890            }
 891            text.append(UIHelper.getMessagePreview(mXmppConnectionService, message).first);
 892        }
 893        return text.toString();
 894    }
 895
 896    private PendingIntent createShowLocationIntent(final Message message) {
 897        Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(mXmppConnectionService, message);
 898        for (Intent intent : intents) {
 899            if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
 900                return PendingIntent.getActivity(mXmppConnectionService, generateRequestCode(message.getConversation(), 18), intent, PendingIntent.FLAG_UPDATE_CURRENT);
 901            }
 902        }
 903        return null;
 904    }
 905
 906    private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
 907        final Intent viewConversationIntent = new Intent(mXmppConnectionService, ConversationsActivity.class);
 908        viewConversationIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
 909        viewConversationIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversationUuid);
 910        if (downloadMessageUuid != null) {
 911            viewConversationIntent.putExtra(ConversationsActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
 912            return PendingIntent.getActivity(mXmppConnectionService,
 913                    generateRequestCode(conversationUuid, 8),
 914                    viewConversationIntent,
 915                    PendingIntent.FLAG_UPDATE_CURRENT);
 916        } else {
 917            return PendingIntent.getActivity(mXmppConnectionService,
 918                    generateRequestCode(conversationUuid, 10),
 919                    viewConversationIntent,
 920                    PendingIntent.FLAG_UPDATE_CURRENT);
 921        }
 922    }
 923
 924    private int generateRequestCode(String uuid, int actionId) {
 925        return (actionId * NOTIFICATION_ID_MULTIPLIER) + (uuid.hashCode() % NOTIFICATION_ID_MULTIPLIER);
 926    }
 927
 928    private int generateRequestCode(Conversational conversation, int actionId) {
 929        return generateRequestCode(conversation.getUuid(), actionId);
 930    }
 931
 932    private PendingIntent createDownloadIntent(final Message message) {
 933        return createContentIntent(message.getConversationUuid(), message.getUuid());
 934    }
 935
 936    private PendingIntent createContentIntent(final Conversational conversation) {
 937        return createContentIntent(conversation.getUuid(), null);
 938    }
 939
 940    private PendingIntent createDeleteIntent(Conversation conversation) {
 941        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
 942        intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
 943        if (conversation != null) {
 944            intent.putExtra("uuid", conversation.getUuid());
 945            return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 20), intent, 0);
 946        }
 947        return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
 948    }
 949
 950    private PendingIntent createReplyIntent(Conversation conversation, boolean dismissAfterReply) {
 951        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
 952        intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
 953        intent.putExtra("uuid", conversation.getUuid());
 954        intent.putExtra("dismiss_notification", dismissAfterReply);
 955        final int id = generateRequestCode(conversation, dismissAfterReply ? 12 : 14);
 956        return PendingIntent.getService(mXmppConnectionService, id, intent, 0);
 957    }
 958
 959    private PendingIntent createReadPendingIntent(Conversation conversation) {
 960        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
 961        intent.setAction(XmppConnectionService.ACTION_MARK_AS_READ);
 962        intent.putExtra("uuid", conversation.getUuid());
 963        intent.setPackage(mXmppConnectionService.getPackageName());
 964        return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 16), intent, PendingIntent.FLAG_UPDATE_CURRENT);
 965    }
 966
 967    private PendingIntent createCallAction(String sessionId, final String action, int requestCode) {
 968        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
 969        intent.setAction(action);
 970        intent.setPackage(mXmppConnectionService.getPackageName());
 971        intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, sessionId);
 972        return PendingIntent.getService(mXmppConnectionService, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
 973    }
 974
 975    private PendingIntent createSnoozeIntent(Conversation conversation) {
 976        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
 977        intent.setAction(XmppConnectionService.ACTION_SNOOZE);
 978        intent.putExtra("uuid", conversation.getUuid());
 979        intent.setPackage(mXmppConnectionService.getPackageName());
 980        return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 22), intent, PendingIntent.FLAG_UPDATE_CURRENT);
 981    }
 982
 983    private PendingIntent createTryAgainIntent() {
 984        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
 985        intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
 986        return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
 987    }
 988
 989    private PendingIntent createDismissErrorIntent() {
 990        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
 991        intent.setAction(XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS);
 992        return PendingIntent.getService(mXmppConnectionService, 69, intent, 0);
 993    }
 994
 995    private boolean wasHighlightedOrPrivate(final Message message) {
 996        if (message.getConversation() instanceof Conversation) {
 997            Conversation conversation = (Conversation) message.getConversation();
 998            final String nick = conversation.getMucOptions().getActualNick();
 999            final Pattern highlight = generateNickHighlightPattern(nick);
1000            if (message.getBody() == null || nick == null) {
1001                return false;
1002            }
1003            final Matcher m = highlight.matcher(message.getBody());
1004            return (m.find() || message.isPrivateMessage());
1005        } else {
1006            return false;
1007        }
1008    }
1009
1010    public void setOpenConversation(final Conversation conversation) {
1011        this.mOpenConversation = conversation;
1012    }
1013
1014    public void setIsInForeground(final boolean foreground) {
1015        this.mIsInForeground = foreground;
1016    }
1017
1018    private int getPixel(final int dp) {
1019        final DisplayMetrics metrics = mXmppConnectionService.getResources()
1020                .getDisplayMetrics();
1021        return ((int) (dp * metrics.density));
1022    }
1023
1024    private void markLastNotification() {
1025        this.mLastNotification = SystemClock.elapsedRealtime();
1026    }
1027
1028    private boolean inMiniGracePeriod(final Account account) {
1029        final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
1030                : Config.MINI_GRACE_PERIOD * 2;
1031        return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
1032    }
1033
1034    Notification createForegroundNotification() {
1035        final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1036        mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.app_name));
1037        final List<Account> accounts = mXmppConnectionService.getAccounts();
1038        int enabled = 0;
1039        int connected = 0;
1040        if (accounts != null) {
1041            for (Account account : accounts) {
1042                if (account.isOnlineAndConnected()) {
1043                    connected++;
1044                    enabled++;
1045                } else if (account.isEnabled()) {
1046                    enabled++;
1047                }
1048            }
1049        }
1050        mBuilder.setContentText(mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
1051        final PendingIntent openIntent = createOpenConversationsIntent();
1052        if (openIntent != null) {
1053            mBuilder.setContentIntent(openIntent);
1054        }
1055        mBuilder.setWhen(0);
1056        mBuilder.setPriority(Notification.PRIORITY_MIN);
1057        mBuilder.setSmallIcon(connected > 0 ? R.drawable.ic_link_white_24dp : R.drawable.ic_link_off_white_24dp);
1058
1059        if (Compatibility.runsTwentySix()) {
1060            mBuilder.setChannelId("foreground");
1061        }
1062
1063
1064        return mBuilder.build();
1065    }
1066
1067    private PendingIntent createOpenConversationsIntent() {
1068        try {
1069            return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService, ConversationsActivity.class), 0);
1070        } catch (RuntimeException e) {
1071            return null;
1072        }
1073    }
1074
1075    void updateErrorNotification() {
1076        if (Config.SUPPRESS_ERROR_NOTIFICATION) {
1077            cancel(ERROR_NOTIFICATION_ID);
1078            return;
1079        }
1080        final boolean showAllErrors = QuickConversationsService.isConversations();
1081        final List<Account> errors = new ArrayList<>();
1082        for (final Account account : mXmppConnectionService.getAccounts()) {
1083            if (account.hasErrorStatus() && account.showErrorNotification() && (showAllErrors || account.getLastErrorStatus() == Account.State.UNAUTHORIZED)) {
1084                errors.add(account);
1085            }
1086        }
1087        if (mXmppConnectionService.foregroundNotificationNeedsUpdatingWhenErrorStateChanges()) {
1088            notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
1089        }
1090        final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1091        if (errors.size() == 0) {
1092            cancel(ERROR_NOTIFICATION_ID);
1093            return;
1094        } else if (errors.size() == 1) {
1095            mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
1096            mBuilder.setContentText(errors.get(0).getJid().asBareJid().toString());
1097        } else {
1098            mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
1099            mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
1100        }
1101        mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
1102                mXmppConnectionService.getString(R.string.try_again),
1103                createTryAgainIntent());
1104        mBuilder.setDeleteIntent(createDismissErrorIntent());
1105        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
1106            mBuilder.setVisibility(Notification.VISIBILITY_PRIVATE);
1107            mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
1108        } else {
1109            mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
1110        }
1111        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
1112            mBuilder.setLocalOnly(true);
1113        }
1114        mBuilder.setPriority(Notification.PRIORITY_LOW);
1115        final Intent intent;
1116        if (AccountUtils.MANAGE_ACCOUNT_ACTIVITY != null) {
1117            intent = new Intent(mXmppConnectionService, AccountUtils.MANAGE_ACCOUNT_ACTIVITY);
1118        } else {
1119            intent = new Intent(mXmppConnectionService, EditAccountActivity.class);
1120            intent.putExtra("jid", errors.get(0).getJid().asBareJid().toEscapedString());
1121            intent.putExtra(EditAccountActivity.EXTRA_OPENED_FROM_NOTIFICATION, true);
1122        }
1123        mBuilder.setContentIntent(PendingIntent.getActivity(mXmppConnectionService, 145, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1124        if (Compatibility.runsTwentySix()) {
1125            mBuilder.setChannelId("error");
1126        }
1127        notify(ERROR_NOTIFICATION_ID, mBuilder.build());
1128    }
1129
1130    void updateFileAddingNotification(int current, Message message) {
1131        Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1132        mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.transcoding_video));
1133        mBuilder.setProgress(100, current, false);
1134        mBuilder.setSmallIcon(R.drawable.ic_hourglass_empty_white_24dp);
1135        mBuilder.setContentIntent(createContentIntent(message.getConversation()));
1136        mBuilder.setOngoing(true);
1137        if (Compatibility.runsTwentySix()) {
1138            mBuilder.setChannelId("compression");
1139        }
1140        Notification notification = mBuilder.build();
1141        notify(FOREGROUND_NOTIFICATION_ID, notification);
1142    }
1143
1144    private void notify(String tag, int id, Notification notification) {
1145        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1146        try {
1147            notificationManager.notify(tag, id, notification);
1148        } catch (RuntimeException e) {
1149            Log.d(Config.LOGTAG, "unable to make notification", e);
1150        }
1151    }
1152
1153    public void notify(int id, Notification notification) {
1154        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1155        try {
1156            notificationManager.notify(id, notification);
1157        } catch (RuntimeException e) {
1158            Log.d(Config.LOGTAG, "unable to make notification", e);
1159        }
1160    }
1161
1162    public void cancel(int id) {
1163        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1164        try {
1165            notificationManager.cancel(id);
1166        } catch (RuntimeException e) {
1167            Log.d(Config.LOGTAG, "unable to cancel notification", e);
1168        }
1169    }
1170
1171    private void cancel(String tag, int id) {
1172        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1173        try {
1174            notificationManager.cancel(tag, id);
1175        } catch (RuntimeException e) {
1176            Log.d(Config.LOGTAG, "unable to cancel notification", e);
1177        }
1178    }
1179}