NotificationService.java

   1package eu.siacs.conversations.services;
   2
   3import android.app.Notification;
   4import android.app.NotificationChannel;
   5import android.app.NotificationChannelGroup;
   6import android.app.NotificationManager;
   7import android.app.PendingIntent;
   8import android.content.Context;
   9import android.content.Intent;
  10import android.content.SharedPreferences;
  11import android.content.res.Resources;
  12import android.graphics.Bitmap;
  13import android.graphics.Typeface;
  14import android.media.AudioAttributes;
  15import android.media.RingtoneManager;
  16import android.net.Uri;
  17import android.os.Build;
  18import android.os.SystemClock;
  19import android.preference.PreferenceManager;
  20import androidx.annotation.RequiresApi;
  21import androidx.core.app.NotificationCompat;
  22import androidx.core.app.NotificationCompat.BigPictureStyle;
  23import androidx.core.app.NotificationCompat.Builder;
  24import androidx.core.app.NotificationManagerCompat;
  25import androidx.core.app.Person;
  26import androidx.core.app.RemoteInput;
  27import androidx.core.content.ContextCompat;
  28import androidx.core.graphics.drawable.IconCompat;
  29import android.text.SpannableString;
  30import android.text.style.StyleSpan;
  31import android.util.DisplayMetrics;
  32import android.util.Log;
  33
  34import java.io.File;
  35import java.io.IOException;
  36import java.util.ArrayList;
  37import java.util.Calendar;
  38import java.util.Collections;
  39import java.util.HashMap;
  40import java.util.Iterator;
  41import java.util.LinkedHashMap;
  42import java.util.List;
  43import java.util.Map;
  44import java.util.Set;
  45import java.util.concurrent.atomic.AtomicInteger;
  46import java.util.regex.Matcher;
  47import java.util.regex.Pattern;
  48
  49import eu.siacs.conversations.Config;
  50import eu.siacs.conversations.R;
  51import eu.siacs.conversations.entities.Account;
  52import eu.siacs.conversations.entities.Contact;
  53import eu.siacs.conversations.entities.Conversation;
  54import eu.siacs.conversations.entities.Conversational;
  55import eu.siacs.conversations.entities.Message;
  56import eu.siacs.conversations.persistance.FileBackend;
  57import eu.siacs.conversations.ui.ConversationsActivity;
  58import eu.siacs.conversations.ui.EditAccountActivity;
  59import eu.siacs.conversations.ui.RtpSessionActivity;
  60import eu.siacs.conversations.ui.TimePreference;
  61import eu.siacs.conversations.utils.AccountUtils;
  62import eu.siacs.conversations.utils.Compatibility;
  63import eu.siacs.conversations.utils.GeoHelper;
  64import eu.siacs.conversations.utils.TorServiceUtils;
  65import eu.siacs.conversations.utils.UIHelper;
  66import eu.siacs.conversations.xmpp.XmppConnection;
  67import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
  68import eu.siacs.conversations.xmpp.jingle.Media;
  69
  70public class NotificationService {
  71
  72    public static final Object CATCHUP_LOCK = new Object();
  73
  74    private static final int LED_COLOR = 0xff00ff00;
  75
  76    private static final int CALL_DAT = 120;
  77    private static final long[] CALL_PATTERN = {0, 3 * CALL_DAT, CALL_DAT, CALL_DAT, 3 * CALL_DAT, CALL_DAT, CALL_DAT};
  78
  79    private static final String CONVERSATIONS_GROUP = "eu.siacs.conversations";
  80    private static final int NOTIFICATION_ID_MULTIPLIER = 1024 * 1024;
  81    static final int FOREGROUND_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 4;
  82    private static final int NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 2;
  83    private static final int ERROR_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 6;
  84    private static final int INCOMING_CALL_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 8;
  85    public static final int ONGOING_CALL_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 10;
  86    private static final int DELIVERY_FAILED_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 12;
  87    private final XmppConnectionService mXmppConnectionService;
  88    private final LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<>();
  89    private final HashMap<Conversation, AtomicInteger> mBacklogMessageCounter = new HashMap<>();
  90    private Conversation mOpenConversation;
  91    private boolean mIsInForeground;
  92    private long mLastNotification;
  93
  94    NotificationService(final XmppConnectionService service) {
  95        this.mXmppConnectionService = service;
  96    }
  97
  98    private static boolean displaySnoozeAction(List<Message> messages) {
  99        int numberOfMessagesWithoutReply = 0;
 100        for (Message message : messages) {
 101            if (message.getStatus() == Message.STATUS_RECEIVED) {
 102                ++numberOfMessagesWithoutReply;
 103            } else {
 104                return false;
 105            }
 106        }
 107        return numberOfMessagesWithoutReply >= 3;
 108    }
 109
 110    public static Pattern generateNickHighlightPattern(final String nick) {
 111        return Pattern.compile("(?<=(^|\\s))" + Pattern.quote(nick) + "(?=\\s|$|\\p{Punct})");
 112    }
 113
 114    private static boolean isImageMessage(Message message) {
 115        return message.getType() != Message.TYPE_TEXT
 116                && message.getTransferable() == null
 117                && !message.isDeleted()
 118                && message.getEncryption() != Message.ENCRYPTION_PGP
 119                && message.getFileParams().height > 0;
 120    }
 121
 122    @RequiresApi(api = Build.VERSION_CODES.O)
 123    void initializeChannels() {
 124        final Context c = mXmppConnectionService;
 125        final NotificationManager notificationManager = c.getSystemService(NotificationManager.class);
 126        if (notificationManager == null) {
 127            return;
 128        }
 129
 130        notificationManager.deleteNotificationChannel("export");
 131
 132        notificationManager.createNotificationChannelGroup(new NotificationChannelGroup("status", c.getString(R.string.notification_group_status_information)));
 133        notificationManager.createNotificationChannelGroup(new NotificationChannelGroup("chats", c.getString(R.string.notification_group_messages)));
 134        notificationManager.createNotificationChannelGroup(new NotificationChannelGroup("calls", c.getString(R.string.notification_group_calls)));
 135        final NotificationChannel foregroundServiceChannel = new NotificationChannel("foreground",
 136                c.getString(R.string.foreground_service_channel_name),
 137                NotificationManager.IMPORTANCE_MIN);
 138        foregroundServiceChannel.setDescription(c.getString(R.string.foreground_service_channel_description));
 139        foregroundServiceChannel.setShowBadge(false);
 140        foregroundServiceChannel.setGroup("status");
 141        notificationManager.createNotificationChannel(foregroundServiceChannel);
 142        final NotificationChannel errorChannel = new NotificationChannel("error",
 143                c.getString(R.string.error_channel_name),
 144                NotificationManager.IMPORTANCE_LOW);
 145        errorChannel.setDescription(c.getString(R.string.error_channel_description));
 146        errorChannel.setShowBadge(false);
 147        errorChannel.setGroup("status");
 148        notificationManager.createNotificationChannel(errorChannel);
 149
 150        final NotificationChannel videoCompressionChannel = new NotificationChannel("compression",
 151                c.getString(R.string.video_compression_channel_name),
 152                NotificationManager.IMPORTANCE_LOW);
 153        videoCompressionChannel.setShowBadge(false);
 154        videoCompressionChannel.setGroup("status");
 155        notificationManager.createNotificationChannel(videoCompressionChannel);
 156
 157        final NotificationChannel exportChannel = new NotificationChannel("backup",
 158                c.getString(R.string.backup_channel_name),
 159                NotificationManager.IMPORTANCE_LOW);
 160        exportChannel.setShowBadge(false);
 161        exportChannel.setGroup("status");
 162        notificationManager.createNotificationChannel(exportChannel);
 163
 164        final NotificationChannel incomingCallsChannel = new NotificationChannel("incoming_calls",
 165                c.getString(R.string.incoming_calls_channel_name),
 166                NotificationManager.IMPORTANCE_HIGH);
 167        incomingCallsChannel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE), new AudioAttributes.Builder()
 168                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
 169                .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
 170                .build());
 171        incomingCallsChannel.setShowBadge(false);
 172        incomingCallsChannel.setLightColor(LED_COLOR);
 173        incomingCallsChannel.enableLights(true);
 174        incomingCallsChannel.setGroup("calls");
 175        incomingCallsChannel.setBypassDnd(true);
 176        incomingCallsChannel.enableVibration(true);
 177        incomingCallsChannel.setVibrationPattern(CALL_PATTERN);
 178        notificationManager.createNotificationChannel(incomingCallsChannel);
 179
 180        final NotificationChannel ongoingCallsChannel = new NotificationChannel("ongoing_calls",
 181                c.getString(R.string.ongoing_calls_channel_name),
 182                NotificationManager.IMPORTANCE_LOW);
 183        ongoingCallsChannel.setShowBadge(false);
 184        ongoingCallsChannel.setGroup("calls");
 185        notificationManager.createNotificationChannel(ongoingCallsChannel);
 186
 187
 188        final NotificationChannel messagesChannel = new NotificationChannel("messages",
 189                c.getString(R.string.messages_channel_name),
 190                NotificationManager.IMPORTANCE_HIGH);
 191        messagesChannel.setShowBadge(true);
 192        messagesChannel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), new AudioAttributes.Builder()
 193                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
 194                .setUsage(AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT)
 195                .build());
 196        messagesChannel.setLightColor(LED_COLOR);
 197        final int dat = 70;
 198        final long[] pattern = {0, 3 * dat, dat, dat};
 199        messagesChannel.setVibrationPattern(pattern);
 200        messagesChannel.enableVibration(true);
 201        messagesChannel.enableLights(true);
 202        messagesChannel.setGroup("chats");
 203        notificationManager.createNotificationChannel(messagesChannel);
 204        final NotificationChannel silentMessagesChannel = new NotificationChannel("silent_messages",
 205                c.getString(R.string.silent_messages_channel_name),
 206                NotificationManager.IMPORTANCE_LOW);
 207        silentMessagesChannel.setDescription(c.getString(R.string.silent_messages_channel_description));
 208        silentMessagesChannel.setShowBadge(true);
 209        silentMessagesChannel.setLightColor(LED_COLOR);
 210        silentMessagesChannel.enableLights(true);
 211        silentMessagesChannel.setGroup("chats");
 212        notificationManager.createNotificationChannel(silentMessagesChannel);
 213
 214        final NotificationChannel quietHoursChannel = new NotificationChannel("quiet_hours",
 215                c.getString(R.string.title_pref_quiet_hours),
 216                NotificationManager.IMPORTANCE_LOW);
 217        quietHoursChannel.setShowBadge(true);
 218        quietHoursChannel.setLightColor(LED_COLOR);
 219        quietHoursChannel.enableLights(true);
 220        quietHoursChannel.setGroup("chats");
 221        quietHoursChannel.enableVibration(false);
 222        quietHoursChannel.setSound(null, null);
 223
 224        notificationManager.createNotificationChannel(quietHoursChannel);
 225
 226        final NotificationChannel deliveryFailedChannel = new NotificationChannel("delivery_failed",
 227                c.getString(R.string.delivery_failed_channel_name),
 228                NotificationManager.IMPORTANCE_DEFAULT);
 229        deliveryFailedChannel.setShowBadge(false);
 230        deliveryFailedChannel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), new AudioAttributes.Builder()
 231                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
 232                .setUsage(AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT)
 233                .build());
 234        deliveryFailedChannel.setGroup("chats");
 235        notificationManager.createNotificationChannel(deliveryFailedChannel);
 236    }
 237
 238    private boolean notify(final Message message) {
 239        final Conversation conversation = (Conversation) message.getConversation();
 240        return message.getStatus() == Message.STATUS_RECEIVED
 241                && !conversation.isMuted()
 242                && (conversation.alwaysNotify() || wasHighlightedOrPrivate(message))
 243                && (!conversation.isWithStranger() || notificationsFromStrangers());
 244    }
 245
 246    public boolean notificationsFromStrangers() {
 247        return mXmppConnectionService.getBooleanPreference("notifications_from_strangers", R.bool.notifications_from_strangers);
 248    }
 249
 250    private boolean isQuietHours() {
 251        if (!mXmppConnectionService.getBooleanPreference("enable_quiet_hours", R.bool.enable_quiet_hours)) {
 252            return false;
 253        }
 254        final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
 255        final long startTime = TimePreference.minutesToTimestamp(preferences.getLong("quiet_hours_start", TimePreference.DEFAULT_VALUE));
 256        final long endTime = TimePreference.minutesToTimestamp(preferences.getLong("quiet_hours_end", TimePreference.DEFAULT_VALUE));
 257        final long nowTime = Calendar.getInstance().getTimeInMillis();
 258
 259        if (endTime < startTime) {
 260            return nowTime > startTime || nowTime < endTime;
 261        } else {
 262            return nowTime > startTime && nowTime < endTime;
 263        }
 264    }
 265
 266    public void pushFromBacklog(final Message message) {
 267        if (notify(message)) {
 268            synchronized (notifications) {
 269                getBacklogMessageCounter((Conversation) message.getConversation()).incrementAndGet();
 270                pushToStack(message);
 271            }
 272        }
 273    }
 274
 275    private AtomicInteger getBacklogMessageCounter(Conversation conversation) {
 276        synchronized (mBacklogMessageCounter) {
 277            if (!mBacklogMessageCounter.containsKey(conversation)) {
 278                mBacklogMessageCounter.put(conversation, new AtomicInteger(0));
 279            }
 280            return mBacklogMessageCounter.get(conversation);
 281        }
 282    }
 283
 284    void pushFromDirectReply(final Message message) {
 285        synchronized (notifications) {
 286            pushToStack(message);
 287            updateNotification(false);
 288        }
 289    }
 290
 291    public void finishBacklog(boolean notify, Account account) {
 292        synchronized (notifications) {
 293            mXmppConnectionService.updateUnreadCountBadge();
 294            if (account == null || !notify) {
 295                updateNotification(notify);
 296            } else {
 297                final int count;
 298                final List<String> conversations;
 299                synchronized (this.mBacklogMessageCounter) {
 300                    conversations = getBacklogConversations(account);
 301                    count = getBacklogMessageCount(account);
 302                }
 303                updateNotification(count > 0, conversations);
 304            }
 305        }
 306    }
 307
 308    private List<String> getBacklogConversations(Account account) {
 309        final List<String> conversations = new ArrayList<>();
 310        for (Map.Entry<Conversation, AtomicInteger> entry : mBacklogMessageCounter.entrySet()) {
 311            if (entry.getKey().getAccount() == account) {
 312                conversations.add(entry.getKey().getUuid());
 313            }
 314        }
 315        return conversations;
 316    }
 317
 318    private int getBacklogMessageCount(Account account) {
 319        int count = 0;
 320        for (Iterator<Map.Entry<Conversation, AtomicInteger>> it = mBacklogMessageCounter.entrySet().iterator(); it.hasNext(); ) {
 321            Map.Entry<Conversation, AtomicInteger> entry = it.next();
 322            if (entry.getKey().getAccount() == account) {
 323                count += entry.getValue().get();
 324                it.remove();
 325            }
 326        }
 327        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": backlog message count=" + count);
 328        return count;
 329    }
 330
 331    void finishBacklog(boolean notify) {
 332        finishBacklog(notify, null);
 333    }
 334
 335    private void pushToStack(final Message message) {
 336        final String conversationUuid = message.getConversationUuid();
 337        if (notifications.containsKey(conversationUuid)) {
 338            notifications.get(conversationUuid).add(message);
 339        } else {
 340            final ArrayList<Message> mList = new ArrayList<>();
 341            mList.add(message);
 342            notifications.put(conversationUuid, mList);
 343        }
 344    }
 345
 346    public void push(final Message message) {
 347        synchronized (CATCHUP_LOCK) {
 348            final XmppConnection connection = message.getConversation().getAccount().getXmppConnection();
 349            if (connection != null && connection.isWaitingForSmCatchup()) {
 350                connection.incrementSmCatchupMessageCounter();
 351                pushFromBacklog(message);
 352            } else {
 353                pushNow(message);
 354            }
 355        }
 356    }
 357
 358    public void pushFailedDelivery(final Message message) {
 359        final Conversation conversation = (Conversation) message.getConversation();
 360        final boolean isScreenOn = mXmppConnectionService.isInteractive();
 361        if (this.mIsInForeground && isScreenOn && this.mOpenConversation == message.getConversation()) {
 362            Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing failed delivery notification because conversation is open");
 363            return;
 364        }
 365        final PendingIntent pendingIntent = createContentIntent(conversation);
 366        final int notificationId = generateRequestCode(conversation, 0) + DELIVERY_FAILED_NOTIFICATION_ID;
 367        final int failedDeliveries = conversation.countFailedDeliveries();
 368        final Notification notification =
 369                new Builder(mXmppConnectionService, "delivery_failed")
 370                        .setContentTitle(conversation.getName())
 371                        .setAutoCancel(true)
 372                        .setSmallIcon(R.drawable.ic_error_white_24dp)
 373                        .setContentText(mXmppConnectionService.getResources().getQuantityText(R.plurals.some_messages_could_not_be_delivered, failedDeliveries))
 374                        .setGroup("delivery_failed")
 375                        .setContentIntent(pendingIntent).build();
 376        final Notification summaryNotification =
 377                new Builder(mXmppConnectionService, "delivery_failed")
 378                        .setContentTitle(mXmppConnectionService.getString(R.string.failed_deliveries))
 379                        .setContentText(mXmppConnectionService.getResources().getQuantityText(R.plurals.some_messages_could_not_be_delivered, 1024))
 380                        .setSmallIcon(R.drawable.ic_error_white_24dp)
 381                        .setGroup("delivery_failed")
 382                        .setGroupSummary(true)
 383                        .setAutoCancel(true)
 384                        .build();
 385        notify(notificationId, notification);
 386        notify(DELIVERY_FAILED_NOTIFICATION_ID, summaryNotification);
 387    }
 388
 389    public void showIncomingCallNotification(final AbstractJingleConnection.Id id, final Set<Media> media) {
 390        final Intent fullScreenIntent = new Intent(mXmppConnectionService, RtpSessionActivity.class);
 391        fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, id.account.getJid().asBareJid().toEscapedString());
 392        fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_WITH, id.with.toEscapedString());
 393        fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.sessionId);
 394        fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 395        fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 396        final NotificationCompat.Builder builder = new NotificationCompat.Builder(mXmppConnectionService, "incoming_calls");
 397        if (media.contains(Media.VIDEO)) {
 398            builder.setSmallIcon(R.drawable.ic_videocam_white_24dp);
 399            builder.setContentTitle(mXmppConnectionService.getString(R.string.rtp_state_incoming_video_call));
 400        } else {
 401            builder.setSmallIcon(R.drawable.ic_call_white_24dp);
 402            builder.setContentTitle(mXmppConnectionService.getString(R.string.rtp_state_incoming_call));
 403        }
 404        final Contact contact = id.getContact();
 405        builder.setLargeIcon(mXmppConnectionService.getAvatarService().get(
 406                contact,
 407                AvatarService.getSystemUiAvatarSize(mXmppConnectionService))
 408        );
 409        final Uri systemAccount = contact.getSystemAccount();
 410        if (systemAccount != null) {
 411            builder.addPerson(systemAccount.toString());
 412        }
 413        builder.setContentText(id.account.getRoster().getContact(id.with).getDisplayName());
 414        builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
 415        builder.setPriority(NotificationCompat.PRIORITY_HIGH);
 416        builder.setCategory(NotificationCompat.CATEGORY_CALL);
 417        PendingIntent pendingIntent = createPendingRtpSession(id, Intent.ACTION_VIEW, 101);
 418        builder.setFullScreenIntent(pendingIntent, true);
 419        builder.setContentIntent(pendingIntent); //old androids need this?
 420        builder.setOngoing(true);
 421        builder.addAction(new NotificationCompat.Action.Builder(
 422                R.drawable.ic_call_end_white_48dp,
 423                mXmppConnectionService.getString(R.string.dismiss_call),
 424                createCallAction(id.sessionId, XmppConnectionService.ACTION_DISMISS_CALL, 102))
 425                .build());
 426        builder.addAction(new NotificationCompat.Action.Builder(
 427                R.drawable.ic_call_white_24dp,
 428                mXmppConnectionService.getString(R.string.answer_call),
 429                createPendingRtpSession(id, RtpSessionActivity.ACTION_ACCEPT_CALL, 103))
 430                .build());
 431        modifyIncomingCall(builder);
 432        final Notification notification = builder.build();
 433        notification.flags = notification.flags | Notification.FLAG_INSISTENT;
 434        notify(INCOMING_CALL_NOTIFICATION_ID, notification);
 435    }
 436
 437    public Notification getOngoingCallNotification(final AbstractJingleConnection.Id id, final Set<Media> media) {
 438        final NotificationCompat.Builder builder = new NotificationCompat.Builder(mXmppConnectionService, "ongoing_calls");
 439        if (media.contains(Media.VIDEO)) {
 440            builder.setSmallIcon(R.drawable.ic_videocam_white_24dp);
 441            builder.setContentTitle(mXmppConnectionService.getString(R.string.ongoing_video_call));
 442        } else {
 443            builder.setSmallIcon(R.drawable.ic_call_white_24dp);
 444            builder.setContentTitle(mXmppConnectionService.getString(R.string.ongoing_call));
 445        }
 446        builder.setContentText(id.account.getRoster().getContact(id.with).getDisplayName());
 447        builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
 448        builder.setPriority(NotificationCompat.PRIORITY_HIGH);
 449        builder.setCategory(NotificationCompat.CATEGORY_CALL);
 450        builder.setContentIntent(createPendingRtpSession(id, Intent.ACTION_VIEW, 101));
 451        builder.setOngoing(true);
 452        builder.addAction(new NotificationCompat.Action.Builder(
 453                R.drawable.ic_call_end_white_48dp,
 454                mXmppConnectionService.getString(R.string.hang_up),
 455                createCallAction(id.sessionId, XmppConnectionService.ACTION_END_CALL, 104))
 456                .build());
 457        return builder.build();
 458    }
 459
 460    private PendingIntent createPendingRtpSession(final AbstractJingleConnection.Id id, final String action, final int requestCode) {
 461        final Intent fullScreenIntent = new Intent(mXmppConnectionService, RtpSessionActivity.class);
 462        fullScreenIntent.setAction(action);
 463        fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, id.account.getJid().asBareJid().toEscapedString());
 464        fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_WITH, id.with.toEscapedString());
 465        fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.sessionId);
 466        return PendingIntent.getActivity(mXmppConnectionService, requestCode, fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);
 467    }
 468
 469    public void cancelIncomingCallNotification() {
 470        cancel(INCOMING_CALL_NOTIFICATION_ID);
 471    }
 472
 473    public static void cancelIncomingCallNotification(final Context context) {
 474        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
 475        try {
 476            notificationManager.cancel(INCOMING_CALL_NOTIFICATION_ID);
 477        } catch (RuntimeException e) {
 478            Log.d(Config.LOGTAG, "unable to cancel incoming call notification after crash", e);
 479        }
 480    }
 481
 482    private void pushNow(final Message message) {
 483        mXmppConnectionService.updateUnreadCountBadge();
 484        if (!notify(message)) {
 485            Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because turned off");
 486            return;
 487        }
 488        final boolean isScreenOn = mXmppConnectionService.isInteractive();
 489        if (this.mIsInForeground && isScreenOn && this.mOpenConversation == message.getConversation()) {
 490            Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because conversation is open");
 491            return;
 492        }
 493        synchronized (notifications) {
 494            pushToStack(message);
 495            final Conversational conversation = message.getConversation();
 496            final Account account = conversation.getAccount();
 497            final boolean doNotify = (!(this.mIsInForeground && this.mOpenConversation == null) || !isScreenOn)
 498                    && !account.inGracePeriod()
 499                    && !this.inMiniGracePeriod(account);
 500            updateNotification(doNotify, Collections.singletonList(conversation.getUuid()));
 501        }
 502    }
 503
 504    public void clear() {
 505        synchronized (notifications) {
 506            for (ArrayList<Message> messages : notifications.values()) {
 507                markAsReadIfHasDirectReply(messages);
 508            }
 509            notifications.clear();
 510            updateNotification(false);
 511        }
 512    }
 513
 514    public void clear(final Conversation conversation) {
 515        synchronized (this.mBacklogMessageCounter) {
 516            this.mBacklogMessageCounter.remove(conversation);
 517        }
 518        synchronized (notifications) {
 519            markAsReadIfHasDirectReply(conversation);
 520            if (notifications.remove(conversation.getUuid()) != null) {
 521                cancel(conversation.getUuid(), NOTIFICATION_ID);
 522                updateNotification(false, null, true);
 523            }
 524        }
 525    }
 526
 527    private void markAsReadIfHasDirectReply(final Conversation conversation) {
 528        markAsReadIfHasDirectReply(notifications.get(conversation.getUuid()));
 529    }
 530
 531    private void markAsReadIfHasDirectReply(final ArrayList<Message> messages) {
 532        if (messages != null && messages.size() > 0) {
 533            Message last = messages.get(messages.size() - 1);
 534            if (last.getStatus() != Message.STATUS_RECEIVED) {
 535                if (mXmppConnectionService.markRead((Conversation) last.getConversation(), false)) {
 536                    mXmppConnectionService.updateConversationUi();
 537                }
 538            }
 539        }
 540    }
 541
 542    private void setNotificationColor(final Builder mBuilder) {
 543        mBuilder.setColor(ContextCompat.getColor(mXmppConnectionService, R.color.green600));
 544    }
 545
 546    public void updateNotification() {
 547        synchronized (notifications) {
 548            updateNotification(false);
 549        }
 550    }
 551
 552    private void updateNotification(final boolean notify) {
 553        updateNotification(notify, null, false);
 554    }
 555
 556    private void updateNotification(final boolean notify, final List<String> conversations) {
 557        updateNotification(notify, conversations, false);
 558    }
 559
 560    private void updateNotification(final boolean notify, final List<String> conversations, final boolean summaryOnly) {
 561        final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
 562
 563        final boolean quiteHours = isQuietHours();
 564
 565        final boolean notifyOnlyOneChild = notify && conversations != null && conversations.size() == 1; //if this check is changed to > 0 catchup messages will create one notification per conversation
 566
 567
 568        if (notifications.size() == 0) {
 569            cancel(NOTIFICATION_ID);
 570        } else {
 571            if (notify) {
 572                this.markLastNotification();
 573            }
 574            final Builder mBuilder;
 575            if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
 576                mBuilder = buildSingleConversations(notifications.values().iterator().next(), notify, quiteHours);
 577                modifyForSoundVibrationAndLight(mBuilder, notify, quiteHours, preferences);
 578                notify(NOTIFICATION_ID, mBuilder.build());
 579            } else {
 580                mBuilder = buildMultipleConversation(notify, quiteHours);
 581                if (notifyOnlyOneChild) {
 582                    mBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
 583                }
 584                modifyForSoundVibrationAndLight(mBuilder, notify, quiteHours, preferences);
 585                if (!summaryOnly) {
 586                    for (Map.Entry<String, ArrayList<Message>> entry : notifications.entrySet()) {
 587                        String uuid = entry.getKey();
 588                        final boolean notifyThis = notifyOnlyOneChild ? conversations.contains(uuid) : notify;
 589                        Builder singleBuilder = buildSingleConversations(entry.getValue(), notifyThis, quiteHours);
 590                        if (!notifyOnlyOneChild) {
 591                            singleBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY);
 592                        }
 593                        modifyForSoundVibrationAndLight(singleBuilder, notifyThis, quiteHours, preferences);
 594                        singleBuilder.setGroup(CONVERSATIONS_GROUP);
 595                        setNotificationColor(singleBuilder);
 596                        notify(entry.getKey(), NOTIFICATION_ID, singleBuilder.build());
 597                    }
 598                }
 599                notify(NOTIFICATION_ID, mBuilder.build());
 600            }
 601        }
 602    }
 603
 604    private void modifyForSoundVibrationAndLight(Builder mBuilder, boolean notify, boolean quietHours, SharedPreferences preferences) {
 605        final Resources resources = mXmppConnectionService.getResources();
 606        final String ringtone = preferences.getString("notification_ringtone", resources.getString(R.string.notification_ringtone));
 607        final boolean vibrate = preferences.getBoolean("vibrate_on_notification", resources.getBoolean(R.bool.vibrate_on_notification));
 608        final boolean led = preferences.getBoolean("led", resources.getBoolean(R.bool.led));
 609        final boolean headsup = preferences.getBoolean("notification_headsup", resources.getBoolean(R.bool.headsup_notifications));
 610        if (notify && !quietHours) {
 611            if (vibrate) {
 612                final int dat = 70;
 613                final long[] pattern = {0, 3 * dat, dat, dat};
 614                mBuilder.setVibrate(pattern);
 615            } else {
 616                mBuilder.setVibrate(new long[]{0});
 617            }
 618            Uri uri = Uri.parse(ringtone);
 619            try {
 620                mBuilder.setSound(fixRingtoneUri(uri));
 621            } catch (SecurityException e) {
 622                Log.d(Config.LOGTAG, "unable to use custom notification sound " + uri.toString());
 623            }
 624        } else {
 625            mBuilder.setLocalOnly(true);
 626        }
 627        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 628            mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
 629        }
 630        mBuilder.setPriority(notify ? (headsup ? NotificationCompat.PRIORITY_HIGH : NotificationCompat.PRIORITY_DEFAULT) : NotificationCompat.PRIORITY_LOW);
 631        setNotificationColor(mBuilder);
 632        mBuilder.setDefaults(0);
 633        if (led) {
 634            mBuilder.setLights(LED_COLOR, 2000, 3000);
 635        }
 636    }
 637
 638    private void modifyIncomingCall(Builder mBuilder) {
 639        final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
 640        final Resources resources = mXmppConnectionService.getResources();
 641        final String ringtone = preferences.getString("call_ringtone", resources.getString(R.string.incoming_call_ringtone));
 642        mBuilder.setVibrate(CALL_PATTERN);
 643        final Uri uri = Uri.parse(ringtone);
 644        try {
 645            mBuilder.setSound(fixRingtoneUri(uri));
 646        } catch (SecurityException e) {
 647            Log.d(Config.LOGTAG, "unable to use custom notification sound " + uri.toString());
 648        }
 649        mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
 650        setNotificationColor(mBuilder);
 651        mBuilder.setLights(LED_COLOR, 2000, 3000);
 652    }
 653
 654    private Uri fixRingtoneUri(Uri uri) {
 655        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && "file".equals(uri.getScheme())) {
 656            return FileBackend.getUriForFile(mXmppConnectionService, new File(uri.getPath()));
 657        } else {
 658            return uri;
 659        }
 660    }
 661
 662    private Builder buildMultipleConversation(final boolean notify, final boolean quietHours) {
 663        final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService, quietHours ? "quiet_hours" : (notify ? "messages" : "silent_messages"));
 664        final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
 665        style.setBigContentTitle(mXmppConnectionService.getString(R.string.x_unread_conversations, notifications.size()));
 666        final StringBuilder names = new StringBuilder();
 667        Conversation conversation = null;
 668        for (final ArrayList<Message> messages : notifications.values()) {
 669            if (messages.size() > 0) {
 670                conversation = (Conversation) messages.get(0).getConversation();
 671                final String name = conversation.getName().toString();
 672                SpannableString styledString;
 673                if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
 674                    int count = messages.size();
 675                    styledString = new SpannableString(name + ": " + mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
 676                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
 677                    style.addLine(styledString);
 678                } else {
 679                    styledString = new SpannableString(name + ": " + UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
 680                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
 681                    style.addLine(styledString);
 682                }
 683                names.append(name);
 684                names.append(", ");
 685            }
 686        }
 687        if (names.length() >= 2) {
 688            names.delete(names.length() - 2, names.length());
 689        }
 690        mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.x_unread_conversations, notifications.size()));
 691        mBuilder.setTicker(mXmppConnectionService.getString(R.string.x_unread_conversations, notifications.size()));
 692        mBuilder.setContentText(names.toString());
 693        mBuilder.setStyle(style);
 694        if (conversation != null) {
 695            mBuilder.setContentIntent(createContentIntent(conversation));
 696        }
 697        mBuilder.setGroupSummary(true);
 698        mBuilder.setGroup(CONVERSATIONS_GROUP);
 699        mBuilder.setDeleteIntent(createDeleteIntent(null));
 700        mBuilder.setSmallIcon(R.drawable.ic_notification);
 701        return mBuilder;
 702    }
 703
 704    private Builder buildSingleConversations(final ArrayList<Message> messages, final boolean notify, final boolean quietHours) {
 705        final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService, quietHours ? "quiet_hours" : (notify ? "messages" : "silent_messages"));
 706        if (messages.size() >= 1) {
 707            final Conversation conversation = (Conversation) messages.get(0).getConversation();
 708            mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
 709                    .get(conversation, AvatarService.getSystemUiAvatarSize(mXmppConnectionService)));
 710            mBuilder.setContentTitle(conversation.getName());
 711            if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
 712                int count = messages.size();
 713                mBuilder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
 714            } else {
 715                Message message;
 716                //TODO starting with Android 9 we might want to put images in MessageStyle
 717                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P && (message = getImage(messages)) != null) {
 718                    modifyForImage(mBuilder, message, messages);
 719                } else {
 720                    modifyForTextOnly(mBuilder, messages);
 721                }
 722                RemoteInput remoteInput = new RemoteInput.Builder("text_reply").setLabel(UIHelper.getMessageHint(mXmppConnectionService, conversation)).build();
 723                PendingIntent markAsReadPendingIntent = createReadPendingIntent(conversation);
 724                NotificationCompat.Action markReadAction = new NotificationCompat.Action.Builder(
 725                        R.drawable.ic_drafts_white_24dp,
 726                        mXmppConnectionService.getString(R.string.mark_as_read),
 727                        markAsReadPendingIntent)
 728                        .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ)
 729                        .setShowsUserInterface(false)
 730                        .build();
 731                String replyLabel = mXmppConnectionService.getString(R.string.reply);
 732                NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
 733                        R.drawable.ic_send_text_offline,
 734                        replyLabel,
 735                        createReplyIntent(conversation, false))
 736                        .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY)
 737                        .setShowsUserInterface(false)
 738                        .addRemoteInput(remoteInput).build();
 739                NotificationCompat.Action wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_wear_reply,
 740                        replyLabel,
 741                        createReplyIntent(conversation, true)).addRemoteInput(remoteInput).build();
 742                mBuilder.extend(new NotificationCompat.WearableExtender().addAction(wearReplyAction));
 743                int addedActionsCount = 1;
 744                mBuilder.addAction(markReadAction);
 745                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 746                    mBuilder.addAction(replyAction);
 747                    ++addedActionsCount;
 748                }
 749
 750                if (displaySnoozeAction(messages)) {
 751                    String label = mXmppConnectionService.getString(R.string.snooze);
 752                    PendingIntent pendingSnoozeIntent = createSnoozeIntent(conversation);
 753                    NotificationCompat.Action snoozeAction = new NotificationCompat.Action.Builder(
 754                            R.drawable.ic_notifications_paused_white_24dp,
 755                            label,
 756                            pendingSnoozeIntent).build();
 757                    mBuilder.addAction(snoozeAction);
 758                    ++addedActionsCount;
 759                }
 760                if (addedActionsCount < 3) {
 761                    final Message firstLocationMessage = getFirstLocationMessage(messages);
 762                    if (firstLocationMessage != null) {
 763                        final PendingIntent pendingShowLocationIntent = createShowLocationIntent(firstLocationMessage);
 764                        if (pendingShowLocationIntent != null) {
 765                            final String label = mXmppConnectionService.getResources().getString(R.string.show_location);
 766                            NotificationCompat.Action locationAction = new NotificationCompat.Action.Builder(
 767                                    R.drawable.ic_room_white_24dp,
 768                                    label,
 769                                    pendingShowLocationIntent).build();
 770                            mBuilder.addAction(locationAction);
 771                            ++addedActionsCount;
 772                        }
 773                    }
 774                }
 775                if (addedActionsCount < 3) {
 776                    Message firstDownloadableMessage = getFirstDownloadableMessage(messages);
 777                    if (firstDownloadableMessage != null) {
 778                        String label = mXmppConnectionService.getResources().getString(R.string.download_x_file, UIHelper.getFileDescriptionString(mXmppConnectionService, firstDownloadableMessage));
 779                        PendingIntent pendingDownloadIntent = createDownloadIntent(firstDownloadableMessage);
 780                        NotificationCompat.Action downloadAction = new NotificationCompat.Action.Builder(
 781                                R.drawable.ic_file_download_white_24dp,
 782                                label,
 783                                pendingDownloadIntent).build();
 784                        mBuilder.addAction(downloadAction);
 785                        ++addedActionsCount;
 786                    }
 787                }
 788            }
 789            if (conversation.getMode() == Conversation.MODE_SINGLE) {
 790                Contact contact = conversation.getContact();
 791                Uri systemAccount = contact.getSystemAccount();
 792                if (systemAccount != null) {
 793                    mBuilder.addPerson(systemAccount.toString());
 794                }
 795            }
 796            mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
 797            mBuilder.setSmallIcon(R.drawable.ic_notification);
 798            mBuilder.setDeleteIntent(createDeleteIntent(conversation));
 799            mBuilder.setContentIntent(createContentIntent(conversation));
 800        }
 801        return mBuilder;
 802    }
 803
 804    private void modifyForImage(final Builder builder, final Message message, final ArrayList<Message> messages) {
 805        try {
 806            final Bitmap bitmap = mXmppConnectionService.getFileBackend().getThumbnail(message, getPixel(288), false);
 807            final ArrayList<Message> tmp = new ArrayList<>();
 808            for (final Message msg : messages) {
 809                if (msg.getType() == Message.TYPE_TEXT
 810                        && msg.getTransferable() == null) {
 811                    tmp.add(msg);
 812                }
 813            }
 814            final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
 815            bigPictureStyle.bigPicture(bitmap);
 816            if (tmp.size() > 0) {
 817                CharSequence text = getMergedBodies(tmp);
 818                bigPictureStyle.setSummaryText(text);
 819                builder.setContentText(text);
 820                builder.setTicker(text);
 821            } else {
 822                final String description = UIHelper.getFileDescriptionString(mXmppConnectionService, message);
 823                builder.setContentText(description);
 824                builder.setTicker(description);
 825            }
 826            builder.setStyle(bigPictureStyle);
 827        } catch (final IOException e) {
 828            modifyForTextOnly(builder, messages);
 829        }
 830    }
 831
 832    private Person getPerson(Message message) {
 833        final Contact contact = message.getContact();
 834        final Person.Builder builder = new Person.Builder();
 835        if (contact != null) {
 836            builder.setName(contact.getDisplayName());
 837            final Uri uri = contact.getSystemAccount();
 838            if (uri != null) {
 839                builder.setUri(uri.toString());
 840            }
 841        } else {
 842            builder.setName(UIHelper.getMessageDisplayName(message));
 843        }
 844        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
 845            builder.setIcon(IconCompat.createWithBitmap(mXmppConnectionService.getAvatarService().get(message, AvatarService.getSystemUiAvatarSize(mXmppConnectionService), false)));
 846        }
 847        return builder.build();
 848    }
 849
 850    private void modifyForTextOnly(final Builder builder, final ArrayList<Message> messages) {
 851        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 852            final Conversation conversation = (Conversation) messages.get(0).getConversation();
 853            final Person.Builder meBuilder = new Person.Builder().setName(mXmppConnectionService.getString(R.string.me));
 854            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
 855                meBuilder.setIcon(IconCompat.createWithBitmap(mXmppConnectionService.getAvatarService().get(conversation.getAccount(), AvatarService.getSystemUiAvatarSize(mXmppConnectionService))));
 856            }
 857            final Person me = meBuilder.build();
 858            NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(me);
 859            final boolean multiple = conversation.getMode() == Conversation.MODE_MULTI;
 860            if (multiple) {
 861                messagingStyle.setConversationTitle(conversation.getName());
 862            }
 863            for (Message message : messages) {
 864                final Person sender = message.getStatus() == Message.STATUS_RECEIVED ? getPerson(message) : null;
 865                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && isImageMessage(message)) {
 866                    final Uri dataUri = FileBackend.getMediaUri(mXmppConnectionService, mXmppConnectionService.getFileBackend().getFile(message));
 867                    NotificationCompat.MessagingStyle.Message imageMessage = new NotificationCompat.MessagingStyle.Message(UIHelper.getMessagePreview(mXmppConnectionService, message).first, message.getTimeSent(), sender);
 868                    if (dataUri != null) {
 869                        imageMessage.setData(message.getMimeType(), dataUri);
 870                    }
 871                    messagingStyle.addMessage(imageMessage);
 872                } else {
 873                    messagingStyle.addMessage(UIHelper.getMessagePreview(mXmppConnectionService, message).first, message.getTimeSent(), sender);
 874                }
 875            }
 876            messagingStyle.setGroupConversation(multiple);
 877            builder.setStyle(messagingStyle);
 878        } else {
 879            if (messages.get(0).getConversation().getMode() == Conversation.MODE_SINGLE) {
 880                builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
 881                final CharSequence preview = UIHelper.getMessagePreview(mXmppConnectionService, messages.get(messages.size() - 1)).first;
 882                builder.setContentText(preview);
 883                builder.setTicker(preview);
 884                builder.setNumber(messages.size());
 885            } else {
 886                final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
 887                SpannableString styledString;
 888                for (Message message : messages) {
 889                    final String name = UIHelper.getMessageDisplayName(message);
 890                    styledString = new SpannableString(name + ": " + message.getBody());
 891                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
 892                    style.addLine(styledString);
 893                }
 894                builder.setStyle(style);
 895                int count = messages.size();
 896                if (count == 1) {
 897                    final String name = UIHelper.getMessageDisplayName(messages.get(0));
 898                    styledString = new SpannableString(name + ": " + messages.get(0).getBody());
 899                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
 900                    builder.setContentText(styledString);
 901                    builder.setTicker(styledString);
 902                } else {
 903                    final String text = mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count);
 904                    builder.setContentText(text);
 905                    builder.setTicker(text);
 906                }
 907            }
 908        }
 909    }
 910
 911    private Message getImage(final Iterable<Message> messages) {
 912        Message image = null;
 913        for (final Message message : messages) {
 914            if (message.getStatus() != Message.STATUS_RECEIVED) {
 915                return null;
 916            }
 917            if (isImageMessage(message)) {
 918                image = message;
 919            }
 920        }
 921        return image;
 922    }
 923
 924    private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
 925        for (final Message message : messages) {
 926            if (message.getTransferable() != null || (message.getType() == Message.TYPE_TEXT && message.treatAsDownloadable())) {
 927                return message;
 928            }
 929        }
 930        return null;
 931    }
 932
 933    private Message getFirstLocationMessage(final Iterable<Message> messages) {
 934        for (final Message message : messages) {
 935            if (message.isGeoUri()) {
 936                return message;
 937            }
 938        }
 939        return null;
 940    }
 941
 942    private CharSequence getMergedBodies(final ArrayList<Message> messages) {
 943        final StringBuilder text = new StringBuilder();
 944        for (Message message : messages) {
 945            if (text.length() != 0) {
 946                text.append("\n");
 947            }
 948            text.append(UIHelper.getMessagePreview(mXmppConnectionService, message).first);
 949        }
 950        return text.toString();
 951    }
 952
 953    private PendingIntent createShowLocationIntent(final Message message) {
 954        Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(mXmppConnectionService, message);
 955        for (Intent intent : intents) {
 956            if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
 957                return PendingIntent.getActivity(mXmppConnectionService, generateRequestCode(message.getConversation(), 18), intent, PendingIntent.FLAG_UPDATE_CURRENT);
 958            }
 959        }
 960        return null;
 961    }
 962
 963    private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
 964        final Intent viewConversationIntent = new Intent(mXmppConnectionService, ConversationsActivity.class);
 965        viewConversationIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
 966        viewConversationIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversationUuid);
 967        if (downloadMessageUuid != null) {
 968            viewConversationIntent.putExtra(ConversationsActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
 969            return PendingIntent.getActivity(mXmppConnectionService,
 970                    generateRequestCode(conversationUuid, 8),
 971                    viewConversationIntent,
 972                    PendingIntent.FLAG_UPDATE_CURRENT);
 973        } else {
 974            return PendingIntent.getActivity(mXmppConnectionService,
 975                    generateRequestCode(conversationUuid, 10),
 976                    viewConversationIntent,
 977                    PendingIntent.FLAG_UPDATE_CURRENT);
 978        }
 979    }
 980
 981    private int generateRequestCode(String uuid, int actionId) {
 982        return (actionId * NOTIFICATION_ID_MULTIPLIER) + (uuid.hashCode() % NOTIFICATION_ID_MULTIPLIER);
 983    }
 984
 985    private int generateRequestCode(Conversational conversation, int actionId) {
 986        return generateRequestCode(conversation.getUuid(), actionId);
 987    }
 988
 989    private PendingIntent createDownloadIntent(final Message message) {
 990        return createContentIntent(message.getConversationUuid(), message.getUuid());
 991    }
 992
 993    private PendingIntent createContentIntent(final Conversational conversation) {
 994        return createContentIntent(conversation.getUuid(), null);
 995    }
 996
 997    private PendingIntent createDeleteIntent(Conversation conversation) {
 998        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
 999        intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
1000        if (conversation != null) {
1001            intent.putExtra("uuid", conversation.getUuid());
1002            return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 20), intent, 0);
1003        }
1004        return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
1005    }
1006
1007    private PendingIntent createReplyIntent(Conversation conversation, boolean dismissAfterReply) {
1008        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1009        intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
1010        intent.putExtra("uuid", conversation.getUuid());
1011        intent.putExtra("dismiss_notification", dismissAfterReply);
1012        final int id = generateRequestCode(conversation, dismissAfterReply ? 12 : 14);
1013        return PendingIntent.getService(mXmppConnectionService, id, intent, 0);
1014    }
1015
1016    private PendingIntent createReadPendingIntent(Conversation conversation) {
1017        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1018        intent.setAction(XmppConnectionService.ACTION_MARK_AS_READ);
1019        intent.putExtra("uuid", conversation.getUuid());
1020        intent.setPackage(mXmppConnectionService.getPackageName());
1021        return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 16), intent, PendingIntent.FLAG_UPDATE_CURRENT);
1022    }
1023
1024    private PendingIntent createCallAction(String sessionId, final String action, int requestCode) {
1025        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1026        intent.setAction(action);
1027        intent.setPackage(mXmppConnectionService.getPackageName());
1028        intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, sessionId);
1029        return PendingIntent.getService(mXmppConnectionService, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
1030    }
1031
1032    private PendingIntent createSnoozeIntent(Conversation conversation) {
1033        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1034        intent.setAction(XmppConnectionService.ACTION_SNOOZE);
1035        intent.putExtra("uuid", conversation.getUuid());
1036        intent.setPackage(mXmppConnectionService.getPackageName());
1037        return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 22), intent, PendingIntent.FLAG_UPDATE_CURRENT);
1038    }
1039
1040    private PendingIntent createTryAgainIntent() {
1041        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1042        intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
1043        return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
1044    }
1045
1046    private PendingIntent createDismissErrorIntent() {
1047        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1048        intent.setAction(XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS);
1049        return PendingIntent.getService(mXmppConnectionService, 69, intent, 0);
1050    }
1051
1052    private boolean wasHighlightedOrPrivate(final Message message) {
1053        if (message.getConversation() instanceof Conversation) {
1054            Conversation conversation = (Conversation) message.getConversation();
1055            final String nick = conversation.getMucOptions().getActualNick();
1056            final Pattern highlight = generateNickHighlightPattern(nick);
1057            if (message.getBody() == null || nick == null) {
1058                return false;
1059            }
1060            final Matcher m = highlight.matcher(message.getBody());
1061            return (m.find() || message.isPrivateMessage());
1062        } else {
1063            return false;
1064        }
1065    }
1066
1067    public void setOpenConversation(final Conversation conversation) {
1068        this.mOpenConversation = conversation;
1069    }
1070
1071    public void setIsInForeground(final boolean foreground) {
1072        this.mIsInForeground = foreground;
1073    }
1074
1075    private int getPixel(final int dp) {
1076        final DisplayMetrics metrics = mXmppConnectionService.getResources()
1077                .getDisplayMetrics();
1078        return ((int) (dp * metrics.density));
1079    }
1080
1081    private void markLastNotification() {
1082        this.mLastNotification = SystemClock.elapsedRealtime();
1083    }
1084
1085    private boolean inMiniGracePeriod(final Account account) {
1086        final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
1087                : Config.MINI_GRACE_PERIOD * 2;
1088        return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
1089    }
1090
1091    Notification createForegroundNotification() {
1092        final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1093        mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.app_name));
1094        final List<Account> accounts = mXmppConnectionService.getAccounts();
1095        int enabled = 0;
1096        int connected = 0;
1097        if (accounts != null) {
1098            for (Account account : accounts) {
1099                if (account.isOnlineAndConnected()) {
1100                    connected++;
1101                    enabled++;
1102                } else if (account.isEnabled()) {
1103                    enabled++;
1104                }
1105            }
1106        }
1107        mBuilder.setContentText(mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
1108        final PendingIntent openIntent = createOpenConversationsIntent();
1109        if (openIntent != null) {
1110            mBuilder.setContentIntent(openIntent);
1111        }
1112        mBuilder.setWhen(0);
1113        mBuilder.setPriority(Notification.PRIORITY_MIN);
1114        mBuilder.setSmallIcon(connected > 0 ? R.drawable.ic_link_white_24dp : R.drawable.ic_link_off_white_24dp);
1115
1116        if (Compatibility.runsTwentySix()) {
1117            mBuilder.setChannelId("foreground");
1118        }
1119
1120
1121        return mBuilder.build();
1122    }
1123
1124    private PendingIntent createOpenConversationsIntent() {
1125        try {
1126            return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService, ConversationsActivity.class), 0);
1127        } catch (RuntimeException e) {
1128            return null;
1129        }
1130    }
1131
1132    void updateErrorNotification() {
1133        if (Config.SUPPRESS_ERROR_NOTIFICATION) {
1134            cancel(ERROR_NOTIFICATION_ID);
1135            return;
1136        }
1137        final boolean showAllErrors = QuickConversationsService.isConversations();
1138        final List<Account> errors = new ArrayList<>();
1139        boolean torNotAvailable = false;
1140        for (final Account account : mXmppConnectionService.getAccounts()) {
1141            if (account.hasErrorStatus() && account.showErrorNotification() && (showAllErrors || account.getLastErrorStatus() == Account.State.UNAUTHORIZED)) {
1142                errors.add(account);
1143                torNotAvailable |= account.getStatus() == Account.State.TOR_NOT_AVAILABLE;
1144            }
1145        }
1146        if (mXmppConnectionService.foregroundNotificationNeedsUpdatingWhenErrorStateChanges()) {
1147            notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
1148        }
1149        final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1150        if (errors.size() == 0) {
1151            cancel(ERROR_NOTIFICATION_ID);
1152            return;
1153        } else if (errors.size() == 1) {
1154            mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
1155            mBuilder.setContentText(errors.get(0).getJid().asBareJid().toEscapedString());
1156        } else {
1157            mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
1158            mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
1159        }
1160        mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
1161                mXmppConnectionService.getString(R.string.try_again),
1162                createTryAgainIntent()
1163        );
1164        if (torNotAvailable) {
1165            if (TorServiceUtils.isOrbotInstalled(mXmppConnectionService)) {
1166                mBuilder.addAction(
1167                        R.drawable.ic_play_circle_filled_white_48dp,
1168                        mXmppConnectionService.getString(R.string.start_orbot),
1169                        PendingIntent.getActivity(mXmppConnectionService, 147, TorServiceUtils.LAUNCH_INTENT, 0)
1170                );
1171            } else {
1172                mBuilder.addAction(
1173                        R.drawable.ic_file_download_white_24dp,
1174                        mXmppConnectionService.getString(R.string.install_orbot),
1175                        PendingIntent.getActivity(mXmppConnectionService, 146, TorServiceUtils.INSTALL_INTENT, 0)
1176                );
1177            }
1178        }
1179        mBuilder.setDeleteIntent(createDismissErrorIntent());
1180        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
1181            mBuilder.setVisibility(Notification.VISIBILITY_PRIVATE);
1182            mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
1183        } else {
1184            mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
1185        }
1186        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
1187            mBuilder.setLocalOnly(true);
1188        }
1189        mBuilder.setPriority(Notification.PRIORITY_LOW);
1190        final Intent intent;
1191        if (AccountUtils.MANAGE_ACCOUNT_ACTIVITY != null) {
1192            intent = new Intent(mXmppConnectionService, AccountUtils.MANAGE_ACCOUNT_ACTIVITY);
1193        } else {
1194            intent = new Intent(mXmppConnectionService, EditAccountActivity.class);
1195            intent.putExtra("jid", errors.get(0).getJid().asBareJid().toEscapedString());
1196            intent.putExtra(EditAccountActivity.EXTRA_OPENED_FROM_NOTIFICATION, true);
1197        }
1198        mBuilder.setContentIntent(PendingIntent.getActivity(mXmppConnectionService, 145, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1199        if (Compatibility.runsTwentySix()) {
1200            mBuilder.setChannelId("error");
1201        }
1202        notify(ERROR_NOTIFICATION_ID, mBuilder.build());
1203    }
1204
1205    void updateFileAddingNotification(int current, Message message) {
1206        Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1207        mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.transcoding_video));
1208        mBuilder.setProgress(100, current, false);
1209        mBuilder.setSmallIcon(R.drawable.ic_hourglass_empty_white_24dp);
1210        mBuilder.setContentIntent(createContentIntent(message.getConversation()));
1211        mBuilder.setOngoing(true);
1212        if (Compatibility.runsTwentySix()) {
1213            mBuilder.setChannelId("compression");
1214        }
1215        Notification notification = mBuilder.build();
1216        notify(FOREGROUND_NOTIFICATION_ID, notification);
1217    }
1218
1219    private void notify(String tag, int id, Notification notification) {
1220        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1221        try {
1222            notificationManager.notify(tag, id, notification);
1223        } catch (RuntimeException e) {
1224            Log.d(Config.LOGTAG, "unable to make notification", e);
1225        }
1226    }
1227
1228    public void notify(int id, Notification notification) {
1229        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1230        try {
1231            notificationManager.notify(id, notification);
1232        } catch (RuntimeException e) {
1233            Log.d(Config.LOGTAG, "unable to make notification", e);
1234        }
1235    }
1236
1237    public void cancel(int id) {
1238        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1239        try {
1240            notificationManager.cancel(id);
1241        } catch (RuntimeException e) {
1242            Log.d(Config.LOGTAG, "unable to cancel notification", e);
1243        }
1244    }
1245
1246    private void cancel(String tag, int id) {
1247        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1248        try {
1249            notificationManager.cancel(tag, id);
1250        } catch (RuntimeException e) {
1251            Log.d(Config.LOGTAG, "unable to cancel notification", e);
1252        }
1253    }
1254}