NotificationService.java

   1package eu.siacs.conversations.services;
   2
   3import android.Manifest;
   4import static eu.siacs.conversations.utils.Compatibility.s;
   5
   6import android.Manifest;
   7import android.app.Notification;
   8import android.app.NotificationChannel;
   9import android.app.NotificationChannelGroup;
  10import android.app.NotificationManager;
  11import android.app.PendingIntent;
  12import android.content.Context;
  13import android.content.Intent;
  14import android.content.SharedPreferences;
  15import android.content.pm.PackageManager;
  16import android.content.pm.ShortcutManager;
  17import android.content.res.Resources;
  18import android.graphics.Bitmap;
  19import android.graphics.Typeface;
  20import android.media.AudioAttributes;
  21import android.media.AudioManager;
  22import android.media.RingtoneManager;
  23import android.net.Uri;
  24import android.os.Build;
  25import android.os.Bundle;
  26import android.os.SystemClock;
  27import android.preference.PreferenceManager;
  28import android.provider.Settings;
  29import android.telecom.PhoneAccountHandle;
  30import android.telecom.TelecomManager;
  31import android.text.SpannableString;
  32import android.text.style.StyleSpan;
  33import android.util.DisplayMetrics;
  34import android.util.Log;
  35import android.util.TypedValue;
  36
  37import androidx.annotation.Nullable;
  38import androidx.annotation.RequiresApi;
  39import androidx.core.app.ActivityCompat;
  40import androidx.core.app.NotificationCompat;
  41import androidx.core.app.NotificationCompat.BigPictureStyle;
  42import androidx.core.app.NotificationCompat.CallStyle;
  43import androidx.core.app.NotificationCompat.Builder;
  44import androidx.core.app.NotificationManagerCompat;
  45import androidx.core.app.Person;
  46import androidx.core.app.RemoteInput;
  47import androidx.core.content.ContextCompat;
  48import androidx.core.content.pm.ShortcutInfoCompat;
  49import androidx.core.graphics.drawable.IconCompat;
  50
  51import com.google.common.base.Joiner;
  52import com.google.common.base.Optional;
  53import com.google.common.base.Splitter;
  54import com.google.common.base.Strings;
  55import com.google.common.collect.ImmutableMap;
  56import com.google.common.collect.Iterables;
  57import com.google.common.primitives.Ints;
  58
  59import eu.siacs.conversations.AppSettings;
  60import eu.siacs.conversations.Config;
  61import eu.siacs.conversations.R;
  62import eu.siacs.conversations.entities.Account;
  63import eu.siacs.conversations.entities.Contact;
  64import eu.siacs.conversations.entities.Conversation;
  65import eu.siacs.conversations.entities.Conversational;
  66import eu.siacs.conversations.entities.Message;
  67import eu.siacs.conversations.entities.Reaction;
  68import eu.siacs.conversations.entities.MucOptions;
  69import eu.siacs.conversations.persistance.FileBackend;
  70import eu.siacs.conversations.ui.ConversationsActivity;
  71import eu.siacs.conversations.ui.EditAccountActivity;
  72import eu.siacs.conversations.ui.RtpSessionActivity;
  73import eu.siacs.conversations.ui.TimePreference;
  74import eu.siacs.conversations.utils.AccountUtils;
  75import eu.siacs.conversations.utils.Compatibility;
  76import eu.siacs.conversations.utils.GeoHelper;
  77import eu.siacs.conversations.utils.TorServiceUtils;
  78import eu.siacs.conversations.utils.UIHelper;
  79import eu.siacs.conversations.xml.Element;
  80import eu.siacs.conversations.xmpp.Jid;
  81import eu.siacs.conversations.xmpp.XmppConnection;
  82import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
  83import eu.siacs.conversations.xmpp.jingle.Media;
  84
  85import java.io.File;
  86import java.io.IOException;
  87import java.util.ArrayList;
  88import java.util.Arrays;
  89import java.util.Collection;
  90import java.util.Calendar;
  91import java.util.Collections;
  92import java.util.HashMap;
  93import java.util.Iterator;
  94import java.util.LinkedHashMap;
  95import java.util.List;
  96import java.util.Map;
  97import java.util.Set;
  98import java.util.concurrent.atomic.AtomicInteger;
  99import java.util.regex.Matcher;
 100import java.util.regex.Pattern;
 101
 102public class NotificationService {
 103
 104    public static final Object CATCHUP_LOCK = new Object();
 105
 106    private static final int LED_COLOR = 0xff7401cf;
 107
 108    private static final long[] CALL_PATTERN = {0, 500, 300, 600, 3000};
 109
 110    private static final String MESSAGES_GROUP = "eu.siacs.conversations.messages";
 111    private static final String MISSED_CALLS_GROUP = "eu.siacs.conversations.missed_calls";
 112    private static final int NOTIFICATION_ID_MULTIPLIER = 1024 * 1024;
 113    static final int FOREGROUND_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 4;
 114    private static final int NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 2;
 115    private static final int ERROR_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 6;
 116    private static final int INCOMING_CALL_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 8;
 117    public static final int ONGOING_CALL_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 10;
 118    public static final int MISSED_CALL_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 12;
 119    private static final int DELIVERY_FAILED_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 13;
 120    public static final int ONGOING_VIDEO_TRANSCODING_NOTIFICATION_ID =
 121            NOTIFICATION_ID_MULTIPLIER * 14;
 122    private final XmppConnectionService mXmppConnectionService;
 123    private final LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<>();
 124    private final HashMap<Conversation, AtomicInteger> mBacklogMessageCounter = new HashMap<>();
 125    private final LinkedHashMap<Conversational, MissedCallsInfo> mMissedCalls =
 126            new LinkedHashMap<>();
 127    private Conversation mOpenConversation;
 128    private boolean mIsInForeground;
 129    private long mLastNotification;
 130
 131    private static final String INCOMING_CALLS_NOTIFICATION_CHANNEL = "incoming_calls_channel";
 132    private static final String INCOMING_CALLS_NOTIFICATION_CHANNEL_PREFIX =
 133            "incoming_calls_channel#";
 134    private static final String MESSAGES_NOTIFICATION_CHANNEL = "messages";
 135
 136    NotificationService(final XmppConnectionService service) {
 137        this.mXmppConnectionService = service;
 138    }
 139
 140    private static boolean displaySnoozeAction(List<Message> messages) {
 141        int numberOfMessagesWithoutReply = 0;
 142        for (Message message : messages) {
 143            if (message.getStatus() == Message.STATUS_RECEIVED) {
 144                ++numberOfMessagesWithoutReply;
 145            } else {
 146                return false;
 147            }
 148        }
 149        return numberOfMessagesWithoutReply >= 3;
 150    }
 151
 152    public static Pattern generateNickHighlightPattern(final String nick) {
 153        return Pattern.compile("(?<=(^|\\s))" + Pattern.quote(nick) + "(?=\\s|$|\\p{Punct})");
 154    }
 155
 156    private static boolean isImageMessage(Message message) {
 157        return message.getType() != Message.TYPE_TEXT
 158                && message.getTransferable() == null
 159                && !message.isDeleted()
 160                && message.getEncryption() != Message.ENCRYPTION_PGP
 161                && message.getFileParams().height > 0;
 162    }
 163
 164    @RequiresApi(api = Build.VERSION_CODES.O)
 165    void initializeChannels() {
 166        final Context c = mXmppConnectionService;
 167        final NotificationManager notificationManager =
 168                c.getSystemService(NotificationManager.class);
 169        if (notificationManager == null) {
 170            return;
 171        }
 172
 173        notificationManager.deleteNotificationChannel("export");
 174        notificationManager.deleteNotificationChannel("incoming_calls");
 175        notificationManager.deleteNotificationChannel(INCOMING_CALLS_NOTIFICATION_CHANNEL);
 176
 177        notificationManager.createNotificationChannelGroup(
 178                new NotificationChannelGroup(
 179                        "status", c.getString(R.string.notification_group_status_information)));
 180        notificationManager.createNotificationChannelGroup(
 181                new NotificationChannelGroup(
 182                        "chats", c.getString(R.string.notification_group_messages)));
 183        notificationManager.createNotificationChannelGroup(
 184                new NotificationChannelGroup(
 185                        "calls", c.getString(R.string.notification_group_calls)));
 186        final NotificationChannel foregroundServiceChannel =
 187                new NotificationChannel(
 188                        "foreground",
 189                        c.getString(R.string.foreground_service_channel_name),
 190                        NotificationManager.IMPORTANCE_MIN);
 191        foregroundServiceChannel.setDescription(
 192                c.getString(
 193                        R.string.foreground_service_channel_description,
 194                        c.getString(R.string.app_name)));
 195        foregroundServiceChannel.setShowBadge(false);
 196        foregroundServiceChannel.setGroup("status");
 197        notificationManager.createNotificationChannel(foregroundServiceChannel);
 198        final NotificationChannel errorChannel =
 199                new NotificationChannel(
 200                        "error",
 201                        c.getString(R.string.error_channel_name),
 202                        NotificationManager.IMPORTANCE_LOW);
 203        errorChannel.setDescription(c.getString(R.string.error_channel_description));
 204        errorChannel.setShowBadge(false);
 205        errorChannel.setGroup("status");
 206        notificationManager.createNotificationChannel(errorChannel);
 207
 208        final NotificationChannel videoCompressionChannel =
 209                new NotificationChannel(
 210                        "compression",
 211                        c.getString(R.string.video_compression_channel_name),
 212                        NotificationManager.IMPORTANCE_LOW);
 213        videoCompressionChannel.setShowBadge(false);
 214        videoCompressionChannel.setGroup("status");
 215        notificationManager.createNotificationChannel(videoCompressionChannel);
 216
 217        final NotificationChannel exportChannel =
 218                new NotificationChannel(
 219                        "backup",
 220                        c.getString(R.string.backup_channel_name),
 221                        NotificationManager.IMPORTANCE_LOW);
 222        exportChannel.setShowBadge(false);
 223        exportChannel.setGroup("status");
 224        notificationManager.createNotificationChannel(exportChannel);
 225
 226        createInitialIncomingCallChannelIfNecessary(c);
 227
 228        final NotificationChannel ongoingCallsChannel =
 229                new NotificationChannel(
 230                        "ongoing_calls",
 231                        c.getString(R.string.ongoing_calls_channel_name),
 232                        NotificationManager.IMPORTANCE_LOW);
 233        ongoingCallsChannel.setShowBadge(false);
 234        ongoingCallsChannel.setGroup("calls");
 235        notificationManager.createNotificationChannel(ongoingCallsChannel);
 236
 237        final NotificationChannel missedCallsChannel =
 238                new NotificationChannel(
 239                        "missed_calls",
 240                        c.getString(R.string.missed_calls_channel_name),
 241                        NotificationManager.IMPORTANCE_HIGH);
 242        missedCallsChannel.setShowBadge(true);
 243        missedCallsChannel.setSound(null, null);
 244        missedCallsChannel.setLightColor(LED_COLOR);
 245        missedCallsChannel.enableLights(true);
 246        missedCallsChannel.setGroup("calls");
 247        notificationManager.createNotificationChannel(missedCallsChannel);
 248
 249        final NotificationChannel messagesChannel =
 250                new NotificationChannel(
 251                        MESSAGES_NOTIFICATION_CHANNEL,
 252                        c.getString(R.string.messages_channel_name),
 253                        NotificationManager.IMPORTANCE_HIGH);
 254        messagesChannel.setShowBadge(true);
 255        messagesChannel.setSound(
 256                RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION),
 257                new AudioAttributes.Builder()
 258                        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
 259                        .setUsage(AudioAttributes.USAGE_NOTIFICATION)
 260                        .build());
 261        messagesChannel.setLightColor(LED_COLOR);
 262        final int dat = 70;
 263        final long[] pattern = {0, 3 * dat, dat, dat};
 264        messagesChannel.setVibrationPattern(pattern);
 265        messagesChannel.enableVibration(true);
 266        messagesChannel.enableLights(true);
 267        messagesChannel.setGroup("chats");
 268        notificationManager.createNotificationChannel(messagesChannel);
 269        final NotificationChannel silentMessagesChannel =
 270                new NotificationChannel(
 271                        "silent_messages",
 272                        c.getString(R.string.silent_messages_channel_name),
 273                        NotificationManager.IMPORTANCE_LOW);
 274        silentMessagesChannel.setDescription(
 275                c.getString(R.string.silent_messages_channel_description));
 276        silentMessagesChannel.setShowBadge(true);
 277        silentMessagesChannel.setLightColor(LED_COLOR);
 278        silentMessagesChannel.enableLights(true);
 279        silentMessagesChannel.setGroup("chats");
 280        notificationManager.createNotificationChannel(silentMessagesChannel);
 281
 282        final NotificationChannel deliveryFailedChannel =
 283                new NotificationChannel(
 284                        "delivery_failed",
 285                        c.getString(R.string.delivery_failed_channel_name),
 286                        NotificationManager.IMPORTANCE_DEFAULT);
 287        deliveryFailedChannel.setShowBadge(false);
 288        deliveryFailedChannel.setSound(
 289                RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION),
 290                new AudioAttributes.Builder()
 291                        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
 292                        .setUsage(AudioAttributes.USAGE_NOTIFICATION)
 293                        .build());
 294        deliveryFailedChannel.setGroup("chats");
 295        notificationManager.createNotificationChannel(deliveryFailedChannel);
 296    }
 297
 298    @RequiresApi(api = Build.VERSION_CODES.O)
 299    private static void createInitialIncomingCallChannelIfNecessary(final Context context) {
 300        final var currentIteration = getCurrentIncomingCallChannelIteration(context);
 301        if (currentIteration.isPresent()) {
 302            return;
 303        }
 304        createInitialIncomingCallChannel(context);
 305    }
 306
 307    @RequiresApi(api = Build.VERSION_CODES.O)
 308    public static Optional<Integer> getCurrentIncomingCallChannelIteration(final Context context) {
 309        final var notificationManager = context.getSystemService(NotificationManager.class);
 310        for (final NotificationChannel channel : notificationManager.getNotificationChannels()) {
 311            final String id = channel.getId();
 312            if (Strings.isNullOrEmpty(id)) {
 313                continue;
 314            }
 315            if (id.startsWith(INCOMING_CALLS_NOTIFICATION_CHANNEL_PREFIX)) {
 316                final var parts = Splitter.on('#').splitToList(id);
 317                if (parts.size() == 2) {
 318                    final var iteration = Ints.tryParse(parts.get(1));
 319                    if (iteration != null) {
 320                        return Optional.of(iteration);
 321                    }
 322                }
 323            }
 324        }
 325        return Optional.absent();
 326    }
 327
 328    @RequiresApi(api = Build.VERSION_CODES.O)
 329    public static Optional<NotificationChannel> getCurrentIncomingCallChannel(
 330            final Context context) {
 331        final var iteration = getCurrentIncomingCallChannelIteration(context);
 332        return iteration.transform(
 333                i -> {
 334                    final var notificationManager =
 335                            context.getSystemService(NotificationManager.class);
 336                    return notificationManager.getNotificationChannel(
 337                            INCOMING_CALLS_NOTIFICATION_CHANNEL_PREFIX + i);
 338                });
 339    }
 340
 341    @RequiresApi(api = Build.VERSION_CODES.O)
 342    private static void createInitialIncomingCallChannel(final Context context) {
 343        final var appSettings = new AppSettings(context);
 344        final var ringtoneUri = appSettings.getRingtone();
 345        createIncomingCallChannel(context, ringtoneUri, 0);
 346    }
 347
 348    @RequiresApi(api = Build.VERSION_CODES.O)
 349    public static void recreateIncomingCallChannel(final Context context, final Uri ringtone) {
 350        final var currentIteration = getCurrentIncomingCallChannelIteration(context);
 351        final int nextIteration;
 352        if (currentIteration.isPresent()) {
 353            final var notificationManager = context.getSystemService(NotificationManager.class);
 354            notificationManager.deleteNotificationChannel(
 355                    INCOMING_CALLS_NOTIFICATION_CHANNEL_PREFIX + currentIteration.get());
 356            nextIteration = currentIteration.get() + 1;
 357        } else {
 358            nextIteration = 0;
 359        }
 360        createIncomingCallChannel(context, ringtone, nextIteration);
 361    }
 362
 363    @RequiresApi(api = Build.VERSION_CODES.O)
 364    private static void createIncomingCallChannel(
 365            final Context context, final Uri ringtoneUri, final int iteration) {
 366        final var notificationManager = context.getSystemService(NotificationManager.class);
 367        final var id = INCOMING_CALLS_NOTIFICATION_CHANNEL_PREFIX + iteration;
 368        Log.d(Config.LOGTAG, "creating incoming call channel with id " + id);
 369        final NotificationChannel incomingCallsChannel =
 370                new NotificationChannel(
 371                        id,
 372                        context.getString(R.string.incoming_calls_channel_name),
 373                        NotificationManager.IMPORTANCE_HIGH);
 374        incomingCallsChannel.setSound(
 375                ringtoneUri,
 376                new AudioAttributes.Builder()
 377                        .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
 378                        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
 379                        .build());
 380        incomingCallsChannel.setShowBadge(false);
 381        incomingCallsChannel.setLightColor(LED_COLOR);
 382        incomingCallsChannel.enableLights(true);
 383        incomingCallsChannel.setGroup("calls");
 384        incomingCallsChannel.setBypassDnd(true);
 385        incomingCallsChannel.enableVibration(true);
 386        incomingCallsChannel.setVibrationPattern(CALL_PATTERN);
 387        notificationManager.createNotificationChannel(incomingCallsChannel);
 388    }
 389
 390    private boolean notifyMessage(final Message message) {
 391        final Conversation conversation = (Conversation) message.getConversation();
 392        return message.getStatus() == Message.STATUS_RECEIVED
 393                && !conversation.isMuted()
 394                && (conversation.alwaysNotify() || (wasHighlightedOrPrivate(message) || (conversation.notifyReplies() && wasReplyToMe(message))))
 395                && (!conversation.isWithStranger() || notificationsFromStrangers())
 396                && message.getType() != Message.TYPE_RTP_SESSION;
 397    }
 398
 399    private boolean notifyMissedCall(final Message message) {
 400        return message.getType() == Message.TYPE_RTP_SESSION
 401                && message.getStatus() == Message.STATUS_RECEIVED;
 402    }
 403
 404    public boolean notificationsFromStrangers() {
 405        return mXmppConnectionService.getBooleanPreference(
 406                "notifications_from_strangers", R.bool.notifications_from_strangers);
 407    }
 408
 409    private boolean isQuietHours(Account account) {
 410        return isQuietHours(mXmppConnectionService, account);
 411    }
 412
 413    public static boolean isQuietHours(Context context, Account account) {
 414        // if (mXmppConnectionService.getAccounts().size() < 2) account = null;
 415        final var suffix = account == null ? "" : ":" + account.getUuid();
 416        final var preferences = PreferenceManager.getDefaultSharedPreferences(context);
 417        if (!preferences.getBoolean("enable_quiet_hours" + suffix, context.getResources().getBoolean(R.bool.enable_quiet_hours))) {
 418            return false;
 419        }
 420        final long startTime =
 421                TimePreference.minutesToTimestamp(
 422                        preferences.getLong("quiet_hours_start" + suffix, TimePreference.DEFAULT_VALUE));
 423        final long endTime =
 424                TimePreference.minutesToTimestamp(
 425                        preferences.getLong("quiet_hours_end" + suffix, TimePreference.DEFAULT_VALUE));
 426        final long nowTime = Calendar.getInstance().getTimeInMillis();
 427
 428        if (endTime < startTime) {
 429            return nowTime > startTime || nowTime < endTime;
 430        } else {
 431            return nowTime > startTime && nowTime < endTime;
 432        }
 433    }
 434
 435    public void pushFromBacklog(final Message message) {
 436        if (notifyMessage(message)) {
 437            synchronized (notifications) {
 438                getBacklogMessageCounter((Conversation) message.getConversation())
 439                        .incrementAndGet();
 440                pushToStack(message);
 441            }
 442        } else if (notifyMissedCall(message)) {
 443            synchronized (mMissedCalls) {
 444                pushMissedCall(message);
 445            }
 446        }
 447    }
 448
 449    private AtomicInteger getBacklogMessageCounter(Conversation conversation) {
 450        synchronized (mBacklogMessageCounter) {
 451            if (!mBacklogMessageCounter.containsKey(conversation)) {
 452                mBacklogMessageCounter.put(conversation, new AtomicInteger(0));
 453            }
 454            return mBacklogMessageCounter.get(conversation);
 455        }
 456    }
 457
 458    void pushFromDirectReply(final Message message) {
 459        synchronized (notifications) {
 460            pushToStack(message);
 461            updateNotification(false);
 462        }
 463    }
 464
 465    public void finishBacklog(boolean notify, Account account) {
 466        synchronized (notifications) {
 467            mXmppConnectionService.updateUnreadCountBadge();
 468            if (account == null || !notify) {
 469                updateNotification(notify);
 470            } else {
 471                final int count;
 472                final List<String> conversations;
 473                synchronized (this.mBacklogMessageCounter) {
 474                    conversations = getBacklogConversations(account);
 475                    count = getBacklogMessageCount(account);
 476                }
 477                updateNotification(count > 0, conversations);
 478            }
 479        }
 480        synchronized (mMissedCalls) {
 481            updateMissedCallNotifications(mMissedCalls.keySet());
 482        }
 483    }
 484
 485    private List<String> getBacklogConversations(Account account) {
 486        final List<String> conversations = new ArrayList<>();
 487        for (Map.Entry<Conversation, AtomicInteger> entry : mBacklogMessageCounter.entrySet()) {
 488            if (entry.getKey().getAccount() == account) {
 489                conversations.add(entry.getKey().getUuid());
 490            }
 491        }
 492        return conversations;
 493    }
 494
 495    private int getBacklogMessageCount(Account account) {
 496        int count = 0;
 497        for (Iterator<Map.Entry<Conversation, AtomicInteger>> it =
 498                        mBacklogMessageCounter.entrySet().iterator();
 499                it.hasNext(); ) {
 500            Map.Entry<Conversation, AtomicInteger> entry = it.next();
 501            if (entry.getKey().getAccount() == account) {
 502                count += entry.getValue().get();
 503                it.remove();
 504            }
 505        }
 506        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": backlog message count=" + count);
 507        return count;
 508    }
 509
 510    void finishBacklog() {
 511        finishBacklog(false, null);
 512    }
 513
 514    private void pushToStack(final Message message) {
 515        final String conversationUuid = message.getConversationUuid();
 516        if (notifications.containsKey(conversationUuid)) {
 517            notifications.get(conversationUuid).add(message);
 518        } else {
 519            final ArrayList<Message> mList = new ArrayList<>();
 520            mList.add(message);
 521            notifications.put(conversationUuid, mList);
 522        }
 523    }
 524
 525    public void push(final Message message) {
 526        synchronized (CATCHUP_LOCK) {
 527            final XmppConnection connection =
 528                    message.getConversation().getAccount().getXmppConnection();
 529            if (connection != null && connection.isWaitingForSmCatchup()) {
 530                connection.incrementSmCatchupMessageCounter();
 531                pushFromBacklog(message);
 532            } else {
 533                pushNow(message);
 534            }
 535        }
 536    }
 537
 538    public void push(final Message reactingTo, final Jid counterpart, final String occupantId, final Collection<String> newReactions) {
 539        if (newReactions.isEmpty()) return;
 540
 541        final var message = reactingTo.reply();
 542        message.appendBody(String.join(" ", newReactions));
 543        message.setCounterpart(counterpart);
 544        message.setOccupantId(occupantId);
 545        message.setStatus(Message.STATUS_RECEIVED);
 546        synchronized (CATCHUP_LOCK) {
 547            final XmppConnection connection =
 548                    message.getConversation().getAccount().getXmppConnection();
 549            if (connection != null && connection.isWaitingForSmCatchup()) {
 550                connection.incrementSmCatchupMessageCounter();
 551                pushFromBacklog(message);
 552            } else {
 553                pushNow(message);
 554            }
 555        }
 556    }
 557
 558    public void pushFailedDelivery(final Message message) {
 559        final Conversation conversation = (Conversation) message.getConversation();
 560        final boolean isScreenLocked = !mXmppConnectionService.isScreenLocked();
 561        if (this.mIsInForeground
 562                && isScreenLocked
 563                && this.mOpenConversation == message.getConversation()) {
 564            Log.d(
 565                    Config.LOGTAG,
 566                    message.getConversation().getAccount().getJid().asBareJid()
 567                            + ": suppressing failed delivery notification because conversation is open");
 568            return;
 569        }
 570        final PendingIntent pendingIntent = createContentIntent(conversation);
 571        final int notificationId =
 572                generateRequestCode(conversation, 0) + DELIVERY_FAILED_NOTIFICATION_ID;
 573        final int failedDeliveries = conversation.countFailedDeliveries();
 574        final Notification notification =
 575                new Builder(mXmppConnectionService, "delivery_failed")
 576                        .setContentTitle(conversation.getName())
 577                        .setAutoCancel(true)
 578                        .setSmallIcon(R.drawable.ic_error_24dp)
 579                        .setContentText(
 580                                mXmppConnectionService
 581                                        .getResources()
 582                                        .getQuantityText(
 583                                                R.plurals.some_messages_could_not_be_delivered,
 584                                                failedDeliveries))
 585                        .setGroup("delivery_failed")
 586                        .setContentIntent(pendingIntent)
 587                        .build();
 588        final Notification summaryNotification =
 589                new Builder(mXmppConnectionService, "delivery_failed")
 590                        .setContentTitle(
 591                                mXmppConnectionService.getString(R.string.failed_deliveries))
 592                        .setContentText(
 593                                mXmppConnectionService
 594                                        .getResources()
 595                                        .getQuantityText(
 596                                                R.plurals.some_messages_could_not_be_delivered,
 597                                                1024))
 598                        .setSmallIcon(R.drawable.ic_error_24dp)
 599                        .setGroup("delivery_failed")
 600                        .setGroupSummary(true)
 601                        .setAutoCancel(true)
 602                        .build();
 603        notify(notificationId, notification);
 604        notify(DELIVERY_FAILED_NOTIFICATION_ID, summaryNotification);
 605    }
 606
 607    public synchronized void startRinging(final AbstractJingleConnection.Id id, final Set<Media> media) {
 608        if (isQuietHours(id.getContact().getAccount())) return;
 609
 610        showIncomingCallNotification(id, media, false);
 611    }
 612
 613    private void showIncomingCallNotification(
 614            final AbstractJingleConnection.Id id,
 615            final Set<Media> media,
 616            final boolean onlyAlertOnce) {
 617        final Intent fullScreenIntent =
 618                new Intent(mXmppConnectionService, RtpSessionActivity.class);
 619        fullScreenIntent.putExtra(
 620                RtpSessionActivity.EXTRA_ACCOUNT,
 621                id.account.getJid().asBareJid().toEscapedString());
 622        fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_WITH, id.with.toEscapedString());
 623        fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.sessionId);
 624        fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 625        fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 626        final int channelIteration;
 627        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
 628            channelIteration = getCurrentIncomingCallChannelIteration(mXmppConnectionService).or(0);
 629        } else {
 630            channelIteration = 0;
 631        }
 632        final var channelId = INCOMING_CALLS_NOTIFICATION_CHANNEL_PREFIX + channelIteration;
 633        Log.d(
 634                Config.LOGTAG,
 635                "showing incoming call notification on channel "
 636                        + channelId
 637                        + ", onlyAlertOnce="
 638                        + onlyAlertOnce);
 639        final NotificationCompat.Builder builder =
 640                new NotificationCompat.Builder(
 641                        mXmppConnectionService, channelId);
 642        final Contact contact = id.getContact();
 643        builder.addPerson(getPerson(contact));
 644        ShortcutInfoCompat info = mXmppConnectionService.getShortcutService().getShortcutInfoCompat(contact);
 645        builder.setShortcutInfo(info);
 646        if (Build.VERSION.SDK_INT >= 30) {
 647            mXmppConnectionService.getSystemService(ShortcutManager.class).pushDynamicShortcut(info.toShortcutInfo());
 648        }
 649        if (mXmppConnectionService.getAccounts().size() > 1) {
 650            builder.setSubText(contact.getAccount().getJid().asBareJid().toString());
 651        }
 652        NotificationCompat.CallStyle style = NotificationCompat.CallStyle.forIncomingCall(
 653            getPerson(contact),
 654            createCallAction(
 655                id.sessionId,
 656                XmppConnectionService.ACTION_DISMISS_CALL,
 657                102),
 658            createPendingRtpSession(id, RtpSessionActivity.ACTION_ACCEPT_CALL, 103)
 659        );
 660        if (media.contains(Media.VIDEO)) {
 661            style.setIsVideo(true);
 662            builder.setSmallIcon(R.drawable.ic_videocam_24dp);
 663            builder.setContentTitle(
 664                    mXmppConnectionService.getString(R.string.rtp_state_incoming_video_call));
 665        } else {
 666            style.setIsVideo(false);
 667            builder.setSmallIcon(R.drawable.ic_call_24dp);
 668            builder.setContentTitle(
 669                    mXmppConnectionService.getString(R.string.rtp_state_incoming_call));
 670        }
 671        builder.setStyle(style);
 672        builder.setLargeIcon(FileBackend.drawDrawable(
 673                mXmppConnectionService
 674                        .getAvatarService()
 675                        .get(contact, AvatarService.getSystemUiAvatarSize(mXmppConnectionService))));
 676        final Uri systemAccount = contact.getSystemAccount();
 677        if (systemAccount != null) {
 678            builder.addPerson(systemAccount.toString());
 679        }
 680        if (!onlyAlertOnce) {
 681            final var appSettings = new AppSettings(mXmppConnectionService);
 682            final var ringtone = appSettings.getRingtone();
 683            if (ringtone != null) {
 684                builder.setSound(ringtone, AudioManager.STREAM_RING);
 685            }
 686            builder.setVibrate(CALL_PATTERN);
 687        }
 688        builder.setOnlyAlertOnce(onlyAlertOnce);
 689        builder.setContentText(id.account.getRoster().getContact(id.with).getDisplayName());
 690        builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
 691        builder.setPriority(NotificationCompat.PRIORITY_HIGH);
 692        builder.setCategory(NotificationCompat.CATEGORY_CALL);
 693        final PendingIntent pendingIntent = createPendingRtpSession(id, Intent.ACTION_VIEW, 101);
 694        builder.setFullScreenIntent(pendingIntent, true);
 695        builder.setContentIntent(pendingIntent); // old androids need this?
 696        builder.setOngoing(true);
 697        builder.addAction(
 698                new NotificationCompat.Action.Builder(
 699                                R.drawable.ic_call_end_24dp,
 700                                mXmppConnectionService.getString(R.string.dismiss_call),
 701                                createCallAction(
 702                                        id.sessionId,
 703                                        XmppConnectionService.ACTION_DISMISS_CALL,
 704                                        102))
 705                        .build());
 706        builder.addAction(
 707                new NotificationCompat.Action.Builder(
 708                                R.drawable.ic_call_24dp,
 709                                mXmppConnectionService.getString(R.string.answer_call),
 710                                createPendingRtpSession(
 711                                        id, RtpSessionActivity.ACTION_ACCEPT_CALL, 103))
 712                        .build());
 713        modifyIncomingCall(builder, id.account);
 714        final Notification notification = builder.build();
 715        notification.audioAttributes = new AudioAttributes.Builder()
 716                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
 717                .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
 718                .build();
 719        notification.flags = notification.flags | Notification.FLAG_INSISTENT;
 720        notify(INCOMING_CALL_NOTIFICATION_ID, notification);
 721    }
 722
 723    public Notification getOngoingCallNotification(
 724            final XmppConnectionService.OngoingCall ongoingCall) {
 725        final AbstractJingleConnection.Id id = ongoingCall.id;
 726        final NotificationCompat.Builder builder =
 727                new NotificationCompat.Builder(mXmppConnectionService, "ongoing_calls");
 728        final Contact contact = id.account.getRoster().getContact(id.with);
 729        NotificationCompat.CallStyle style = NotificationCompat.CallStyle.forOngoingCall(
 730            getPerson(contact),
 731            createCallAction(id.sessionId, XmppConnectionService.ACTION_END_CALL, 104)
 732        );
 733        if (ongoingCall.media.contains(Media.VIDEO)) {
 734            style.setIsVideo(true);
 735            builder.setSmallIcon(R.drawable.ic_videocam_24dp);
 736            if (ongoingCall.reconnecting) {
 737                builder.setContentTitle(
 738                        mXmppConnectionService.getString(R.string.reconnecting_video_call));
 739            } else {
 740                builder.setContentTitle(
 741                        mXmppConnectionService.getString(R.string.ongoing_video_call));
 742            }
 743        } else {
 744            style.setIsVideo(false);
 745            builder.setSmallIcon(R.drawable.ic_call_24dp);
 746            if (ongoingCall.reconnecting) {
 747                builder.setContentTitle(
 748                        mXmppConnectionService.getString(R.string.reconnecting_call));
 749            } else {
 750                builder.setContentTitle(mXmppConnectionService.getString(R.string.ongoing_call));
 751            }
 752        }
 753        builder.setStyle(style);
 754        builder.setContentText(contact.getDisplayName());
 755        builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
 756        builder.setPriority(NotificationCompat.PRIORITY_HIGH);
 757        builder.setCategory(NotificationCompat.CATEGORY_CALL);
 758        builder.setContentIntent(createPendingRtpSession(id, Intent.ACTION_VIEW, 101));
 759        builder.setOngoing(true);
 760        builder.addAction(
 761                new NotificationCompat.Action.Builder(
 762                                R.drawable.ic_call_end_24dp,
 763                                mXmppConnectionService.getString(R.string.hang_up),
 764                                createCallAction(
 765                                        id.sessionId, XmppConnectionService.ACTION_END_CALL, 104))
 766                        .build());
 767        builder.setLocalOnly(true);
 768        return builder.build();
 769    }
 770
 771    private PendingIntent createPendingRtpSession(
 772            final AbstractJingleConnection.Id id, final String action, final int requestCode) {
 773        final Intent fullScreenIntent =
 774                new Intent(mXmppConnectionService, RtpSessionActivity.class);
 775        fullScreenIntent.setAction(action);
 776        fullScreenIntent.putExtra(
 777                RtpSessionActivity.EXTRA_ACCOUNT,
 778                id.account.getJid().asBareJid().toEscapedString());
 779        fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_WITH, id.with.toEscapedString());
 780        fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.sessionId);
 781        return PendingIntent.getActivity(
 782                mXmppConnectionService,
 783                requestCode,
 784                fullScreenIntent,
 785                s()
 786                        ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
 787                        : PendingIntent.FLAG_UPDATE_CURRENT);
 788    }
 789
 790    public void cancelIncomingCallNotification() {
 791        cancel(INCOMING_CALL_NOTIFICATION_ID);
 792    }
 793
 794    public boolean stopSoundAndVibration() {
 795        final var jingleRtpConnection =
 796                mXmppConnectionService.getJingleConnectionManager().getOngoingRtpConnection();
 797        if (jingleRtpConnection == null) {
 798            return false;
 799        }
 800        final var notificationManager = mXmppConnectionService.getSystemService(NotificationManager.class);
 801        if (Iterables.any(
 802                Arrays.asList(notificationManager.getActiveNotifications()),
 803                n -> n.getId() == INCOMING_CALL_NOTIFICATION_ID)) {
 804            Log.d(Config.LOGTAG, "stopping sound and vibration for incoming call notification");
 805            showIncomingCallNotification(
 806                    jingleRtpConnection.getId(), jingleRtpConnection.getMedia(), true);
 807            return true;
 808        }
 809        return false;
 810    }
 811
 812    public static void cancelIncomingCallNotification(final Context context) {
 813        final NotificationManagerCompat notificationManager =
 814                NotificationManagerCompat.from(context);
 815        try {
 816            notificationManager.cancel(INCOMING_CALL_NOTIFICATION_ID);
 817        } catch (RuntimeException e) {
 818            Log.d(Config.LOGTAG, "unable to cancel incoming call notification after crash", e);
 819        }
 820    }
 821
 822    private void pushNow(final Message message) {
 823        mXmppConnectionService.updateUnreadCountBadge();
 824        if (!notifyMessage(message)) {
 825            Log.d(
 826                    Config.LOGTAG,
 827                    message.getConversation().getAccount().getJid().asBareJid()
 828                            + ": suppressing notification because turned off");
 829            return;
 830        }
 831        final boolean isScreenLocked = mXmppConnectionService.isScreenLocked();
 832        if (this.mIsInForeground
 833                && !isScreenLocked
 834                && this.mOpenConversation == message.getConversation()) {
 835            Log.d(
 836                    Config.LOGTAG,
 837                    message.getConversation().getAccount().getJid().asBareJid()
 838                            + ": suppressing notification because conversation is open");
 839            return;
 840        }
 841        synchronized (notifications) {
 842            pushToStack(message);
 843            final Conversational conversation = message.getConversation();
 844            final Account account = conversation.getAccount();
 845            final boolean doNotify =
 846                    (!(this.mIsInForeground && this.mOpenConversation == null) || isScreenLocked)
 847                            && !account.inGracePeriod()
 848                            && !this.inMiniGracePeriod(account);
 849            updateNotification(doNotify, Collections.singletonList(conversation.getUuid()));
 850        }
 851    }
 852
 853    private void pushMissedCall(final Message message) {
 854        final Conversational conversation = message.getConversation();
 855        final MissedCallsInfo info = mMissedCalls.get(conversation);
 856        if (info == null) {
 857            mMissedCalls.put(conversation, new MissedCallsInfo(message.getTimeSent()));
 858        } else {
 859            info.newMissedCall(message.getTimeSent());
 860        }
 861    }
 862
 863    public void pushMissedCallNow(final Message message) {
 864        synchronized (mMissedCalls) {
 865            pushMissedCall(message);
 866            updateMissedCallNotifications(Collections.singleton(message.getConversation()));
 867        }
 868    }
 869
 870    public void clear(final Conversation conversation) {
 871        clearMessages(conversation);
 872        clearMissedCalls(conversation);
 873    }
 874
 875    public void clearMessages() {
 876        synchronized (notifications) {
 877            for (ArrayList<Message> messages : notifications.values()) {
 878                markAsReadIfHasDirectReply(messages);
 879            }
 880            notifications.clear();
 881            updateNotification(false);
 882        }
 883    }
 884
 885    public void clearMessages(final Conversation conversation) {
 886        synchronized (this.mBacklogMessageCounter) {
 887            this.mBacklogMessageCounter.remove(conversation);
 888        }
 889        synchronized (notifications) {
 890            markAsReadIfHasDirectReply(conversation);
 891            if (notifications.remove(conversation.getUuid()) != null) {
 892                cancel(conversation.getUuid(), NOTIFICATION_ID);
 893                updateNotification(false, null, true);
 894            }
 895        }
 896    }
 897
 898    public void clearMissedCall(final Message message) {
 899        synchronized (mMissedCalls) {
 900            final Iterator<Map.Entry<Conversational, MissedCallsInfo>> iterator =
 901                    mMissedCalls.entrySet().iterator();
 902            while (iterator.hasNext()) {
 903                final Map.Entry<Conversational, MissedCallsInfo> entry = iterator.next();
 904                final Conversational conversational = entry.getKey();
 905                final MissedCallsInfo missedCallsInfo = entry.getValue();
 906                if (conversational.getUuid().equals(message.getConversation().getUuid())) {
 907                    if (missedCallsInfo.removeMissedCall()) {
 908                        cancel(conversational.getUuid(), MISSED_CALL_NOTIFICATION_ID);
 909                        Log.d(
 910                                Config.LOGTAG,
 911                                conversational.getAccount().getJid().asBareJid()
 912                                        + ": dismissed missed call because call was picked up on other device");
 913                        iterator.remove();
 914                    }
 915                }
 916            }
 917            updateMissedCallNotifications(null);
 918        }
 919    }
 920
 921    public void clearMissedCalls() {
 922        synchronized (mMissedCalls) {
 923            for (final Conversational conversation : mMissedCalls.keySet()) {
 924                cancel(conversation.getUuid(), MISSED_CALL_NOTIFICATION_ID);
 925            }
 926            mMissedCalls.clear();
 927            updateMissedCallNotifications(null);
 928        }
 929    }
 930
 931    public void clearMissedCalls(final Conversation conversation) {
 932        synchronized (mMissedCalls) {
 933            if (mMissedCalls.remove(conversation) != null) {
 934                cancel(conversation.getUuid(), MISSED_CALL_NOTIFICATION_ID);
 935                updateMissedCallNotifications(null);
 936            }
 937        }
 938    }
 939
 940    private void markAsReadIfHasDirectReply(final Conversation conversation) {
 941        markAsReadIfHasDirectReply(notifications.get(conversation.getUuid()));
 942    }
 943
 944    private void markAsReadIfHasDirectReply(final ArrayList<Message> messages) {
 945        if (messages != null && !messages.isEmpty()) {
 946            Message last = messages.get(messages.size() - 1);
 947            if (last.getStatus() != Message.STATUS_RECEIVED) {
 948                if (mXmppConnectionService.markRead((Conversation) last.getConversation(), false)) {
 949                    mXmppConnectionService.updateConversationUi();
 950                }
 951            }
 952        }
 953    }
 954
 955    private void setNotificationColor(final Builder mBuilder, Account account) {
 956        int color;
 957        if (account != null && mXmppConnectionService.getAccounts().size() > 1) {
 958		      color = account.getColor(false);
 959        } else {
 960            TypedValue typedValue = new TypedValue();
 961            mXmppConnectionService.getTheme().resolveAttribute(com.google.android.material.R.attr.colorPrimary, typedValue, true);
 962            color = typedValue.data;
 963        }
 964        mBuilder.setColor(color);
 965    }
 966
 967    public void updateNotification() {
 968        synchronized (notifications) {
 969            updateNotification(false);
 970        }
 971    }
 972
 973    private void updateNotification(final boolean notify) {
 974        updateNotification(notify, null, false);
 975    }
 976
 977    private void updateNotification(final boolean notify, final List<String> conversations) {
 978        updateNotification(notify, conversations, false);
 979    }
 980
 981    private void updateNotification(
 982            final boolean notify, final List<String> conversations, final boolean summaryOnly) {
 983        final SharedPreferences preferences =
 984                PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
 985
 986        final boolean notifyOnlyOneChild =
 987                notify
 988                        && conversations != null
 989                        && conversations.size()
 990                                == 1; // if this check is changed to > 0 catchup messages will
 991        // create one notification per conversation
 992
 993        if (notifications.isEmpty()) {
 994            cancel(NOTIFICATION_ID);
 995        } else {
 996            if (notify) {
 997                this.markLastNotification();
 998            }
 999            final Builder mBuilder;
1000            if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
1001                final Account account = notifications.values().iterator().next().get(0).getConversation().getAccount();
1002                mBuilder = buildSingleConversations(notifications.values().iterator().next(), notify, isQuietHours(account));
1003                modifyForSoundVibrationAndLight(mBuilder, notify, preferences, account);
1004                notify(NOTIFICATION_ID, mBuilder.build());
1005            } else {
1006                mBuilder = buildMultipleConversation(notify, isQuietHours(null));
1007                if (notifyOnlyOneChild) {
1008                    mBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
1009                }
1010                modifyForSoundVibrationAndLight(mBuilder, notify, preferences, null);
1011                if (!summaryOnly) {
1012                    for (Map.Entry<String, ArrayList<Message>> entry : notifications.entrySet()) {
1013                        String uuid = entry.getKey();
1014                        final boolean notifyThis =
1015                                notifyOnlyOneChild ? conversations.contains(uuid) : notify;
1016                        final Account account = entry.getValue().isEmpty() ? null : entry.getValue().get(0).getConversation().getAccount();
1017                        Builder singleBuilder =
1018                                buildSingleConversations(entry.getValue(), notifyThis, isQuietHours(account));
1019                        if (!notifyOnlyOneChild) {
1020                            singleBuilder.setGroupAlertBehavior(
1021                                    NotificationCompat.GROUP_ALERT_SUMMARY);
1022                        }
1023                        modifyForSoundVibrationAndLight(singleBuilder, notifyThis, preferences, account);
1024                        singleBuilder.setGroup(MESSAGES_GROUP);
1025                        notify(entry.getKey(), NOTIFICATION_ID, singleBuilder.build());
1026                    }
1027                }
1028                notify(NOTIFICATION_ID, mBuilder.build());
1029            }
1030        }
1031    }
1032
1033    private void updateMissedCallNotifications(final Set<Conversational> update) {
1034        if (mMissedCalls.isEmpty()) {
1035            cancel(MISSED_CALL_NOTIFICATION_ID);
1036            return;
1037        }
1038        if (mMissedCalls.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
1039            final Conversational conversation = mMissedCalls.keySet().iterator().next();
1040            final MissedCallsInfo info = mMissedCalls.values().iterator().next();
1041            final Notification notification = missedCall(conversation, info);
1042            notify(MISSED_CALL_NOTIFICATION_ID, notification);
1043        } else {
1044            final Notification summary = missedCallsSummary();
1045            notify(MISSED_CALL_NOTIFICATION_ID, summary);
1046            if (update != null) {
1047                for (final Conversational conversation : update) {
1048                    final MissedCallsInfo info = mMissedCalls.get(conversation);
1049                    if (info != null) {
1050                        final Notification notification = missedCall(conversation, info);
1051                        notify(conversation.getUuid(), MISSED_CALL_NOTIFICATION_ID, notification);
1052                    }
1053                }
1054            }
1055        }
1056    }
1057
1058    private void modifyForSoundVibrationAndLight(
1059            Builder mBuilder, boolean notify, SharedPreferences preferences, Account account) {
1060        final Resources resources = mXmppConnectionService.getResources();
1061        final String ringtone =
1062                preferences.getString(
1063                        AppSettings.NOTIFICATION_RINGTONE,
1064                        resources.getString(R.string.notification_ringtone));
1065        final boolean vibrate =
1066                preferences.getBoolean(
1067                        AppSettings.NOTIFICATION_VIBRATE,
1068                        resources.getBoolean(R.bool.vibrate_on_notification));
1069        final boolean led =
1070                preferences.getBoolean(
1071                        AppSettings.NOTIFICATION_LED, resources.getBoolean(R.bool.led));
1072        final boolean headsup =
1073                preferences.getBoolean(
1074                        AppSettings.NOTIFICATION_HEADS_UP, resources.getBoolean(R.bool.headsup_notifications));
1075        if (notify && !isQuietHours(account)) {
1076            if (vibrate) {
1077                final int dat = 70;
1078                final long[] pattern = {0, 3 * dat, dat, dat};
1079                mBuilder.setVibrate(pattern);
1080            } else {
1081                mBuilder.setVibrate(new long[] {0});
1082            }
1083            Uri uri = Uri.parse(ringtone);
1084            try {
1085                mBuilder.setSound(fixRingtoneUri(uri));
1086            } catch (SecurityException e) {
1087                Log.d(Config.LOGTAG, "unable to use custom notification sound " + uri.toString());
1088            }
1089        } else {
1090            mBuilder.setLocalOnly(true);
1091        }
1092        mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
1093        mBuilder.setPriority(
1094                notify
1095                        ? (headsup
1096                                ? NotificationCompat.PRIORITY_HIGH
1097                                : NotificationCompat.PRIORITY_DEFAULT)
1098                        : NotificationCompat.PRIORITY_LOW);
1099        setNotificationColor(mBuilder, account);
1100        mBuilder.setDefaults(0);
1101        if (led) {
1102            mBuilder.setLights(LED_COLOR, 2000, 3000);
1103        }
1104    }
1105
1106    private void modifyIncomingCall(final Builder mBuilder, Account account) {
1107        mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
1108        setNotificationColor(mBuilder, account);
1109        if (Build.VERSION.SDK_INT >= 26 && account != null && mXmppConnectionService.getAccounts().size() > 1) {
1110            mBuilder.setColorized(true);
1111        }
1112        mBuilder.setLights(LED_COLOR, 2000, 3000);
1113    }
1114
1115    private Uri fixRingtoneUri(Uri uri) {
1116        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && "file".equals(uri.getScheme())) {
1117            return FileBackend.getUriForFile(mXmppConnectionService, new File(uri.getPath()));
1118        } else {
1119            return uri;
1120        }
1121    }
1122
1123    private Notification missedCallsSummary() {
1124        final Builder publicBuilder = buildMissedCallsSummary(true);
1125        final Builder builder = buildMissedCallsSummary(false);
1126        builder.setPublicVersion(publicBuilder.build());
1127        return builder.build();
1128    }
1129
1130    private Builder buildMissedCallsSummary(boolean publicVersion) {
1131        final Builder builder =
1132                new NotificationCompat.Builder(mXmppConnectionService, "missed_calls");
1133        int totalCalls = 0;
1134        final List<String> names = new ArrayList<>();
1135        long lastTime = 0;
1136        for (final Map.Entry<Conversational, MissedCallsInfo> entry : mMissedCalls.entrySet()) {
1137            final Conversational conversation = entry.getKey();
1138            final MissedCallsInfo missedCallsInfo = entry.getValue();
1139            names.add(conversation.getContact().getDisplayName());
1140            totalCalls += missedCallsInfo.getNumberOfCalls();
1141            lastTime = Math.max(lastTime, missedCallsInfo.getLastTime());
1142        }
1143        final String title =
1144                (totalCalls == 1)
1145                        ? mXmppConnectionService.getString(R.string.missed_call)
1146                        : (mMissedCalls.size() == 1)
1147                                ? mXmppConnectionService
1148                                        .getResources()
1149                                        .getQuantityString(
1150                                                R.plurals.n_missed_calls, totalCalls, totalCalls)
1151                                : mXmppConnectionService
1152                                        .getResources()
1153                                        .getQuantityString(
1154                                                R.plurals.n_missed_calls_from_m_contacts,
1155                                                mMissedCalls.size(),
1156                                                totalCalls,
1157                                                mMissedCalls.size());
1158        builder.setContentTitle(title);
1159        builder.setTicker(title);
1160        if (!publicVersion) {
1161            builder.setContentText(Joiner.on(", ").join(names));
1162        }
1163        builder.setSmallIcon(R.drawable.ic_call_missed_24db);
1164        builder.setGroupSummary(true);
1165        builder.setGroup(MISSED_CALLS_GROUP);
1166        builder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
1167        builder.setCategory(NotificationCompat.CATEGORY_CALL);
1168        builder.setWhen(lastTime);
1169        if (!mMissedCalls.isEmpty()) {
1170            final Conversational firstConversation = mMissedCalls.keySet().iterator().next();
1171            builder.setContentIntent(createContentIntent(firstConversation));
1172        }
1173        builder.setDeleteIntent(createMissedCallsDeleteIntent(null));
1174        modifyMissedCall(builder, null);
1175        return builder;
1176    }
1177
1178    private Notification missedCall(final Conversational conversation, final MissedCallsInfo info) {
1179        final Builder publicBuilder = buildMissedCall(conversation, info, true);
1180        final Builder builder = buildMissedCall(conversation, info, false);
1181        builder.setPublicVersion(publicBuilder.build());
1182        return builder.build();
1183    }
1184
1185    private Builder buildMissedCall(
1186            final Conversational conversation, final MissedCallsInfo info, boolean publicVersion) {
1187        final Builder builder =
1188                new NotificationCompat.Builder(mXmppConnectionService, isQuietHours(conversation.getAccount()) ? "quiet_hours" : "missed_calls");
1189        final String title =
1190                (info.getNumberOfCalls() == 1)
1191                        ? mXmppConnectionService.getString(R.string.missed_call)
1192                        : mXmppConnectionService
1193                                .getResources()
1194                                .getQuantityString(
1195                                        R.plurals.n_missed_calls,
1196                                        info.getNumberOfCalls(),
1197                                        info.getNumberOfCalls());
1198        builder.setContentTitle(title);
1199        if (mXmppConnectionService.getAccounts().size() > 1) {
1200            builder.setSubText(conversation.getAccount().getJid().asBareJid().toString());
1201        }
1202        final String name = conversation.getContact().getDisplayName();
1203        if (publicVersion) {
1204            builder.setTicker(title);
1205        } else {
1206            builder.setTicker(
1207                    mXmppConnectionService
1208                            .getResources()
1209                            .getQuantityString(
1210                                    R.plurals.n_missed_calls_from_x,
1211                                    info.getNumberOfCalls(),
1212                                    info.getNumberOfCalls(),
1213                                    name));
1214            builder.setContentText(name);
1215        }
1216        builder.setSmallIcon(R.drawable.ic_call_missed_24db);
1217        builder.setGroup(MISSED_CALLS_GROUP);
1218        builder.setCategory(NotificationCompat.CATEGORY_CALL);
1219        builder.setWhen(info.getLastTime());
1220        builder.setContentIntent(createContentIntent(conversation));
1221        builder.setDeleteIntent(createMissedCallsDeleteIntent(conversation));
1222        if (!publicVersion && conversation instanceof Conversation) {
1223            builder.setLargeIcon(FileBackend.drawDrawable(
1224                    mXmppConnectionService
1225                            .getAvatarService()
1226                            .get(
1227                                    (Conversation) conversation,
1228                                    AvatarService.getSystemUiAvatarSize(mXmppConnectionService))));
1229        }
1230        modifyMissedCall(builder, conversation.getAccount());
1231        return builder;
1232    }
1233
1234    private void modifyMissedCall(final Builder builder, Account account) {
1235        final SharedPreferences preferences =
1236                PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
1237        final Resources resources = mXmppConnectionService.getResources();
1238        final boolean led = preferences.getBoolean("led", resources.getBoolean(R.bool.led));
1239        if (led) {
1240            builder.setLights(LED_COLOR, 2000, 3000);
1241        }
1242        builder.setPriority(isQuietHours(account) ? NotificationCompat.PRIORITY_LOW : NotificationCompat.PRIORITY_HIGH);
1243        builder.setSound(null);
1244        setNotificationColor(builder, account);
1245    }
1246
1247    private Builder buildMultipleConversation(final boolean notify, final boolean quietHours) {
1248        final Builder mBuilder =
1249                new NotificationCompat.Builder(
1250                        mXmppConnectionService,
1251                        notify && !quietHours ? MESSAGES_NOTIFICATION_CHANNEL : "silent_messages");
1252        final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
1253        style.setBigContentTitle(
1254                mXmppConnectionService
1255                        .getResources()
1256                        .getQuantityString(
1257                                R.plurals.x_unread_conversations,
1258                                notifications.size(),
1259                                notifications.size()));
1260        final List<String> names = new ArrayList<>();
1261        Conversation conversation = null;
1262        for (final ArrayList<Message> messages : notifications.values()) {
1263            if (messages.isEmpty()) {
1264                continue;
1265            }
1266            conversation = (Conversation) messages.get(0).getConversation();
1267            final String name = conversation.getName().toString();
1268            SpannableString styledString;
1269            if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
1270                int count = messages.size();
1271                styledString =
1272                        new SpannableString(
1273                                name
1274                                        + ": "
1275                                        + mXmppConnectionService
1276                                                .getResources()
1277                                                .getQuantityString(
1278                                                        R.plurals.x_messages, count, count));
1279                styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
1280                style.addLine(styledString);
1281            } else {
1282                styledString =
1283                        new SpannableString(
1284                                name
1285                                        + ": "
1286                                        + UIHelper.getMessagePreview(
1287                                                        mXmppConnectionService, messages.get(0))
1288                                                .first);
1289                styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
1290                style.addLine(styledString);
1291            }
1292            names.add(name);
1293        }
1294        final String contentTitle =
1295                mXmppConnectionService
1296                        .getResources()
1297                        .getQuantityString(
1298                                R.plurals.x_unread_conversations,
1299                                notifications.size(),
1300                                notifications.size());
1301        mBuilder.setContentTitle(contentTitle);
1302        mBuilder.setTicker(contentTitle);
1303        mBuilder.setContentText(Joiner.on(", ").join(names));
1304        mBuilder.setStyle(style);
1305        if (conversation != null) {
1306            mBuilder.setContentIntent(createContentIntent(conversation));
1307        }
1308        mBuilder.setGroupSummary(true);
1309        mBuilder.setGroup(MESSAGES_GROUP);
1310        mBuilder.setDeleteIntent(createDeleteIntent(null));
1311        mBuilder.setSmallIcon(R.drawable.ic_notification);
1312        return mBuilder;
1313    }
1314
1315    private Builder buildSingleConversations(
1316            final ArrayList<Message> messages, final boolean notify, final boolean quietHours) {
1317        final var channel = notify && !quietHours ? MESSAGES_NOTIFICATION_CHANNEL : "silent_messages";
1318        final Builder notificationBuilder =
1319                new NotificationCompat.Builder(mXmppConnectionService, channel);
1320        if (messages.isEmpty()) {
1321            return notificationBuilder;
1322        }
1323        final Conversation conversation = (Conversation) messages.get(0).getConversation();
1324        notificationBuilder.setLargeIcon(FileBackend.drawDrawable(
1325                mXmppConnectionService
1326                        .getAvatarService()
1327                        .get(
1328                                conversation,
1329                                AvatarService.getSystemUiAvatarSize(mXmppConnectionService))));
1330        notificationBuilder.setContentTitle(conversation.getName());
1331        if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
1332            int count = messages.size();
1333            notificationBuilder.setContentText(
1334                    mXmppConnectionService
1335                            .getResources()
1336                            .getQuantityString(R.plurals.x_messages, count, count));
1337        } else {
1338            final Message message;
1339            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P
1340                    && (message = getImage(messages)) != null) {
1341                modifyForImage(notificationBuilder, message, messages);
1342            } else {
1343                modifyForTextOnly(notificationBuilder, messages);
1344            }
1345            RemoteInput remoteInput =
1346                    new RemoteInput.Builder("text_reply")
1347                            .setLabel(UIHelper.getMessageHint(mXmppConnectionService, conversation))
1348                            .build();
1349            PendingIntent markAsReadPendingIntent = createReadPendingIntent(conversation);
1350            NotificationCompat.Action markReadAction =
1351                    new NotificationCompat.Action.Builder(
1352                                    R.drawable.ic_mark_chat_read_24dp,
1353                                    mXmppConnectionService.getString(R.string.mark_as_read),
1354                                    markAsReadPendingIntent)
1355                            .setSemanticAction(
1356                                    NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ)
1357                            .setShowsUserInterface(false)
1358                            .build();
1359            final String replyLabel = mXmppConnectionService.getString(R.string.reply);
1360            final String lastMessageUuid = Iterables.getLast(messages).getUuid();
1361            final NotificationCompat.Action replyAction =
1362                    new NotificationCompat.Action.Builder(
1363                                    R.drawable.ic_send_24dp,
1364                                    replyLabel,
1365                                    createReplyIntent(conversation, lastMessageUuid, false))
1366                            .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY)
1367                            .setShowsUserInterface(false)
1368                            .addRemoteInput(remoteInput)
1369                            .build();
1370            final NotificationCompat.Action wearReplyAction =
1371                    new NotificationCompat.Action.Builder(
1372                                    R.drawable.ic_reply_24dp,
1373                                    replyLabel,
1374                                    createReplyIntent(conversation, lastMessageUuid, true))
1375                            .addRemoteInput(remoteInput)
1376                            .build();
1377            notificationBuilder.extend(
1378                    new NotificationCompat.WearableExtender().addAction(wearReplyAction));
1379            int addedActionsCount = 1;
1380            notificationBuilder.addAction(markReadAction);
1381            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1382                notificationBuilder.addAction(replyAction);
1383                ++addedActionsCount;
1384            }
1385
1386            if (displaySnoozeAction(messages)) {
1387                String label = mXmppConnectionService.getString(R.string.snooze);
1388                PendingIntent pendingSnoozeIntent = createSnoozeIntent(conversation);
1389                NotificationCompat.Action snoozeAction =
1390                        new NotificationCompat.Action.Builder(
1391                                        R.drawable.ic_notifications_paused_24dp,
1392                                        label,
1393                                        pendingSnoozeIntent)
1394                                .build();
1395                notificationBuilder.addAction(snoozeAction);
1396                ++addedActionsCount;
1397            }
1398            if (addedActionsCount < 3) {
1399                final Message firstLocationMessage = getFirstLocationMessage(messages);
1400                if (firstLocationMessage != null) {
1401                    final PendingIntent pendingShowLocationIntent =
1402                            createShowLocationIntent(firstLocationMessage);
1403                    if (pendingShowLocationIntent != null) {
1404                        final String label =
1405                                mXmppConnectionService
1406                                        .getResources()
1407                                        .getString(R.string.show_location);
1408                        NotificationCompat.Action locationAction =
1409                                new NotificationCompat.Action.Builder(
1410                                                R.drawable.ic_location_pin_24dp,
1411                                                label,
1412                                                pendingShowLocationIntent)
1413                                        .build();
1414                        notificationBuilder.addAction(locationAction);
1415                        ++addedActionsCount;
1416                    }
1417                }
1418            }
1419            if (addedActionsCount < 3) {
1420                Message firstDownloadableMessage = getFirstDownloadableMessage(messages);
1421                if (firstDownloadableMessage != null) {
1422                    String label =
1423                            mXmppConnectionService
1424                                    .getResources()
1425                                    .getString(
1426                                            R.string.download_x_file,
1427                                            UIHelper.getFileDescriptionString(
1428                                                    mXmppConnectionService,
1429                                                    firstDownloadableMessage));
1430                    PendingIntent pendingDownloadIntent =
1431                            createDownloadIntent(firstDownloadableMessage);
1432                    NotificationCompat.Action downloadAction =
1433                            new NotificationCompat.Action.Builder(
1434                                            R.drawable.ic_download_24dp,
1435                                            label,
1436                                            pendingDownloadIntent)
1437                                    .build();
1438                    notificationBuilder.addAction(downloadAction);
1439                    ++addedActionsCount;
1440                }
1441            }
1442        }
1443        final ShortcutInfoCompat info;
1444        if (conversation.getMode() == Conversation.MODE_SINGLE) {
1445            final Contact contact = conversation.getContact();
1446            final Uri systemAccount = contact.getSystemAccount();
1447            if (systemAccount != null) {
1448                notificationBuilder.addPerson(systemAccount.toString());
1449            }
1450            info = mXmppConnectionService.getShortcutService().getShortcutInfoCompat(contact);
1451        } else {
1452            info =
1453                    mXmppConnectionService
1454                            .getShortcutService()
1455                            .getShortcutInfoCompat(conversation.getMucOptions());
1456        }
1457        notificationBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
1458        notificationBuilder.setSmallIcon(R.drawable.ic_notification);
1459        notificationBuilder.setDeleteIntent(createDeleteIntent(conversation));
1460        notificationBuilder.setContentIntent(createContentIntent(conversation));
1461        if (mXmppConnectionService.getAccounts().size() > 1) {
1462            notificationBuilder.setSubText(conversation.getAccount().getJid().asBareJid().toString());
1463        }
1464        if (channel.equals(MESSAGES_NOTIFICATION_CHANNEL)) {
1465            // when do not want 'customized' notifications for silent notifications in their
1466            // respective channels
1467            notificationBuilder.setShortcutInfo(info);
1468            if (Build.VERSION.SDK_INT >= 30) {
1469                mXmppConnectionService
1470                        .getSystemService(ShortcutManager.class)
1471                        .pushDynamicShortcut(info.toShortcutInfo());
1472                // mBuilder.setBubbleMetadata(new NotificationCompat.BubbleMetadata.Builder(info.getId()).build());
1473            }
1474        }
1475        return notificationBuilder;
1476    }
1477
1478    private void modifyForImage(
1479            final Builder builder, final Message message, final ArrayList<Message> messages) {
1480        try {
1481            final Bitmap bitmap = mXmppConnectionService.getFileBackend().getThumbnailBitmap(message, mXmppConnectionService.getResources(), getPixel(288));
1482            final ArrayList<Message> tmp = new ArrayList<>();
1483            for (final Message msg : messages) {
1484                if (msg.getType() == Message.TYPE_TEXT && msg.getTransferable() == null) {
1485                    tmp.add(msg);
1486                }
1487            }
1488            final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
1489            bigPictureStyle.bigPicture(bitmap);
1490            if (tmp.size() > 0) {
1491                CharSequence text = getMergedBodies(tmp);
1492                bigPictureStyle.setSummaryText(text);
1493                builder.setContentText(text);
1494                builder.setTicker(text);
1495            } else {
1496                final String description =
1497                        UIHelper.getFileDescriptionString(mXmppConnectionService, message);
1498                builder.setContentText(description);
1499                builder.setTicker(description);
1500            }
1501            builder.setStyle(bigPictureStyle);
1502        } catch (final IOException e) {
1503            modifyForTextOnly(builder, messages);
1504        }
1505    }
1506
1507    private Person getPerson(Message message) {
1508        final Contact contact = message.getContact();
1509        final Person.Builder builder = new Person.Builder();
1510        if (contact != null) {
1511            builder.setName(contact.getDisplayName());
1512            final Uri uri = contact.getSystemAccount();
1513            if (uri != null) {
1514                builder.setUri(uri.toString());
1515            }
1516        } else {
1517            builder.setName(UIHelper.getMessageDisplayName(message));
1518        }
1519        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
1520            final Jid jid = contact == null ? message.getCounterpart() : contact.getJid();
1521            builder.setKey(jid.toString());
1522            final Conversation c = mXmppConnectionService.find(message.getConversation().getAccount(), jid);
1523            if (c != null) {
1524                builder.setImportant(c.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false));
1525            }
1526            builder.setIcon(
1527                    IconCompat.createWithBitmap(FileBackend.drawDrawable(
1528                            mXmppConnectionService
1529                                    .getAvatarService()
1530                                    .get(
1531                                            message,
1532                                            AvatarService.getSystemUiAvatarSize(
1533                                                    mXmppConnectionService),
1534                                            false))));
1535        }
1536        return builder.build();
1537    }
1538
1539    private Person getPerson(Contact contact) {
1540        final Person.Builder builder = new Person.Builder();
1541        builder.setName(contact.getDisplayName());
1542        final Uri uri = contact.getSystemAccount();
1543        if (uri != null) {
1544            builder.setUri(uri.toString());
1545        }
1546        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
1547            final Jid jid = contact.getJid();
1548            builder.setKey(jid.toString());
1549            final Conversation c = mXmppConnectionService.find(contact.getAccount(), jid);
1550            if (c != null) {
1551                builder.setImportant(c.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false));
1552            }
1553            builder.setIcon(
1554                    IconCompat.createWithBitmap(FileBackend.drawDrawable(
1555                            mXmppConnectionService
1556                                    .getAvatarService()
1557                                    .get(
1558                                            contact,
1559                                            AvatarService.getSystemUiAvatarSize(
1560                                                    mXmppConnectionService),
1561                                            false))));
1562        }
1563        return builder.build();
1564    }
1565
1566    private void modifyForTextOnly(final Builder builder, final ArrayList<Message> messages) {
1567        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1568            final Conversation conversation = (Conversation) messages.get(0).getConversation();
1569            final Person.Builder meBuilder =
1570                    new Person.Builder().setName(mXmppConnectionService.getString(R.string.me));
1571            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
1572                meBuilder.setIcon(
1573                        IconCompat.createWithBitmap(FileBackend.drawDrawable(
1574                                mXmppConnectionService
1575                                        .getAvatarService()
1576                                        .get(
1577                                                conversation.getAccount(),
1578                                                AvatarService.getSystemUiAvatarSize(
1579                                                        mXmppConnectionService)))));
1580            }
1581            final Person me = meBuilder.build();
1582            NotificationCompat.MessagingStyle messagingStyle =
1583                    new NotificationCompat.MessagingStyle(me);
1584            final boolean multiple = conversation.getMode() == Conversation.MODE_MULTI || messages.get(0).getTrueCounterpart() != null;
1585            if (multiple) {
1586                messagingStyle.setConversationTitle(conversation.getName());
1587            }
1588            for (Message message : messages) {
1589                final Person sender =
1590                        message.getStatus() == Message.STATUS_RECEIVED ? getPerson(message) : null;
1591                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && isImageMessage(message)) {
1592                    final Uri dataUri =
1593                            FileBackend.getMediaUri(
1594                                    mXmppConnectionService,
1595                                    mXmppConnectionService.getFileBackend().getFile(message));
1596                    NotificationCompat.MessagingStyle.Message imageMessage =
1597                            new NotificationCompat.MessagingStyle.Message(
1598                                    UIHelper.getMessagePreview(mXmppConnectionService, message)
1599                                            .first,
1600                                    message.getTimeSent(),
1601                                    sender);
1602                    if (dataUri != null) {
1603                        imageMessage.setData(message.getMimeType(), dataUri);
1604                    }
1605                    messagingStyle.addMessage(imageMessage);
1606                } else {
1607                    messagingStyle.addMessage(
1608                            UIHelper.getMessagePreview(mXmppConnectionService, message).first,
1609                            message.getTimeSent(),
1610                            sender);
1611                }
1612            }
1613            messagingStyle.setGroupConversation(multiple);
1614            builder.setStyle(messagingStyle);
1615        } else {
1616            if (messages.get(0).getConversation().getMode() == Conversation.MODE_SINGLE && messages.get(0).getTrueCounterpart() == null) {
1617                builder.setStyle(
1618                        new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
1619                final CharSequence preview =
1620                        UIHelper.getMessagePreview(
1621                                        mXmppConnectionService, messages.get(messages.size() - 1))
1622                                .first;
1623                builder.setContentText(preview);
1624                builder.setTicker(preview);
1625                builder.setNumber(messages.size());
1626            } else {
1627                final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
1628                SpannableString styledString;
1629                for (Message message : messages) {
1630                    final String name = UIHelper.getMessageDisplayName(message);
1631                    styledString = new SpannableString(name + ": " + message.getBody());
1632                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
1633                    style.addLine(styledString);
1634                }
1635                builder.setStyle(style);
1636                int count = messages.size();
1637                if (count == 1) {
1638                    final String name = UIHelper.getMessageDisplayName(messages.get(0));
1639                    styledString = new SpannableString(name + ": " + messages.get(0).getBody());
1640                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
1641                    builder.setContentText(styledString);
1642                    builder.setTicker(styledString);
1643                } else {
1644                    final String text =
1645                            mXmppConnectionService
1646                                    .getResources()
1647                                    .getQuantityString(R.plurals.x_messages, count, count);
1648                    builder.setContentText(text);
1649                    builder.setTicker(text);
1650                }
1651            }
1652        }
1653    }
1654
1655    private Message getImage(final Iterable<Message> messages) {
1656        Message image = null;
1657        for (final Message message : messages) {
1658            if (message.getStatus() != Message.STATUS_RECEIVED) {
1659                return null;
1660            }
1661            if (isImageMessage(message)) {
1662                image = message;
1663            }
1664        }
1665        return image;
1666    }
1667
1668    private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
1669        for (final Message message : messages) {
1670            if (message.getTransferable() != null
1671                    || (message.getType() == Message.TYPE_TEXT && message.treatAsDownloadable())) {
1672                return message;
1673            }
1674        }
1675        return null;
1676    }
1677
1678    private Message getFirstLocationMessage(final Iterable<Message> messages) {
1679        for (final Message message : messages) {
1680            if (message.isGeoUri()) {
1681                return message;
1682            }
1683        }
1684        return null;
1685    }
1686
1687    private CharSequence getMergedBodies(final ArrayList<Message> messages) {
1688        final StringBuilder text = new StringBuilder();
1689        for (Message message : messages) {
1690            if (text.length() != 0) {
1691                text.append("\n");
1692            }
1693            text.append(UIHelper.getMessagePreview(mXmppConnectionService, message).first);
1694        }
1695        return text.toString();
1696    }
1697
1698    private PendingIntent createShowLocationIntent(final Message message) {
1699        Iterable<Intent> intents =
1700                GeoHelper.createGeoIntentsFromMessage(mXmppConnectionService, message);
1701        for (final Intent intent : intents) {
1702            if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
1703                return PendingIntent.getActivity(
1704                        mXmppConnectionService,
1705                        generateRequestCode(message.getConversation(), 18),
1706                        intent,
1707                        s()
1708                                ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1709                                : PendingIntent.FLAG_UPDATE_CURRENT);
1710            }
1711        }
1712        return null;
1713    }
1714
1715    private PendingIntent createContentIntent(
1716            final String conversationUuid, final String downloadMessageUuid) {
1717        final Intent viewConversationIntent =
1718                new Intent(mXmppConnectionService, ConversationsActivity.class);
1719        viewConversationIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
1720        viewConversationIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversationUuid);
1721        if (downloadMessageUuid != null) {
1722            viewConversationIntent.putExtra(
1723                    ConversationsActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
1724            return PendingIntent.getActivity(
1725                    mXmppConnectionService,
1726                    generateRequestCode(conversationUuid, 8),
1727                    viewConversationIntent,
1728                    s()
1729                            ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1730                            : PendingIntent.FLAG_UPDATE_CURRENT);
1731        } else {
1732            return PendingIntent.getActivity(
1733                    mXmppConnectionService,
1734                    generateRequestCode(conversationUuid, 10),
1735                    viewConversationIntent,
1736                    s()
1737                            ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1738                            : PendingIntent.FLAG_UPDATE_CURRENT);
1739        }
1740    }
1741
1742    private int generateRequestCode(String uuid, int actionId) {
1743        return (actionId * NOTIFICATION_ID_MULTIPLIER)
1744                + (uuid.hashCode() % NOTIFICATION_ID_MULTIPLIER);
1745    }
1746
1747    private int generateRequestCode(Conversational conversation, int actionId) {
1748        return generateRequestCode(conversation.getUuid(), actionId);
1749    }
1750
1751    private PendingIntent createDownloadIntent(final Message message) {
1752        return createContentIntent(message.getConversationUuid(), message.getUuid());
1753    }
1754
1755    private PendingIntent createContentIntent(final Conversational conversation) {
1756        return createContentIntent(conversation.getUuid(), null);
1757    }
1758
1759    private PendingIntent createDeleteIntent(final Conversation conversation) {
1760        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1761        intent.setAction(XmppConnectionService.ACTION_CLEAR_MESSAGE_NOTIFICATION);
1762        if (conversation != null) {
1763            intent.putExtra("uuid", conversation.getUuid());
1764            return PendingIntent.getService(
1765                    mXmppConnectionService,
1766                    generateRequestCode(conversation, 20),
1767                    intent,
1768                    s()
1769                            ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1770                            : PendingIntent.FLAG_UPDATE_CURRENT);
1771        }
1772        return PendingIntent.getService(
1773                mXmppConnectionService,
1774                0,
1775                intent,
1776                s()
1777                        ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1778                        : PendingIntent.FLAG_UPDATE_CURRENT);
1779    }
1780
1781    private PendingIntent createMissedCallsDeleteIntent(final Conversational conversation) {
1782        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1783        intent.setAction(XmppConnectionService.ACTION_CLEAR_MISSED_CALL_NOTIFICATION);
1784        if (conversation != null) {
1785            intent.putExtra("uuid", conversation.getUuid());
1786            return PendingIntent.getService(
1787                    mXmppConnectionService,
1788                    generateRequestCode(conversation, 21),
1789                    intent,
1790                    s()
1791                            ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1792                            : PendingIntent.FLAG_UPDATE_CURRENT);
1793        }
1794        return PendingIntent.getService(
1795                mXmppConnectionService,
1796                1,
1797                intent,
1798                s()
1799                        ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1800                        : PendingIntent.FLAG_UPDATE_CURRENT);
1801    }
1802
1803    private PendingIntent createReplyIntent(
1804            final Conversation conversation,
1805            final String lastMessageUuid,
1806            final boolean dismissAfterReply) {
1807        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1808        intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
1809        intent.putExtra("uuid", conversation.getUuid());
1810        intent.putExtra("dismiss_notification", dismissAfterReply);
1811        intent.putExtra("last_message_uuid", lastMessageUuid);
1812        final int id = generateRequestCode(conversation, dismissAfterReply ? 12 : 14);
1813        return PendingIntent.getService(
1814                mXmppConnectionService,
1815                id,
1816                intent,
1817                s()
1818                        ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1819                        : PendingIntent.FLAG_UPDATE_CURRENT);
1820    }
1821
1822    private PendingIntent createReadPendingIntent(Conversation conversation) {
1823        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1824        intent.setAction(XmppConnectionService.ACTION_MARK_AS_READ);
1825        intent.putExtra("uuid", conversation.getUuid());
1826        intent.setPackage(mXmppConnectionService.getPackageName());
1827        return PendingIntent.getService(
1828                mXmppConnectionService,
1829                generateRequestCode(conversation, 16),
1830                intent,
1831                s()
1832                        ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1833                        : PendingIntent.FLAG_UPDATE_CURRENT);
1834    }
1835
1836    private PendingIntent createCallAction(String sessionId, final String action, int requestCode) {
1837        return pendingServiceIntent(
1838                mXmppConnectionService,
1839                action,
1840                requestCode,
1841                ImmutableMap.of(RtpSessionActivity.EXTRA_SESSION_ID, sessionId));
1842    }
1843
1844    private PendingIntent createSnoozeIntent(final Conversation conversation) {
1845        return pendingServiceIntent(
1846                mXmppConnectionService,
1847                XmppConnectionService.ACTION_SNOOZE,
1848                generateRequestCode(conversation, 22),
1849                ImmutableMap.of("uuid", conversation.getUuid()));
1850    }
1851
1852    private static PendingIntent pendingServiceIntent(
1853            final Context context, final String action, final int requestCode) {
1854        return pendingServiceIntent(context, action, requestCode, ImmutableMap.of());
1855    }
1856
1857    private static PendingIntent pendingServiceIntent(
1858            final Context context,
1859            final String action,
1860            final int requestCode,
1861            final Map<String, String> extras) {
1862        final Intent intent = new Intent(context, XmppConnectionService.class);
1863        intent.setAction(action);
1864        for (final Map.Entry<String, String> entry : extras.entrySet()) {
1865            intent.putExtra(entry.getKey(), entry.getValue());
1866        }
1867        return PendingIntent.getService(
1868                context,
1869                requestCode,
1870                intent,
1871                s()
1872                        ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1873                        : PendingIntent.FLAG_UPDATE_CURRENT);
1874    }
1875
1876    private boolean wasHighlightedOrPrivate(final Message message) {
1877        if (message.getConversation() instanceof Conversation) {
1878            Conversation conversation = (Conversation) message.getConversation();
1879            final MucOptions.User sender = conversation.getMucOptions().findUserByFullJid(message.getCounterpart());
1880            final boolean muted = message.getStatus() == Message.STATUS_RECEIVED && mXmppConnectionService.isMucUserMuted(new MucOptions.User(null, conversation.getJid(), message.getOccupantId(), null, null));
1881            if (muted) return false;
1882            if (sender != null && sender.getAffiliation().ranks(MucOptions.Affiliation.MEMBER) && message.isAttention()) {
1883                return true;
1884            }
1885            final String nick = conversation.getMucOptions().getActualNick();
1886            final Pattern highlight = generateNickHighlightPattern(nick);
1887            final String name = conversation.getMucOptions().getActualName();
1888            final Pattern highlightName = generateNickHighlightPattern(name);
1889            if (message.getBody() == null || (nick == null && name == null)) {
1890                return false;
1891            }
1892            final Matcher m = highlight.matcher(message.getBody(true));
1893            final Matcher m2 = highlightName.matcher(message.getBody(true));
1894            return (m.find() || m2.find() || message.isPrivateMessage());
1895        } else {
1896            return false;
1897        }
1898    }
1899
1900    private boolean wasReplyToMe(final Message message) {
1901       final Element reply = message.getReply();
1902       if (reply == null || reply.getAttribute("id") == null) return false;
1903       final Message parent = ((Conversation) message.getConversation()).findMessageWithRemoteIdAndCounterpart(reply.getAttribute("id"), null);
1904       if (parent == null) return false;
1905       return parent.getStatus() >= Message.STATUS_SEND;
1906    }
1907
1908    public void setOpenConversation(final Conversation conversation) {
1909        this.mOpenConversation = conversation;
1910    }
1911
1912    public void setIsInForeground(final boolean foreground) {
1913        this.mIsInForeground = foreground;
1914    }
1915
1916    private int getPixel(final int dp) {
1917        final DisplayMetrics metrics = mXmppConnectionService.getResources().getDisplayMetrics();
1918        return ((int) (dp * metrics.density));
1919    }
1920
1921    private void markLastNotification() {
1922        this.mLastNotification = SystemClock.elapsedRealtime();
1923    }
1924
1925    private boolean inMiniGracePeriod(final Account account) {
1926        final int miniGrace =
1927                account.getStatus() == Account.State.ONLINE
1928                        ? Config.MINI_GRACE_PERIOD
1929                        : Config.MINI_GRACE_PERIOD * 2;
1930        return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
1931    }
1932
1933    Notification createForegroundNotification() {
1934        final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1935        mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.app_name));
1936        final List<Account> accounts = mXmppConnectionService.getAccounts();
1937        final int enabled;
1938        final int connected;
1939        if (accounts == null) {
1940            enabled = 0;
1941            connected = 0;
1942        } else {
1943            enabled = Iterables.size(Iterables.filter(accounts, Account::isEnabled));
1944            connected = Iterables.size(Iterables.filter(accounts, Account::isOnlineAndConnected));
1945        }
1946        mBuilder.setContentText(
1947                mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
1948        final PendingIntent openIntent = createOpenConversationsIntent();
1949        if (openIntent != null) {
1950            mBuilder.setContentIntent(openIntent);
1951        }
1952        mBuilder.setWhen(0)
1953                .setPriority(Notification.PRIORITY_MIN)
1954                .setSmallIcon(connected >= enabled ? R.drawable.ic_link_24dp : R.drawable.ic_link_off_24dp)
1955                .setLocalOnly(true);
1956
1957        if (Compatibility.runsTwentySix()) {
1958            mBuilder.setChannelId("foreground");
1959            mBuilder.addAction(
1960                    R.drawable.ic_logout_24dp,
1961                    mXmppConnectionService.getString(R.string.log_out),
1962                    pendingServiceIntent(
1963                            mXmppConnectionService,
1964                            XmppConnectionService.ACTION_TEMPORARILY_DISABLE,
1965                            87));
1966            mBuilder.addAction(
1967                    R.drawable.ic_notifications_off_24dp,
1968                    mXmppConnectionService.getString(R.string.hide_notification),
1969                    pendingNotificationSettingsIntent(mXmppConnectionService));
1970        }
1971
1972        return mBuilder.build();
1973    }
1974
1975    @RequiresApi(api = Build.VERSION_CODES.O)
1976    private static PendingIntent pendingNotificationSettingsIntent(final Context context) {
1977        final Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
1978        intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
1979        intent.putExtra(Settings.EXTRA_CHANNEL_ID, "foreground");
1980        return PendingIntent.getActivity(
1981                context,
1982                89,
1983                intent,
1984                s()
1985                        ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1986                        : PendingIntent.FLAG_UPDATE_CURRENT);
1987    }
1988
1989    private PendingIntent createOpenConversationsIntent() {
1990        try {
1991            return PendingIntent.getActivity(
1992                    mXmppConnectionService,
1993                    0,
1994                    new Intent(mXmppConnectionService, ConversationsActivity.class),
1995                    s()
1996                            ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1997                            : PendingIntent.FLAG_UPDATE_CURRENT);
1998        } catch (RuntimeException e) {
1999            return null;
2000        }
2001    }
2002
2003    void updateErrorNotification() {
2004        if (Config.SUPPRESS_ERROR_NOTIFICATION) {
2005            cancel(ERROR_NOTIFICATION_ID);
2006            return;
2007        }
2008        final boolean showAllErrors = QuickConversationsService.isConversations();
2009        final List<Account> errors = new ArrayList<>();
2010        boolean torNotAvailable = false;
2011        for (final Account account : mXmppConnectionService.getAccounts()) {
2012            if (account.hasErrorStatus()
2013                    && account.showErrorNotification()
2014                    && (showAllErrors
2015                            || account.getLastErrorStatus() == Account.State.UNAUTHORIZED)) {
2016                errors.add(account);
2017                torNotAvailable |= account.getStatus() == Account.State.TOR_NOT_AVAILABLE;
2018            }
2019        }
2020        if (mXmppConnectionService.foregroundNotificationNeedsUpdatingWhenErrorStateChanges()) {
2021            try {
2022                notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
2023            } catch (final RuntimeException e) {
2024                Log.d(
2025                        Config.LOGTAG,
2026                        "not refreshing foreground service notification because service has died",
2027                        e);
2028            }
2029        }
2030        final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
2031        if (errors.isEmpty()) {
2032            cancel(ERROR_NOTIFICATION_ID);
2033            return;
2034        } else if (errors.size() == 1) {
2035            mBuilder.setContentTitle(
2036                    mXmppConnectionService.getString(R.string.problem_connecting_to_account));
2037            mBuilder.setContentText(errors.get(0).getJid().asBareJid().toEscapedString());
2038        } else {
2039            mBuilder.setContentTitle(
2040                    mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
2041            mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
2042        }
2043        try {
2044            mBuilder.addAction(
2045                    R.drawable.ic_autorenew_24dp,
2046                    mXmppConnectionService.getString(R.string.try_again),
2047                    pendingServiceIntent(
2048                            mXmppConnectionService, XmppConnectionService.ACTION_TRY_AGAIN, 45));
2049            mBuilder.setDeleteIntent(
2050                    pendingServiceIntent(
2051                            mXmppConnectionService,
2052                            XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS,
2053                            69));
2054        } catch (final RuntimeException e) {
2055            Log.d(
2056                    Config.LOGTAG,
2057                    "not including some actions in error notification because service has died",
2058                    e);
2059        }
2060        if (torNotAvailable) {
2061            if (TorServiceUtils.isOrbotInstalled(mXmppConnectionService)) {
2062                mBuilder.addAction(
2063                        R.drawable.ic_play_circle_24dp,
2064                        mXmppConnectionService.getString(R.string.start_orbot),
2065                        PendingIntent.getActivity(
2066                                mXmppConnectionService,
2067                                147,
2068                                TorServiceUtils.LAUNCH_INTENT,
2069                                s()
2070                                        ? PendingIntent.FLAG_IMMUTABLE
2071                                                | PendingIntent.FLAG_UPDATE_CURRENT
2072                                        : PendingIntent.FLAG_UPDATE_CURRENT));
2073            } else {
2074                mBuilder.addAction(
2075                        R.drawable.ic_download_24dp,
2076                        mXmppConnectionService.getString(R.string.install_orbot),
2077                        PendingIntent.getActivity(
2078                                mXmppConnectionService,
2079                                146,
2080                                TorServiceUtils.INSTALL_INTENT,
2081                                s()
2082                                        ? PendingIntent.FLAG_IMMUTABLE
2083                                                | PendingIntent.FLAG_UPDATE_CURRENT
2084                                        : PendingIntent.FLAG_UPDATE_CURRENT));
2085            }
2086        }
2087        mBuilder.setVisibility(Notification.VISIBILITY_PRIVATE);
2088        mBuilder.setSmallIcon(R.drawable.ic_warning_24dp);
2089        mBuilder.setLocalOnly(true);
2090        mBuilder.setPriority(Notification.PRIORITY_LOW);
2091        final Intent intent;
2092        if (AccountUtils.MANAGE_ACCOUNT_ACTIVITY != null) {
2093            intent = new Intent(mXmppConnectionService, AccountUtils.MANAGE_ACCOUNT_ACTIVITY);
2094        } else {
2095            intent = new Intent(mXmppConnectionService, EditAccountActivity.class);
2096            intent.putExtra("jid", errors.get(0).getJid().asBareJid().toEscapedString());
2097            intent.putExtra(EditAccountActivity.EXTRA_OPENED_FROM_NOTIFICATION, true);
2098        }
2099        mBuilder.setContentIntent(
2100                PendingIntent.getActivity(
2101                        mXmppConnectionService,
2102                        145,
2103                        intent,
2104                        s()
2105                                ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
2106                                : PendingIntent.FLAG_UPDATE_CURRENT));
2107        if (Compatibility.runsTwentySix()) {
2108            mBuilder.setChannelId("error");
2109        }
2110        notify(ERROR_NOTIFICATION_ID, mBuilder.build());
2111    }
2112
2113    void updateFileAddingNotification(final int current, final Message message) {
2114
2115        final Notification notification = videoTranscoding(current, message);
2116        notify(ONGOING_VIDEO_TRANSCODING_NOTIFICATION_ID, notification);
2117    }
2118
2119    private Notification videoTranscoding(final int current, @Nullable final Message message) {
2120        final Notification.Builder builder = new Notification.Builder(mXmppConnectionService);
2121        builder.setContentTitle(mXmppConnectionService.getString(R.string.transcoding_video));
2122        if (current >= 0) {
2123            builder.setProgress(100, current, false);
2124        } else {
2125            builder.setProgress(100, 0, true);
2126        }
2127        builder.setSmallIcon(R.drawable.ic_hourglass_top_24dp);
2128        if (message != null) {
2129            builder.setContentIntent(createContentIntent(message.getConversation()));
2130        }
2131        builder.setOngoing(true);
2132        if (Compatibility.runsTwentySix()) {
2133            builder.setChannelId("compression");
2134        }
2135        return builder.build();
2136    }
2137
2138    public Notification getIndeterminateVideoTranscoding() {
2139        return videoTranscoding(-1, null);
2140    }
2141
2142    private void notify(final String tag, final int id, final Notification notification) {
2143        if (ActivityCompat.checkSelfPermission(
2144                        mXmppConnectionService, Manifest.permission.POST_NOTIFICATIONS)
2145                != PackageManager.PERMISSION_GRANTED) {
2146            return;
2147        }
2148        final var notificationManager =
2149                mXmppConnectionService.getSystemService(NotificationManager.class);
2150        try {
2151            notificationManager.notify(tag, id, notification);
2152        } catch (final RuntimeException e) {
2153            Log.d(Config.LOGTAG, "unable to make notification", e);
2154        }
2155    }
2156
2157    public void notify(final int id, final Notification notification) {
2158        if (ActivityCompat.checkSelfPermission(
2159                        mXmppConnectionService, Manifest.permission.POST_NOTIFICATIONS)
2160                != PackageManager.PERMISSION_GRANTED) {
2161            return;
2162        }
2163        final var notificationManager =
2164                mXmppConnectionService.getSystemService(NotificationManager.class);
2165        try {
2166            notificationManager.notify(id, notification);
2167        } catch (final RuntimeException e) {
2168            Log.d(Config.LOGTAG, "unable to make notification", e);
2169        }
2170    }
2171
2172    public void cancel(final int id) {
2173        final NotificationManagerCompat notificationManager =
2174                NotificationManagerCompat.from(mXmppConnectionService);
2175        try {
2176            notificationManager.cancel(id);
2177        } catch (RuntimeException e) {
2178            Log.d(Config.LOGTAG, "unable to cancel notification", e);
2179        }
2180    }
2181
2182    private void cancel(String tag, int id) {
2183        final NotificationManagerCompat notificationManager =
2184                NotificationManagerCompat.from(mXmppConnectionService);
2185        try {
2186            notificationManager.cancel(tag, id);
2187        } catch (RuntimeException e) {
2188            Log.d(Config.LOGTAG, "unable to cancel notification", e);
2189        }
2190    }
2191
2192    private static class MissedCallsInfo {
2193        private int numberOfCalls;
2194        private long lastTime;
2195
2196        MissedCallsInfo(final long time) {
2197            numberOfCalls = 1;
2198            lastTime = time;
2199        }
2200
2201        public void newMissedCall(final long time) {
2202            ++numberOfCalls;
2203            lastTime = time;
2204        }
2205
2206        public boolean removeMissedCall() {
2207            --numberOfCalls;
2208            return numberOfCalls <= 0;
2209        }
2210
2211        public int getNumberOfCalls() {
2212            return numberOfCalls;
2213        }
2214
2215        public long getLastTime() {
2216            return lastTime;
2217        }
2218    }
2219}