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