NotificationService.java

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