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