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.NotificationCompat.CarExtender.UnreadConversation;
 26import android.support.v4.app.RemoteInput;
 27import android.support.v4.content.ContextCompat;
 28import android.text.SpannableString;
 29import android.text.style.StyleSpan;
 30import android.util.DisplayMetrics;
 31import android.util.Log;
 32import android.util.Pair;
 33
 34import org.conscrypt.Conscrypt;
 35
 36import java.io.File;
 37import java.io.IOException;
 38import java.util.ArrayList;
 39import java.util.Calendar;
 40import java.util.Collections;
 41import java.util.HashMap;
 42import java.util.Iterator;
 43import java.util.LinkedHashMap;
 44import java.util.List;
 45import java.util.Map;
 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.TimePreference;
 61import eu.siacs.conversations.utils.AccountUtils;
 62import eu.siacs.conversations.utils.Compatibility;
 63import eu.siacs.conversations.utils.GeoHelper;
 64import eu.siacs.conversations.utils.UIHelper;
 65import eu.siacs.conversations.xmpp.XmppConnection;
 66
 67public class NotificationService {
 68
 69    public static final Object CATCHUP_LOCK = new Object();
 70
 71    private static final int LED_COLOR = 0xff00ff00;
 72
 73    private static final String CONVERSATIONS_GROUP = "eu.siacs.conversations";
 74    private static final int NOTIFICATION_ID_MULTIPLIER = 1024 * 1024;
 75    private static final int NOTIFICATION_ID = 2 * NOTIFICATION_ID_MULTIPLIER;
 76    public static final int FOREGROUND_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 4;
 77    private static final int ERROR_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 6;
 78    private final XmppConnectionService mXmppConnectionService;
 79    private final LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<>();
 80    private final HashMap<Conversation, AtomicInteger> mBacklogMessageCounter = new HashMap<>();
 81    private Conversation mOpenConversation;
 82    private boolean mIsInForeground;
 83    private long mLastNotification;
 84
 85    NotificationService(final XmppConnectionService service) {
 86        this.mXmppConnectionService = service;
 87    }
 88
 89    private static boolean displaySnoozeAction(List<Message> messages) {
 90        int numberOfMessagesWithoutReply = 0;
 91        for (Message message : messages) {
 92            if (message.getStatus() == Message.STATUS_RECEIVED) {
 93                ++numberOfMessagesWithoutReply;
 94            } else {
 95                return false;
 96            }
 97        }
 98        return numberOfMessagesWithoutReply >= 3;
 99    }
100
101    public static Pattern generateNickHighlightPattern(final String nick) {
102        return Pattern.compile("(?<=(^|\\s))" + Pattern.quote(nick) + "(?=\\s|$|\\p{Punct})");
103    }
104
105    @RequiresApi(api = Build.VERSION_CODES.O)
106    void initializeChannels() {
107        final Context c = mXmppConnectionService;
108        final NotificationManager notificationManager = c.getSystemService(NotificationManager.class);
109        if (notificationManager == null) {
110            return;
111        }
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("export",
138                c.getString(R.string.export_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_RINGTONE)
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 = preferences.getLong("quiet_hours_start", TimePreference.DEFAULT_VALUE) % Config.MILLISECONDS_IN_DAY;
201        final long endTime = preferences.getLong("quiet_hours_end", TimePreference.DEFAULT_VALUE) % Config.MILLISECONDS_IN_DAY;
202        final long nowTime = Calendar.getInstance().getTimeInMillis() % Config.MILLISECONDS_IN_DAY;
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    public 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 (Iterator<Map.Entry<Conversation, AtomicInteger>> it = mBacklogMessageCounter.entrySet().iterator(); it.hasNext(); ) {
256            Map.Entry<Conversation, AtomicInteger> entry = it.next();
257            if (entry.getKey().getAccount() == account) {
258                conversations.add(entry.getKey().getUuid());
259            }
260        }
261        return conversations;
262    }
263
264    private int getBacklogMessageCount(Account account) {
265        int count = 0;
266        for (Iterator<Map.Entry<Conversation, AtomicInteger>> it = mBacklogMessageCounter.entrySet().iterator(); it.hasNext(); ) {
267            Map.Entry<Conversation, AtomicInteger> entry = it.next();
268            if (entry.getKey().getAccount() == account) {
269                count += entry.getValue().get();
270                it.remove();
271            }
272        }
273        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": backlog message count=" + count);
274        return count;
275    }
276
277    public void finishBacklog(boolean notify) {
278        finishBacklog(notify, null);
279    }
280
281    private void pushToStack(final Message message) {
282        final String conversationUuid = message.getConversationUuid();
283        if (notifications.containsKey(conversationUuid)) {
284            notifications.get(conversationUuid).add(message);
285        } else {
286            final ArrayList<Message> mList = new ArrayList<>();
287            mList.add(message);
288            notifications.put(conversationUuid, mList);
289        }
290    }
291
292    public void push(final Message message) {
293        synchronized (CATCHUP_LOCK) {
294            final XmppConnection connection = message.getConversation().getAccount().getXmppConnection();
295            if (connection != null && connection.isWaitingForSmCatchup()) {
296                connection.incrementSmCatchupMessageCounter();
297                pushFromBacklog(message);
298            } else {
299                pushNow(message);
300            }
301        }
302    }
303
304    private void pushNow(final Message message) {
305        mXmppConnectionService.updateUnreadCountBadge();
306        if (!notify(message)) {
307            Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because turned off");
308            return;
309        }
310        final boolean isScreenOn = mXmppConnectionService.isInteractive();
311        if (this.mIsInForeground && isScreenOn && this.mOpenConversation == message.getConversation()) {
312            Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because conversation is open");
313            return;
314        }
315        synchronized (notifications) {
316            pushToStack(message);
317            final Conversational conversation = message.getConversation();
318            final Account account = conversation.getAccount();
319            final boolean doNotify = (!(this.mIsInForeground && this.mOpenConversation == null) || !isScreenOn)
320                    && !account.inGracePeriod()
321                    && !this.inMiniGracePeriod(account);
322            updateNotification(doNotify, Collections.singletonList(conversation.getUuid()));
323        }
324    }
325
326    public void clear() {
327        synchronized (notifications) {
328            for (ArrayList<Message> messages : notifications.values()) {
329                markAsReadIfHasDirectReply(messages);
330            }
331            notifications.clear();
332            updateNotification(false);
333        }
334    }
335
336    public void clear(final Conversation conversation) {
337        synchronized (this.mBacklogMessageCounter) {
338            this.mBacklogMessageCounter.remove(conversation);
339        }
340        synchronized (notifications) {
341            markAsReadIfHasDirectReply(conversation);
342            if (notifications.remove(conversation.getUuid()) != null) {
343                cancel(conversation.getUuid(), NOTIFICATION_ID);
344                updateNotification(false, null, true);
345            }
346        }
347    }
348
349    private void markAsReadIfHasDirectReply(final Conversation conversation) {
350        markAsReadIfHasDirectReply(notifications.get(conversation.getUuid()));
351    }
352
353    private void markAsReadIfHasDirectReply(final ArrayList<Message> messages) {
354        if (messages != null && messages.size() > 0) {
355            Message last = messages.get(messages.size() - 1);
356            if (last.getStatus() != Message.STATUS_RECEIVED) {
357                if (mXmppConnectionService.markRead((Conversation) last.getConversation(), false)) {
358                    mXmppConnectionService.updateConversationUi();
359                }
360            }
361        }
362    }
363
364    private void setNotificationColor(final Builder mBuilder) {
365        mBuilder.setColor(ContextCompat.getColor(mXmppConnectionService, R.color.green600));
366    }
367
368    public void updateNotification(final boolean notify) {
369        updateNotification(notify, null, false);
370    }
371
372    public void updateNotification(final boolean notify, final List<String> conversations) {
373        updateNotification(notify, conversations, false);
374    }
375
376    private void updateNotification(final boolean notify, final List<String> conversations, final boolean summaryOnly) {
377        final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
378
379        final boolean quiteHours = isQuietHours();
380
381        final boolean notifyOnlyOneChild = notify && conversations != null && conversations.size() == 1; //if this check is changed to > 0 catchup messages will create one notification per conversation
382
383
384        if (notifications.size() == 0) {
385            cancel(NOTIFICATION_ID);
386        } else {
387            if (notify) {
388                this.markLastNotification();
389            }
390            final Builder mBuilder;
391            if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
392                mBuilder = buildSingleConversations(notifications.values().iterator().next(), notify, quiteHours);
393                modifyForSoundVibrationAndLight(mBuilder, notify, quiteHours, preferences);
394                notify(NOTIFICATION_ID, mBuilder.build());
395            } else {
396                mBuilder = buildMultipleConversation(notify, quiteHours);
397                if (notifyOnlyOneChild) {
398                    mBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
399                }
400                modifyForSoundVibrationAndLight(mBuilder, notify, quiteHours, preferences);
401                if (!summaryOnly) {
402                    for (Map.Entry<String, ArrayList<Message>> entry : notifications.entrySet()) {
403                        String uuid = entry.getKey();
404                        final boolean notifyThis = notifyOnlyOneChild ? conversations.contains(uuid) : notify;
405                        Builder singleBuilder = buildSingleConversations(entry.getValue(), notifyThis, quiteHours);
406                        if (!notifyOnlyOneChild) {
407                            singleBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY);
408                        }
409                        modifyForSoundVibrationAndLight(singleBuilder, notifyThis, quiteHours, preferences);
410                        singleBuilder.setGroup(CONVERSATIONS_GROUP);
411                        setNotificationColor(singleBuilder);
412                        notify(entry.getKey(), NOTIFICATION_ID, singleBuilder.build());
413                    }
414                }
415                notify(NOTIFICATION_ID, mBuilder.build());
416            }
417        }
418    }
419
420    private void modifyForSoundVibrationAndLight(Builder mBuilder, boolean notify, boolean quietHours, SharedPreferences preferences) {
421        final Resources resources = mXmppConnectionService.getResources();
422        final String ringtone = preferences.getString("notification_ringtone", resources.getString(R.string.notification_ringtone));
423        final boolean vibrate = preferences.getBoolean("vibrate_on_notification", resources.getBoolean(R.bool.vibrate_on_notification));
424        final boolean led = preferences.getBoolean("led", resources.getBoolean(R.bool.led));
425        final boolean headsup = preferences.getBoolean("notification_headsup", resources.getBoolean(R.bool.headsup_notifications));
426        if (notify && !quietHours) {
427            if (vibrate) {
428                final int dat = 70;
429                final long[] pattern = {0, 3 * dat, dat, dat};
430                mBuilder.setVibrate(pattern);
431            } else {
432                mBuilder.setVibrate(new long[]{0});
433            }
434            Uri uri = Uri.parse(ringtone);
435            try {
436                mBuilder.setSound(fixRingtoneUri(uri));
437            } catch (SecurityException e) {
438                Log.d(Config.LOGTAG, "unable to use custom notification sound " + uri.toString());
439            }
440        }
441        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
442            mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
443        }
444        mBuilder.setPriority(notify ? (headsup ? NotificationCompat.PRIORITY_HIGH : NotificationCompat.PRIORITY_DEFAULT) : NotificationCompat.PRIORITY_LOW);
445        setNotificationColor(mBuilder);
446        mBuilder.setDefaults(0);
447        if (led) {
448            mBuilder.setLights(LED_COLOR, 2000, 3000);
449        }
450    }
451
452    private Uri fixRingtoneUri(Uri uri) {
453        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && "file".equals(uri.getScheme())) {
454            return FileBackend.getUriForFile(mXmppConnectionService, new File(uri.getPath()));
455        } else {
456            return uri;
457        }
458    }
459
460    private Builder buildMultipleConversation(final boolean notify, final boolean quietHours) {
461        final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService, quietHours ? "quiet_hours" : (notify ? "messages" : "silent_messages"));
462        final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
463        style.setBigContentTitle(notifications.size()
464                + " "
465                + mXmppConnectionService
466                .getString(R.string.unread_conversations));
467        final StringBuilder names = new StringBuilder();
468        Conversation conversation = null;
469        for (final ArrayList<Message> messages : notifications.values()) {
470            if (messages.size() > 0) {
471                conversation = (Conversation) messages.get(0).getConversation();
472                final String name = conversation.getName().toString();
473                SpannableString styledString;
474                if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
475                    int count = messages.size();
476                    styledString = new SpannableString(name + ": " + mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
477                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
478                    style.addLine(styledString);
479                } else {
480                    styledString = new SpannableString(name + ": " + UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
481                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
482                    style.addLine(styledString);
483                }
484                names.append(name);
485                names.append(", ");
486            }
487        }
488        if (names.length() >= 2) {
489            names.delete(names.length() - 2, names.length());
490        }
491        mBuilder.setContentTitle(notifications.size()
492                + " "
493                + mXmppConnectionService
494                .getString(R.string.unread_conversations));
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            final UnreadConversation.Builder mUnreadBuilder = new UnreadConversation.Builder(conversation.getName().toString());
512            mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
513                    .get(conversation, getPixel(64)));
514            mBuilder.setContentTitle(conversation.getName());
515            if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
516                int count = messages.size();
517                mBuilder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
518            } else {
519                Message message;
520                if ((message = getImage(messages)) != null) {
521                    modifyForImage(mBuilder, mUnreadBuilder, message, messages);
522                } else {
523                    modifyForTextOnly(mBuilder, mUnreadBuilder, 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).build();
531                String replyLabel = mXmppConnectionService.getString(R.string.reply);
532                NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
533                        R.drawable.ic_send_text_offline,
534                        replyLabel,
535                        createReplyIntent(conversation, false)).addRemoteInput(remoteInput).build();
536                NotificationCompat.Action wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_wear_reply,
537                        replyLabel,
538                        createReplyIntent(conversation, true)).addRemoteInput(remoteInput).build();
539                mBuilder.extend(new NotificationCompat.WearableExtender().addAction(wearReplyAction));
540                mUnreadBuilder.setReplyAction(createReplyIntent(conversation, true), remoteInput);
541                mUnreadBuilder.setReadPendingIntent(markAsReadPendingIntent);
542                mBuilder.extend(new NotificationCompat.CarExtender().setUnreadConversation(mUnreadBuilder.build()));
543                int addedActionsCount = 1;
544                mBuilder.addAction(markReadAction);
545                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
546                    mBuilder.addAction(replyAction);
547                    ++addedActionsCount;
548                }
549
550                if (displaySnoozeAction(messages)) {
551                    String label = mXmppConnectionService.getString(R.string.snooze);
552                    PendingIntent pendingSnoozeIntent = createSnoozeIntent(conversation);
553                    NotificationCompat.Action snoozeAction = new NotificationCompat.Action.Builder(
554                            R.drawable.ic_notifications_paused_white_24dp,
555                            label,
556                            pendingSnoozeIntent).build();
557                    mBuilder.addAction(snoozeAction);
558                    ++addedActionsCount;
559                }
560                if (addedActionsCount < 3) {
561                    final Message firstLocationMessage = getFirstLocationMessage(messages);
562                    if (firstLocationMessage != null) {
563                        String label = mXmppConnectionService.getResources().getString(R.string.show_location);
564                        PendingIntent pendingShowLocationIntent = createShowLocationIntent(firstLocationMessage);
565                        NotificationCompat.Action locationAction = new NotificationCompat.Action.Builder(
566                                R.drawable.ic_room_white_24dp,
567                                label,
568                                pendingShowLocationIntent).build();
569                        mBuilder.addAction(locationAction);
570                        ++addedActionsCount;
571                    }
572                }
573                if (addedActionsCount < 3) {
574                    Message firstDownloadableMessage = getFirstDownloadableMessage(messages);
575                    if (firstDownloadableMessage != null) {
576                        String label = mXmppConnectionService.getResources().getString(R.string.download_x_file, UIHelper.getFileDescriptionString(mXmppConnectionService, firstDownloadableMessage));
577                        PendingIntent pendingDownloadIntent = createDownloadIntent(firstDownloadableMessage);
578                        NotificationCompat.Action downloadAction = new NotificationCompat.Action.Builder(
579                                R.drawable.ic_file_download_white_24dp,
580                                label,
581                                pendingDownloadIntent).build();
582                        mBuilder.addAction(downloadAction);
583                        ++addedActionsCount;
584                    }
585                }
586            }
587            if (conversation.getMode() == Conversation.MODE_SINGLE) {
588                Contact contact = conversation.getContact();
589                Uri systemAccount = contact.getSystemAccount();
590                if (systemAccount != null) {
591                    mBuilder.addPerson(systemAccount.toString());
592                }
593            }
594            mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
595            mBuilder.setSmallIcon(R.drawable.ic_notification);
596            mBuilder.setDeleteIntent(createDeleteIntent(conversation));
597            mBuilder.setContentIntent(createContentIntent(conversation));
598        }
599        return mBuilder;
600    }
601
602    private void modifyForImage(final Builder builder, final UnreadConversation.Builder uBuilder,
603                                final Message message, final ArrayList<Message> messages) {
604        try {
605            final Bitmap bitmap = mXmppConnectionService.getFileBackend()
606                    .getThumbnail(message, getPixel(288), false);
607            final ArrayList<Message> tmp = new ArrayList<>();
608            for (final Message msg : messages) {
609                if (msg.getType() == Message.TYPE_TEXT
610                        && msg.getTransferable() == null) {
611                    tmp.add(msg);
612                }
613            }
614            final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
615            bigPictureStyle.bigPicture(bitmap);
616            if (tmp.size() > 0) {
617                CharSequence text = getMergedBodies(tmp);
618                bigPictureStyle.setSummaryText(text);
619                builder.setContentText(text);
620            } else {
621                builder.setContentText(UIHelper.getFileDescriptionString(mXmppConnectionService, message));
622            }
623            builder.setStyle(bigPictureStyle);
624        } catch (final IOException e) {
625            modifyForTextOnly(builder, uBuilder, messages);
626        }
627    }
628
629    private void modifyForTextOnly(final Builder builder, final UnreadConversation.Builder uBuilder, final ArrayList<Message> messages) {
630        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
631            NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(mXmppConnectionService.getString(R.string.me));
632            final Conversation conversation = (Conversation) messages.get(0).getConversation();
633            if (conversation.getMode() == Conversation.MODE_MULTI) {
634                messagingStyle.setConversationTitle(conversation.getName());
635            }
636            for (Message message : messages) {
637                String sender = message.getStatus() == Message.STATUS_RECEIVED ? UIHelper.getMessageDisplayName(message) : null;
638                messagingStyle.addMessage(UIHelper.getMessagePreview(mXmppConnectionService, message).first, message.getTimeSent(), sender);
639            }
640            builder.setStyle(messagingStyle);
641        } else {
642            if (messages.get(0).getConversation().getMode() == Conversation.MODE_SINGLE) {
643                builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
644                builder.setContentText(UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
645            } else {
646                final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
647                SpannableString styledString;
648                for (Message message : messages) {
649                    final String name = UIHelper.getMessageDisplayName(message);
650                    styledString = new SpannableString(name + ": " + message.getBody());
651                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
652                    style.addLine(styledString);
653                }
654                builder.setStyle(style);
655                int count = messages.size();
656                if (count == 1) {
657                    final String name = UIHelper.getMessageDisplayName(messages.get(0));
658                    styledString = new SpannableString(name + ": " + messages.get(0).getBody());
659                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
660                    builder.setContentText(styledString);
661                } else {
662                    builder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
663                }
664            }
665        }
666        /** message preview for Android Auto **/
667        for (Message message : messages) {
668            Pair<CharSequence, Boolean> preview = UIHelper.getMessagePreview(mXmppConnectionService, message);
669            // only show user written text
670            if (!preview.second) {
671                uBuilder.addMessage(preview.first.toString());
672                uBuilder.setLatestTimestamp(message.getTimeSent());
673            }
674        }
675    }
676
677    private Message getImage(final Iterable<Message> messages) {
678        Message image = null;
679        for (final Message message : messages) {
680            if (message.getStatus() != Message.STATUS_RECEIVED) {
681                return null;
682            }
683            if (message.getType() != Message.TYPE_TEXT
684                    && message.getTransferable() == null
685                    && message.getEncryption() != Message.ENCRYPTION_PGP
686                    && message.getFileParams().height > 0) {
687                image = message;
688            }
689        }
690        return image;
691    }
692
693    private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
694        for (final Message message : messages) {
695            if (message.getTransferable() != null || (message.getType() == Message.TYPE_TEXT && message.treatAsDownloadable())) {
696                return message;
697            }
698        }
699        return null;
700    }
701
702    private Message getFirstLocationMessage(final Iterable<Message> messages) {
703        for (final Message message : messages) {
704            if (message.isGeoUri()) {
705                return message;
706            }
707        }
708        return null;
709    }
710
711    private CharSequence getMergedBodies(final ArrayList<Message> messages) {
712        final StringBuilder text = new StringBuilder();
713        for (Message message : messages) {
714            if (text.length() != 0) {
715                text.append("\n");
716            }
717            text.append(UIHelper.getMessagePreview(mXmppConnectionService, message).first);
718        }
719        return text.toString();
720    }
721
722    private PendingIntent createShowLocationIntent(final Message message) {
723        Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(mXmppConnectionService, message);
724        for (Intent intent : intents) {
725            if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
726                return PendingIntent.getActivity(mXmppConnectionService, generateRequestCode(message.getConversation(), 18), intent, PendingIntent.FLAG_UPDATE_CURRENT);
727            }
728        }
729        return createOpenConversationsIntent();
730    }
731
732    private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
733        final Intent viewConversationIntent = new Intent(mXmppConnectionService, ConversationsActivity.class);
734        viewConversationIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
735        viewConversationIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversationUuid);
736        if (downloadMessageUuid != null) {
737            viewConversationIntent.putExtra(ConversationsActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
738            return PendingIntent.getActivity(mXmppConnectionService,
739                    generateRequestCode(conversationUuid, 8),
740                    viewConversationIntent,
741                    PendingIntent.FLAG_UPDATE_CURRENT);
742        } else {
743            return PendingIntent.getActivity(mXmppConnectionService,
744                    generateRequestCode(conversationUuid, 10),
745                    viewConversationIntent,
746                    PendingIntent.FLAG_UPDATE_CURRENT);
747        }
748    }
749
750    private int generateRequestCode(String uuid, int actionId) {
751        return (actionId * NOTIFICATION_ID_MULTIPLIER) + (uuid.hashCode() % NOTIFICATION_ID_MULTIPLIER);
752    }
753
754    private int generateRequestCode(Conversational conversation, int actionId) {
755        return generateRequestCode(conversation.getUuid(), actionId);
756    }
757
758    private PendingIntent createDownloadIntent(final Message message) {
759        return createContentIntent(message.getConversationUuid(), message.getUuid());
760    }
761
762    private PendingIntent createContentIntent(final Conversational conversation) {
763        return createContentIntent(conversation.getUuid(), null);
764    }
765
766    private PendingIntent createDeleteIntent(Conversation conversation) {
767        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
768        intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
769        if (conversation != null) {
770            intent.putExtra("uuid", conversation.getUuid());
771            return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 20), intent, 0);
772        }
773        return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
774    }
775
776    private PendingIntent createReplyIntent(Conversation conversation, boolean dismissAfterReply) {
777        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
778        intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
779        intent.putExtra("uuid", conversation.getUuid());
780        intent.putExtra("dismiss_notification", dismissAfterReply);
781        final int id = generateRequestCode(conversation, dismissAfterReply ? 12 : 14);
782        return PendingIntent.getService(mXmppConnectionService, id, intent, 0);
783    }
784
785    private PendingIntent createReadPendingIntent(Conversation conversation) {
786        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
787        intent.setAction(XmppConnectionService.ACTION_MARK_AS_READ);
788        intent.putExtra("uuid", conversation.getUuid());
789        intent.setPackage(mXmppConnectionService.getPackageName());
790        return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 16), intent, PendingIntent.FLAG_UPDATE_CURRENT);
791    }
792
793    private PendingIntent createSnoozeIntent(Conversation conversation) {
794        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
795        intent.setAction(XmppConnectionService.ACTION_SNOOZE);
796        intent.putExtra("uuid", conversation.getUuid());
797        intent.setPackage(mXmppConnectionService.getPackageName());
798        return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 22), intent, PendingIntent.FLAG_UPDATE_CURRENT);
799    }
800
801    private PendingIntent createTryAgainIntent() {
802        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
803        intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
804        return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
805    }
806
807    private PendingIntent createDismissErrorIntent() {
808        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
809        intent.setAction(XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS);
810        return PendingIntent.getService(mXmppConnectionService, 69, intent, 0);
811    }
812
813    private boolean wasHighlightedOrPrivate(final Message message) {
814        if (message.getConversation() instanceof Conversation) {
815            Conversation conversation = (Conversation) message.getConversation();
816            final String nick = conversation.getMucOptions().getActualNick();
817            final Pattern highlight = generateNickHighlightPattern(nick);
818            if (message.getBody() == null || nick == null) {
819                return false;
820            }
821            final Matcher m = highlight.matcher(message.getBody());
822            return (m.find() || message.getType() == Message.TYPE_PRIVATE);
823        } else {
824            return false;
825        }
826    }
827
828    public void setOpenConversation(final Conversation conversation) {
829        this.mOpenConversation = conversation;
830    }
831
832    public void setIsInForeground(final boolean foreground) {
833        this.mIsInForeground = foreground;
834    }
835
836    private int getPixel(final int dp) {
837        final DisplayMetrics metrics = mXmppConnectionService.getResources()
838                .getDisplayMetrics();
839        return ((int) (dp * metrics.density));
840    }
841
842    private void markLastNotification() {
843        this.mLastNotification = SystemClock.elapsedRealtime();
844    }
845
846    private boolean inMiniGracePeriod(final Account account) {
847        final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
848                : Config.MINI_GRACE_PERIOD * 2;
849        return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
850    }
851
852    public Notification createForegroundNotification() {
853        final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
854        mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.conversations_foreground_service));
855        if (Compatibility.runsAndTargetsTwentySix(mXmppConnectionService) || Config.SHOW_CONNECTED_ACCOUNTS) {
856            List<Account> accounts = mXmppConnectionService.getAccounts();
857            int enabled = 0;
858            int connected = 0;
859            for (Account account : accounts) {
860                if (account.isOnlineAndConnected()) {
861                    connected++;
862                    enabled++;
863                } else if (account.isEnabled()) {
864                    enabled++;
865                }
866            }
867            mBuilder.setContentText(mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
868        } else {
869            mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_open_conversations));
870        }
871        mBuilder.setContentIntent(createOpenConversationsIntent());
872        mBuilder.setWhen(0);
873        mBuilder.setPriority(Notification.PRIORITY_MIN);
874        mBuilder.setSmallIcon(R.drawable.ic_link_white_24dp);
875
876        if (Compatibility.runsTwentySix()) {
877            mBuilder.setChannelId("foreground");
878        }
879
880
881        return mBuilder.build();
882    }
883
884    private PendingIntent createOpenConversationsIntent() {
885        return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService, ConversationsActivity.class), 0);
886    }
887
888    public void updateErrorNotification() {
889        if (Config.SUPPRESS_ERROR_NOTIFICATION) {
890            cancel(ERROR_NOTIFICATION_ID);
891            return;
892        }
893        final boolean showAllErrors = QuickConversationsService.isConversations();
894        final List<Account> errors = new ArrayList<>();
895        for (final Account account : mXmppConnectionService.getAccounts()) {
896            if (account.hasErrorStatus() && account.showErrorNotification() && (showAllErrors || account.getLastErrorStatus() == Account.State.UNAUTHORIZED)) {
897                errors.add(account);
898            }
899        }
900        if (Compatibility.keepForegroundService(mXmppConnectionService)) {
901            notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
902        }
903        final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
904        if (errors.size() == 0) {
905            cancel(ERROR_NOTIFICATION_ID);
906            return;
907        } else if (errors.size() == 1) {
908            mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
909            mBuilder.setContentText(errors.get(0).getJid().asBareJid().toString());
910        } else {
911            mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
912            mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
913        }
914        mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
915                mXmppConnectionService.getString(R.string.try_again),
916                createTryAgainIntent());
917        mBuilder.setDeleteIntent(createDismissErrorIntent());
918        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
919            mBuilder.setVisibility(NotificationCompat.VISIBILITY_PRIVATE);
920            mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
921        } else {
922            mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
923        }
924        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
925            mBuilder.setLocalOnly(true);
926        }
927        mBuilder.setPriority(Notification.PRIORITY_LOW);
928        final Intent intent;
929        if (AccountUtils.MANAGE_ACCOUNT_ACTIVITY != null) {
930            intent = new Intent(mXmppConnectionService, AccountUtils.MANAGE_ACCOUNT_ACTIVITY);
931        } else {
932            intent = new Intent(mXmppConnectionService, EditAccountActivity.class);
933            intent.putExtra("jid", errors.get(0).getJid().asBareJid().toEscapedString());
934            intent.putExtra(EditAccountActivity.EXTRA_OPENED_FROM_NOTIFICATION, true);
935        }
936        mBuilder.setContentIntent(PendingIntent.getActivity(mXmppConnectionService, 145, intent, PendingIntent.FLAG_UPDATE_CURRENT));
937        if (Compatibility.runsTwentySix()) {
938            mBuilder.setChannelId("error");
939        }
940        notify(ERROR_NOTIFICATION_ID, mBuilder.build());
941    }
942
943    public void updateFileAddingNotification(int current, Message message) {
944        Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
945        mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.transcoding_video));
946        mBuilder.setProgress(100, current, false);
947        mBuilder.setSmallIcon(R.drawable.ic_hourglass_empty_white_24dp);
948        mBuilder.setContentIntent(createContentIntent(message.getConversation()));
949        mBuilder.setOngoing(true);
950        if (Compatibility.runsTwentySix()) {
951            mBuilder.setChannelId("compression");
952        }
953        Notification notification = mBuilder.build();
954        notify(FOREGROUND_NOTIFICATION_ID, notification);
955    }
956
957    public void dismissForcedForegroundNotification() {
958        cancel(FOREGROUND_NOTIFICATION_ID);
959    }
960
961    private void notify(String tag, int id, Notification notification) {
962        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
963        try {
964            notificationManager.notify(tag, id, notification);
965        } catch (RuntimeException e) {
966            Log.d(Config.LOGTAG, "unable to make notification", e);
967        }
968    }
969
970    private void notify(int id, Notification notification) {
971        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
972        try {
973            notificationManager.notify(id, notification);
974        } catch (RuntimeException e) {
975            Log.d(Config.LOGTAG, "unable to make notification", e);
976        }
977    }
978
979    private void cancel(int id) {
980        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
981        try {
982            notificationManager.cancel(id);
983        } catch (RuntimeException e) {
984            Log.d(Config.LOGTAG, "unable to cancel notification", e);
985        }
986    }
987
988    private void cancel(String tag, int id) {
989        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
990        try {
991            notificationManager.cancel(tag, id);
992        } catch (RuntimeException e) {
993            Log.d(Config.LOGTAG, "unable to cancel notification", e);
994        }
995    }
996}