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