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