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