NotificationService.java

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