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