NotificationService.java

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