NotificationService.java

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