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