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            final ShortcutInfoCompat info;
1377            if (conversation.getMode() == Conversation.MODE_SINGLE) {
1378                Contact contact = conversation.getContact();
1379                Uri systemAccount = contact.getSystemAccount();
1380                if (systemAccount != null) {
1381                    mBuilder.addPerson(systemAccount.toString());
1382                }
1383                info = mXmppConnectionService.getShortcutService().getShortcutInfoCompat(contact);
1384            } else {
1385                info =
1386                        mXmppConnectionService
1387                                .getShortcutService()
1388                                .getShortcutInfoCompat(conversation.getMucOptions());
1389            }
1390            mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
1391            mBuilder.setSmallIcon(R.drawable.ic_notification);
1392            mBuilder.setDeleteIntent(createDeleteIntent(conversation));
1393            mBuilder.setContentIntent(createContentIntent(conversation));
1394            if (mXmppConnectionService.getAccounts().size() > 1) {
1395                mBuilder.setSubText(conversation.getAccount().getJid().asBareJid().toString());
1396            }
1397
1398            mBuilder.setShortcutInfo(info);
1399            if (Build.VERSION.SDK_INT >= 30) {
1400                mXmppConnectionService.getSystemService(ShortcutManager.class).pushDynamicShortcut(info.toShortcutInfo());
1401                // mBuilder.setBubbleMetadata(new NotificationCompat.BubbleMetadata.Builder(info.getId()).build());
1402            }
1403        }
1404        return mBuilder;
1405    }
1406
1407    private void modifyForImage(
1408            final Builder builder, final Message message, final ArrayList<Message> messages) {
1409        try {
1410            final Bitmap bitmap = mXmppConnectionService.getFileBackend().getThumbnailBitmap(message, mXmppConnectionService.getResources(), getPixel(288));
1411            final ArrayList<Message> tmp = new ArrayList<>();
1412            for (final Message msg : messages) {
1413                if (msg.getType() == Message.TYPE_TEXT && msg.getTransferable() == null) {
1414                    tmp.add(msg);
1415                }
1416            }
1417            final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
1418            bigPictureStyle.bigPicture(bitmap);
1419            if (tmp.size() > 0) {
1420                CharSequence text = getMergedBodies(tmp);
1421                bigPictureStyle.setSummaryText(text);
1422                builder.setContentText(text);
1423                builder.setTicker(text);
1424            } else {
1425                final String description =
1426                        UIHelper.getFileDescriptionString(mXmppConnectionService, message);
1427                builder.setContentText(description);
1428                builder.setTicker(description);
1429            }
1430            builder.setStyle(bigPictureStyle);
1431        } catch (final IOException e) {
1432            modifyForTextOnly(builder, messages);
1433        }
1434    }
1435
1436    private Person getPerson(Message message) {
1437        final Contact contact = message.getContact();
1438        final Person.Builder builder = new Person.Builder();
1439        if (contact != null) {
1440            builder.setName(contact.getDisplayName());
1441            final Uri uri = contact.getSystemAccount();
1442            if (uri != null) {
1443                builder.setUri(uri.toString());
1444            }
1445        } else {
1446            builder.setName(UIHelper.getMessageDisplayName(message));
1447        }
1448        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
1449            final Jid jid = contact == null ? message.getCounterpart() : contact.getJid();
1450            builder.setKey(jid.toString());
1451            final Conversation c = mXmppConnectionService.find(message.getConversation().getAccount(), jid);
1452            if (c != null) {
1453                builder.setImportant(c.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false));
1454            }
1455            builder.setIcon(
1456                    IconCompat.createWithBitmap(FileBackend.drawDrawable(
1457                            mXmppConnectionService
1458                                    .getAvatarService()
1459                                    .get(
1460                                            message,
1461                                            AvatarService.getSystemUiAvatarSize(
1462                                                    mXmppConnectionService),
1463                                            false))));
1464        }
1465        return builder.build();
1466    }
1467
1468    private Person getPerson(Contact contact) {
1469        final Person.Builder builder = new Person.Builder();
1470        builder.setName(contact.getDisplayName());
1471        final Uri uri = contact.getSystemAccount();
1472        if (uri != null) {
1473            builder.setUri(uri.toString());
1474        }
1475        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
1476            final Jid jid = contact.getJid();
1477            builder.setKey(jid.toString());
1478            final Conversation c = mXmppConnectionService.find(contact.getAccount(), jid);
1479            if (c != null) {
1480                builder.setImportant(c.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false));
1481            }
1482            builder.setIcon(
1483                    IconCompat.createWithBitmap(FileBackend.drawDrawable(
1484                            mXmppConnectionService
1485                                    .getAvatarService()
1486                                    .get(
1487                                            contact,
1488                                            AvatarService.getSystemUiAvatarSize(
1489                                                    mXmppConnectionService),
1490                                            false))));
1491        }
1492        return builder.build();
1493    }
1494
1495    private void modifyForTextOnly(final Builder builder, final ArrayList<Message> messages) {
1496        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1497            final Conversation conversation = (Conversation) messages.get(0).getConversation();
1498            final Person.Builder meBuilder =
1499                    new Person.Builder().setName(mXmppConnectionService.getString(R.string.me));
1500            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
1501                meBuilder.setIcon(
1502                        IconCompat.createWithBitmap(FileBackend.drawDrawable(
1503                                mXmppConnectionService
1504                                        .getAvatarService()
1505                                        .get(
1506                                                conversation.getAccount(),
1507                                                AvatarService.getSystemUiAvatarSize(
1508                                                        mXmppConnectionService)))));
1509            }
1510            final Person me = meBuilder.build();
1511            NotificationCompat.MessagingStyle messagingStyle =
1512                    new NotificationCompat.MessagingStyle(me);
1513            final boolean multiple = conversation.getMode() == Conversation.MODE_MULTI || messages.get(0).getTrueCounterpart() != null;
1514            if (multiple) {
1515                messagingStyle.setConversationTitle(conversation.getName());
1516            }
1517            for (Message message : messages) {
1518                final Person sender =
1519                        message.getStatus() == Message.STATUS_RECEIVED ? getPerson(message) : null;
1520                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && isImageMessage(message)) {
1521                    final Uri dataUri =
1522                            FileBackend.getMediaUri(
1523                                    mXmppConnectionService,
1524                                    mXmppConnectionService.getFileBackend().getFile(message));
1525                    NotificationCompat.MessagingStyle.Message imageMessage =
1526                            new NotificationCompat.MessagingStyle.Message(
1527                                    UIHelper.getMessagePreview(mXmppConnectionService, message)
1528                                            .first,
1529                                    message.getTimeSent(),
1530                                    sender);
1531                    if (dataUri != null) {
1532                        imageMessage.setData(message.getMimeType(), dataUri);
1533                    }
1534                    messagingStyle.addMessage(imageMessage);
1535                } else {
1536                    messagingStyle.addMessage(
1537                            UIHelper.getMessagePreview(mXmppConnectionService, message).first,
1538                            message.getTimeSent(),
1539                            sender);
1540                }
1541            }
1542            messagingStyle.setGroupConversation(multiple);
1543            builder.setStyle(messagingStyle);
1544        } else {
1545            if (messages.get(0).getConversation().getMode() == Conversation.MODE_SINGLE && messages.get(0).getTrueCounterpart() == null) {
1546                builder.setStyle(
1547                        new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
1548                final CharSequence preview =
1549                        UIHelper.getMessagePreview(
1550                                        mXmppConnectionService, messages.get(messages.size() - 1))
1551                                .first;
1552                builder.setContentText(preview);
1553                builder.setTicker(preview);
1554                builder.setNumber(messages.size());
1555            } else {
1556                final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
1557                SpannableString styledString;
1558                for (Message message : messages) {
1559                    final String name = UIHelper.getMessageDisplayName(message);
1560                    styledString = new SpannableString(name + ": " + message.getBody());
1561                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
1562                    style.addLine(styledString);
1563                }
1564                builder.setStyle(style);
1565                int count = messages.size();
1566                if (count == 1) {
1567                    final String name = UIHelper.getMessageDisplayName(messages.get(0));
1568                    styledString = new SpannableString(name + ": " + messages.get(0).getBody());
1569                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
1570                    builder.setContentText(styledString);
1571                    builder.setTicker(styledString);
1572                } else {
1573                    final String text =
1574                            mXmppConnectionService
1575                                    .getResources()
1576                                    .getQuantityString(R.plurals.x_messages, count, count);
1577                    builder.setContentText(text);
1578                    builder.setTicker(text);
1579                }
1580            }
1581        }
1582    }
1583
1584    private Message getImage(final Iterable<Message> messages) {
1585        Message image = null;
1586        for (final Message message : messages) {
1587            if (message.getStatus() != Message.STATUS_RECEIVED) {
1588                return null;
1589            }
1590            if (isImageMessage(message)) {
1591                image = message;
1592            }
1593        }
1594        return image;
1595    }
1596
1597    private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
1598        for (final Message message : messages) {
1599            if (message.getTransferable() != null
1600                    || (message.getType() == Message.TYPE_TEXT && message.treatAsDownloadable())) {
1601                return message;
1602            }
1603        }
1604        return null;
1605    }
1606
1607    private Message getFirstLocationMessage(final Iterable<Message> messages) {
1608        for (final Message message : messages) {
1609            if (message.isGeoUri()) {
1610                return message;
1611            }
1612        }
1613        return null;
1614    }
1615
1616    private CharSequence getMergedBodies(final ArrayList<Message> messages) {
1617        final StringBuilder text = new StringBuilder();
1618        for (Message message : messages) {
1619            if (text.length() != 0) {
1620                text.append("\n");
1621            }
1622            text.append(UIHelper.getMessagePreview(mXmppConnectionService, message).first);
1623        }
1624        return text.toString();
1625    }
1626
1627    private PendingIntent createShowLocationIntent(final Message message) {
1628        Iterable<Intent> intents =
1629                GeoHelper.createGeoIntentsFromMessage(mXmppConnectionService, message);
1630        for (final Intent intent : intents) {
1631            if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
1632                return PendingIntent.getActivity(
1633                        mXmppConnectionService,
1634                        generateRequestCode(message.getConversation(), 18),
1635                        intent,
1636                        s()
1637                                ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1638                                : PendingIntent.FLAG_UPDATE_CURRENT);
1639            }
1640        }
1641        return null;
1642    }
1643
1644    private PendingIntent createContentIntent(
1645            final String conversationUuid, final String downloadMessageUuid) {
1646        final Intent viewConversationIntent =
1647                new Intent(mXmppConnectionService, ConversationsActivity.class);
1648        viewConversationIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
1649        viewConversationIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversationUuid);
1650        if (downloadMessageUuid != null) {
1651            viewConversationIntent.putExtra(
1652                    ConversationsActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
1653            return PendingIntent.getActivity(
1654                    mXmppConnectionService,
1655                    generateRequestCode(conversationUuid, 8),
1656                    viewConversationIntent,
1657                    s()
1658                            ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1659                            : PendingIntent.FLAG_UPDATE_CURRENT);
1660        } else {
1661            return PendingIntent.getActivity(
1662                    mXmppConnectionService,
1663                    generateRequestCode(conversationUuid, 10),
1664                    viewConversationIntent,
1665                    s()
1666                            ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1667                            : PendingIntent.FLAG_UPDATE_CURRENT);
1668        }
1669    }
1670
1671    private int generateRequestCode(String uuid, int actionId) {
1672        return (actionId * NOTIFICATION_ID_MULTIPLIER)
1673                + (uuid.hashCode() % NOTIFICATION_ID_MULTIPLIER);
1674    }
1675
1676    private int generateRequestCode(Conversational conversation, int actionId) {
1677        return generateRequestCode(conversation.getUuid(), actionId);
1678    }
1679
1680    private PendingIntent createDownloadIntent(final Message message) {
1681        return createContentIntent(message.getConversationUuid(), message.getUuid());
1682    }
1683
1684    private PendingIntent createContentIntent(final Conversational conversation) {
1685        return createContentIntent(conversation.getUuid(), null);
1686    }
1687
1688    private PendingIntent createDeleteIntent(final Conversation conversation) {
1689        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1690        intent.setAction(XmppConnectionService.ACTION_CLEAR_MESSAGE_NOTIFICATION);
1691        if (conversation != null) {
1692            intent.putExtra("uuid", conversation.getUuid());
1693            return PendingIntent.getService(
1694                    mXmppConnectionService,
1695                    generateRequestCode(conversation, 20),
1696                    intent,
1697                    s()
1698                            ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1699                            : PendingIntent.FLAG_UPDATE_CURRENT);
1700        }
1701        return PendingIntent.getService(
1702                mXmppConnectionService,
1703                0,
1704                intent,
1705                s()
1706                        ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1707                        : PendingIntent.FLAG_UPDATE_CURRENT);
1708    }
1709
1710    private PendingIntent createMissedCallsDeleteIntent(final Conversational conversation) {
1711        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1712        intent.setAction(XmppConnectionService.ACTION_CLEAR_MISSED_CALL_NOTIFICATION);
1713        if (conversation != null) {
1714            intent.putExtra("uuid", conversation.getUuid());
1715            return PendingIntent.getService(
1716                    mXmppConnectionService,
1717                    generateRequestCode(conversation, 21),
1718                    intent,
1719                    s()
1720                            ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1721                            : PendingIntent.FLAG_UPDATE_CURRENT);
1722        }
1723        return PendingIntent.getService(
1724                mXmppConnectionService,
1725                1,
1726                intent,
1727                s()
1728                        ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1729                        : PendingIntent.FLAG_UPDATE_CURRENT);
1730    }
1731
1732    private PendingIntent createReplyIntent(
1733            final Conversation conversation,
1734            final String lastMessageUuid,
1735            final boolean dismissAfterReply) {
1736        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1737        intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
1738        intent.putExtra("uuid", conversation.getUuid());
1739        intent.putExtra("dismiss_notification", dismissAfterReply);
1740        intent.putExtra("last_message_uuid", lastMessageUuid);
1741        final int id = generateRequestCode(conversation, dismissAfterReply ? 12 : 14);
1742        return PendingIntent.getService(
1743                mXmppConnectionService,
1744                id,
1745                intent,
1746                s()
1747                        ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1748                        : PendingIntent.FLAG_UPDATE_CURRENT);
1749    }
1750
1751    private PendingIntent createReadPendingIntent(Conversation conversation) {
1752        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1753        intent.setAction(XmppConnectionService.ACTION_MARK_AS_READ);
1754        intent.putExtra("uuid", conversation.getUuid());
1755        intent.setPackage(mXmppConnectionService.getPackageName());
1756        return PendingIntent.getService(
1757                mXmppConnectionService,
1758                generateRequestCode(conversation, 16),
1759                intent,
1760                s()
1761                        ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1762                        : PendingIntent.FLAG_UPDATE_CURRENT);
1763    }
1764
1765    private PendingIntent createCallAction(String sessionId, final String action, int requestCode) {
1766        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1767        intent.setAction(action);
1768        intent.setPackage(mXmppConnectionService.getPackageName());
1769        intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, sessionId);
1770        return PendingIntent.getService(
1771                mXmppConnectionService,
1772                requestCode,
1773                intent,
1774                s()
1775                        ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1776                        : PendingIntent.FLAG_UPDATE_CURRENT);
1777    }
1778
1779    private PendingIntent createSnoozeIntent(Conversation conversation) {
1780        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1781        intent.setAction(XmppConnectionService.ACTION_SNOOZE);
1782        intent.putExtra("uuid", conversation.getUuid());
1783        intent.setPackage(mXmppConnectionService.getPackageName());
1784        return PendingIntent.getService(
1785                mXmppConnectionService,
1786                generateRequestCode(conversation, 22),
1787                intent,
1788                s()
1789                        ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1790                        : PendingIntent.FLAG_UPDATE_CURRENT);
1791    }
1792
1793    private PendingIntent createTryAgainIntent() {
1794        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1795        intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
1796        return PendingIntent.getService(
1797                mXmppConnectionService,
1798                45,
1799                intent,
1800                s()
1801                        ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1802                        : PendingIntent.FLAG_UPDATE_CURRENT);
1803    }
1804
1805    private PendingIntent createDismissErrorIntent() {
1806        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1807        intent.setAction(XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS);
1808        return PendingIntent.getService(
1809                mXmppConnectionService,
1810                69,
1811                intent,
1812                s()
1813                        ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1814                        : PendingIntent.FLAG_UPDATE_CURRENT);
1815    }
1816
1817    private boolean wasHighlightedOrPrivate(final Message message) {
1818        if (message.getConversation() instanceof Conversation) {
1819            Conversation conversation = (Conversation) message.getConversation();
1820            final MucOptions.User sender = conversation.getMucOptions().findUserByFullJid(message.getCounterpart());
1821            if (sender != null && sender.getAffiliation().ranks(MucOptions.Affiliation.MEMBER) && message.isAttention()) {
1822                return true;
1823            }
1824
1825            final String nick = conversation.getMucOptions().getActualNick();
1826            final Pattern highlight = generateNickHighlightPattern(nick);
1827            final String name = conversation.getMucOptions().getActualName();
1828            final Pattern highlightName = generateNickHighlightPattern(name);
1829            if (message.getBody() == null || (nick == null && name == null)) {
1830                return false;
1831            }
1832            final Matcher m = highlight.matcher(message.getBody());
1833            final Matcher m2 = highlightName.matcher(message.getBody());
1834            return (m.find() || m2.find() || message.isPrivateMessage());
1835        } else {
1836            return false;
1837        }
1838    }
1839
1840    private boolean wasReplyToMe(final Message message) {
1841       final Element reply = message.getReply();
1842       if (reply == null || reply.getAttribute("id") == null) return false;
1843       final Message parent = ((Conversation) message.getConversation()).findMessageWithRemoteIdAndCounterpart(reply.getAttribute("id"), null);
1844       if (parent == null) return false;
1845       return parent.getStatus() >= Message.STATUS_SEND;
1846    }
1847
1848    public void setOpenConversation(final Conversation conversation) {
1849        this.mOpenConversation = conversation;
1850    }
1851
1852    public void setIsInForeground(final boolean foreground) {
1853        this.mIsInForeground = foreground;
1854    }
1855
1856    private int getPixel(final int dp) {
1857        final DisplayMetrics metrics = mXmppConnectionService.getResources().getDisplayMetrics();
1858        return ((int) (dp * metrics.density));
1859    }
1860
1861    private void markLastNotification() {
1862        this.mLastNotification = SystemClock.elapsedRealtime();
1863    }
1864
1865    private boolean inMiniGracePeriod(final Account account) {
1866        final int miniGrace =
1867                account.getStatus() == Account.State.ONLINE
1868                        ? Config.MINI_GRACE_PERIOD
1869                        : Config.MINI_GRACE_PERIOD * 2;
1870        return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
1871    }
1872
1873    Notification createForegroundNotification() {
1874        final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1875        mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.app_name));
1876        final List<Account> accounts = mXmppConnectionService.getAccounts();
1877        int enabled = 0;
1878        int connected = 0;
1879        if (accounts != null) {
1880            for (Account account : accounts) {
1881                if (account.isOnlineAndConnected()) {
1882                    connected++;
1883                    enabled++;
1884                } else if (account.isEnabled()) {
1885                    enabled++;
1886                }
1887            }
1888        }
1889        mBuilder.setContentText(
1890                mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
1891        final PendingIntent openIntent = createOpenConversationsIntent();
1892        if (openIntent != null) {
1893            mBuilder.setContentIntent(openIntent);
1894        }
1895        mBuilder.setWhen(0)
1896                .setPriority(Notification.PRIORITY_MIN)
1897                .setSmallIcon(
1898                        connected > 0
1899                                ? R.drawable.ic_link_white_24dp
1900                                : R.drawable.ic_link_off_white_24dp)
1901                .setLocalOnly(true);
1902
1903        if (Compatibility.runsTwentySix()) {
1904            mBuilder.setChannelId("foreground");
1905        }
1906
1907        return mBuilder.build();
1908    }
1909
1910    private PendingIntent createOpenConversationsIntent() {
1911        try {
1912            return PendingIntent.getActivity(
1913                    mXmppConnectionService,
1914                    0,
1915                    new Intent(mXmppConnectionService, ConversationsActivity.class),
1916                    s()
1917                            ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1918                            : PendingIntent.FLAG_UPDATE_CURRENT);
1919        } catch (RuntimeException e) {
1920            return null;
1921        }
1922    }
1923
1924    void updateErrorNotification() {
1925        if (Config.SUPPRESS_ERROR_NOTIFICATION) {
1926            cancel(ERROR_NOTIFICATION_ID);
1927            return;
1928        }
1929        final boolean showAllErrors = QuickConversationsService.isConversations();
1930        final List<Account> errors = new ArrayList<>();
1931        boolean torNotAvailable = false;
1932        for (final Account account : mXmppConnectionService.getAccounts()) {
1933            if (account.hasErrorStatus()
1934                    && account.showErrorNotification()
1935                    && (showAllErrors
1936                            || account.getLastErrorStatus() == Account.State.UNAUTHORIZED)) {
1937                errors.add(account);
1938                torNotAvailable |= account.getStatus() == Account.State.TOR_NOT_AVAILABLE;
1939            }
1940        }
1941        if (mXmppConnectionService.foregroundNotificationNeedsUpdatingWhenErrorStateChanges()) {
1942            notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
1943        }
1944        final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1945        if (errors.size() == 0) {
1946            cancel(ERROR_NOTIFICATION_ID);
1947            return;
1948        } else if (errors.size() == 1) {
1949            mBuilder.setContentTitle(
1950                    mXmppConnectionService.getString(R.string.problem_connecting_to_account));
1951            mBuilder.setContentText(errors.get(0).getJid().asBareJid().toEscapedString());
1952        } else {
1953            mBuilder.setContentTitle(
1954                    mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
1955            mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
1956        }
1957        mBuilder.addAction(
1958                R.drawable.ic_autorenew_white_24dp,
1959                mXmppConnectionService.getString(R.string.try_again),
1960                createTryAgainIntent());
1961        if (torNotAvailable) {
1962            if (TorServiceUtils.isOrbotInstalled(mXmppConnectionService)) {
1963                mBuilder.addAction(
1964                        R.drawable.ic_play_circle_filled_white_48dp,
1965                        mXmppConnectionService.getString(R.string.start_orbot),
1966                        PendingIntent.getActivity(
1967                                mXmppConnectionService,
1968                                147,
1969                                TorServiceUtils.LAUNCH_INTENT,
1970                                s()
1971                                        ? PendingIntent.FLAG_IMMUTABLE
1972                                                | PendingIntent.FLAG_UPDATE_CURRENT
1973                                        : PendingIntent.FLAG_UPDATE_CURRENT));
1974            } else {
1975                mBuilder.addAction(
1976                        R.drawable.ic_file_download_white_24dp,
1977                        mXmppConnectionService.getString(R.string.install_orbot),
1978                        PendingIntent.getActivity(
1979                                mXmppConnectionService,
1980                                146,
1981                                TorServiceUtils.INSTALL_INTENT,
1982                                s()
1983                                        ? PendingIntent.FLAG_IMMUTABLE
1984                                                | PendingIntent.FLAG_UPDATE_CURRENT
1985                                        : PendingIntent.FLAG_UPDATE_CURRENT));
1986            }
1987        }
1988        mBuilder.setDeleteIntent(createDismissErrorIntent());
1989        mBuilder.setVisibility(Notification.VISIBILITY_PRIVATE);
1990        mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
1991        mBuilder.setLocalOnly(true);
1992        mBuilder.setPriority(Notification.PRIORITY_LOW);
1993        final Intent intent;
1994        if (AccountUtils.MANAGE_ACCOUNT_ACTIVITY != null) {
1995            intent = new Intent(mXmppConnectionService, AccountUtils.MANAGE_ACCOUNT_ACTIVITY);
1996        } else {
1997            intent = new Intent(mXmppConnectionService, EditAccountActivity.class);
1998            intent.putExtra("jid", errors.get(0).getJid().asBareJid().toEscapedString());
1999            intent.putExtra(EditAccountActivity.EXTRA_OPENED_FROM_NOTIFICATION, true);
2000        }
2001        mBuilder.setContentIntent(
2002                PendingIntent.getActivity(
2003                        mXmppConnectionService,
2004                        145,
2005                        intent,
2006                        s()
2007                                ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
2008                                : PendingIntent.FLAG_UPDATE_CURRENT));
2009        if (Compatibility.runsTwentySix()) {
2010            mBuilder.setChannelId("error");
2011        }
2012        notify(ERROR_NOTIFICATION_ID, mBuilder.build());
2013    }
2014
2015    void updateFileAddingNotification(int current, Message message) {
2016        Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
2017        mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.transcoding_video));
2018        mBuilder.setProgress(100, current, false);
2019        mBuilder.setSmallIcon(R.drawable.ic_hourglass_empty_white_24dp);
2020        mBuilder.setContentIntent(createContentIntent(message.getConversation()));
2021        mBuilder.setOngoing(true);
2022        if (Compatibility.runsTwentySix()) {
2023            mBuilder.setChannelId("compression");
2024        }
2025        Notification notification = mBuilder.build();
2026        notify(FOREGROUND_NOTIFICATION_ID, notification);
2027    }
2028
2029    private void notify(String tag, int id, Notification notification) {
2030        final NotificationManagerCompat notificationManager =
2031                NotificationManagerCompat.from(mXmppConnectionService);
2032        try {
2033            notificationManager.notify(tag, id, notification);
2034        } catch (RuntimeException e) {
2035            Log.d(Config.LOGTAG, "unable to make notification", e);
2036        }
2037    }
2038
2039    public void notify(int id, Notification notification) {
2040        final NotificationManagerCompat notificationManager =
2041                NotificationManagerCompat.from(mXmppConnectionService);
2042        try {
2043            notificationManager.notify(id, notification);
2044        } catch (RuntimeException e) {
2045            Log.d(Config.LOGTAG, "unable to make notification", e);
2046        }
2047    }
2048
2049    public void cancel(int id) {
2050        final NotificationManagerCompat notificationManager =
2051                NotificationManagerCompat.from(mXmppConnectionService);
2052        try {
2053            notificationManager.cancel(id);
2054        } catch (RuntimeException e) {
2055            Log.d(Config.LOGTAG, "unable to cancel notification", e);
2056        }
2057    }
2058
2059    private void cancel(String tag, int id) {
2060        final NotificationManagerCompat notificationManager =
2061                NotificationManagerCompat.from(mXmppConnectionService);
2062        try {
2063            notificationManager.cancel(tag, id);
2064        } catch (RuntimeException e) {
2065            Log.d(Config.LOGTAG, "unable to cancel notification", e);
2066        }
2067    }
2068
2069    private static class MissedCallsInfo {
2070        private int numberOfCalls;
2071        private long lastTime;
2072
2073        MissedCallsInfo(final long time) {
2074            numberOfCalls = 1;
2075            lastTime = time;
2076        }
2077
2078        public void newMissedCall(final long time) {
2079            ++numberOfCalls;
2080            lastTime = time;
2081        }
2082
2083        public int getNumberOfCalls() {
2084            return numberOfCalls;
2085        }
2086
2087        public long getLastTime() {
2088            return lastTime;
2089        }
2090    }
2091
2092    private class VibrationRunnable implements Runnable {
2093
2094        @Override
2095        public void run() {
2096            final Vibrator vibrator =
2097                    (Vibrator) mXmppConnectionService.getSystemService(Context.VIBRATOR_SERVICE);
2098            vibrator.vibrate(CALL_PATTERN, -1);
2099			}
2100		}
2101}