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