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