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