NotificationService.java

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