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