1package eu.siacs.conversations.services;
2
3import android.Manifest;
4import static eu.siacs.conversations.utils.Compatibility.s;
5
6import android.Manifest;
7import android.app.Notification;
8import android.app.NotificationChannel;
9import android.app.NotificationChannelGroup;
10import android.app.NotificationManager;
11import android.app.PendingIntent;
12import android.content.Context;
13import android.content.Intent;
14import android.content.SharedPreferences;
15import android.content.pm.PackageManager;
16import android.content.pm.ShortcutManager;
17import android.content.res.Resources;
18import android.graphics.Bitmap;
19import android.graphics.Typeface;
20import android.media.AudioAttributes;
21import android.media.AudioManager;
22import android.media.RingtoneManager;
23import android.net.Uri;
24import android.os.Build;
25import android.os.Bundle;
26import android.os.SystemClock;
27import android.preference.PreferenceManager;
28import android.provider.Settings;
29import android.telecom.PhoneAccountHandle;
30import android.telecom.TelecomManager;
31import android.text.SpannableString;
32import android.text.style.StyleSpan;
33import android.util.DisplayMetrics;
34import android.util.Log;
35import android.util.TypedValue;
36
37import androidx.annotation.Nullable;
38import androidx.annotation.RequiresApi;
39import androidx.core.app.ActivityCompat;
40import androidx.core.app.NotificationCompat;
41import androidx.core.app.NotificationCompat.BigPictureStyle;
42import androidx.core.app.NotificationCompat.CallStyle;
43import androidx.core.app.NotificationCompat.Builder;
44import androidx.core.app.NotificationManagerCompat;
45import androidx.core.app.Person;
46import androidx.core.app.RemoteInput;
47import androidx.core.content.ContextCompat;
48import androidx.core.content.pm.ShortcutInfoCompat;
49import androidx.core.graphics.drawable.IconCompat;
50
51import com.google.common.base.Joiner;
52import com.google.common.base.Optional;
53import com.google.common.base.Splitter;
54import com.google.common.base.Strings;
55import com.google.common.collect.ImmutableMap;
56import com.google.common.collect.Iterables;
57import com.google.common.primitives.Ints;
58
59import eu.siacs.conversations.AppSettings;
60import eu.siacs.conversations.Config;
61import eu.siacs.conversations.R;
62import eu.siacs.conversations.entities.Account;
63import eu.siacs.conversations.entities.Contact;
64import eu.siacs.conversations.entities.Conversation;
65import eu.siacs.conversations.entities.Conversational;
66import eu.siacs.conversations.entities.Message;
67import eu.siacs.conversations.entities.Reaction;
68import eu.siacs.conversations.entities.MucOptions;
69import eu.siacs.conversations.persistance.FileBackend;
70import eu.siacs.conversations.ui.ConversationsActivity;
71import eu.siacs.conversations.ui.EditAccountActivity;
72import eu.siacs.conversations.ui.RtpSessionActivity;
73import eu.siacs.conversations.ui.TimePreference;
74import eu.siacs.conversations.utils.AccountUtils;
75import eu.siacs.conversations.utils.Compatibility;
76import eu.siacs.conversations.utils.GeoHelper;
77import eu.siacs.conversations.utils.TorServiceUtils;
78import eu.siacs.conversations.utils.UIHelper;
79import eu.siacs.conversations.xml.Element;
80import eu.siacs.conversations.xmpp.Jid;
81import eu.siacs.conversations.xmpp.XmppConnection;
82import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
83import eu.siacs.conversations.xmpp.jingle.Media;
84
85import java.io.File;
86import java.io.IOException;
87import java.util.ArrayList;
88import java.util.Arrays;
89import java.util.Collection;
90import java.util.Calendar;
91import java.util.Collections;
92import java.util.HashMap;
93import java.util.Iterator;
94import java.util.LinkedHashMap;
95import java.util.List;
96import java.util.Map;
97import java.util.Set;
98import java.util.concurrent.atomic.AtomicInteger;
99import java.util.regex.Matcher;
100import java.util.regex.Pattern;
101
102public class NotificationService {
103
104 public static final Object CATCHUP_LOCK = new Object();
105
106 private static final int LED_COLOR = 0xff7401cf;
107
108 private static final long[] CALL_PATTERN = {0, 500, 300, 600, 3000};
109
110 private static final String MESSAGES_GROUP = "eu.siacs.conversations.messages";
111 private static final String MISSED_CALLS_GROUP = "eu.siacs.conversations.missed_calls";
112 private static final int NOTIFICATION_ID_MULTIPLIER = 1024 * 1024;
113 static final int FOREGROUND_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 4;
114 private static final int NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 2;
115 private static final int ERROR_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 6;
116 private static final int INCOMING_CALL_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 8;
117 public static final int ONGOING_CALL_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 10;
118 public static final int MISSED_CALL_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 12;
119 private static final int DELIVERY_FAILED_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 13;
120 public static final int ONGOING_VIDEO_TRANSCODING_NOTIFICATION_ID =
121 NOTIFICATION_ID_MULTIPLIER * 14;
122 private final XmppConnectionService mXmppConnectionService;
123 private final LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<>();
124 private final HashMap<Conversation, AtomicInteger> mBacklogMessageCounter = new HashMap<>();
125 private final LinkedHashMap<Conversational, MissedCallsInfo> mMissedCalls =
126 new LinkedHashMap<>();
127 private Conversation mOpenConversation;
128 private boolean mIsInForeground;
129 private long mLastNotification;
130
131 private static final String INCOMING_CALLS_NOTIFICATION_CHANNEL = "incoming_calls_channel";
132 private static final String INCOMING_CALLS_NOTIFICATION_CHANNEL_PREFIX =
133 "incoming_calls_channel#";
134 private static final String MESSAGES_NOTIFICATION_CHANNEL = "messages";
135
136 NotificationService(final XmppConnectionService service) {
137 this.mXmppConnectionService = service;
138 }
139
140 private static boolean displaySnoozeAction(List<Message> messages) {
141 int numberOfMessagesWithoutReply = 0;
142 for (Message message : messages) {
143 if (message.getStatus() == Message.STATUS_RECEIVED) {
144 ++numberOfMessagesWithoutReply;
145 } else {
146 return false;
147 }
148 }
149 return numberOfMessagesWithoutReply >= 3;
150 }
151
152 public static Pattern generateNickHighlightPattern(final String nick) {
153 return Pattern.compile("(?<=(^|\\s))" + Pattern.quote(nick) + "(?=\\s|$|\\p{Punct})");
154 }
155
156 private static boolean isImageMessage(Message message) {
157 return message.getType() != Message.TYPE_TEXT
158 && message.getTransferable() == null
159 && !message.isDeleted()
160 && message.getEncryption() != Message.ENCRYPTION_PGP
161 && message.getFileParams().height > 0;
162 }
163
164 @RequiresApi(api = Build.VERSION_CODES.O)
165 void initializeChannels() {
166 final Context c = mXmppConnectionService;
167 final NotificationManager notificationManager =
168 c.getSystemService(NotificationManager.class);
169 if (notificationManager == null) {
170 return;
171 }
172
173 notificationManager.deleteNotificationChannel("export");
174 notificationManager.deleteNotificationChannel("incoming_calls");
175 notificationManager.deleteNotificationChannel(INCOMING_CALLS_NOTIFICATION_CHANNEL);
176
177 notificationManager.createNotificationChannelGroup(
178 new NotificationChannelGroup(
179 "status", c.getString(R.string.notification_group_status_information)));
180 notificationManager.createNotificationChannelGroup(
181 new NotificationChannelGroup(
182 "chats", c.getString(R.string.notification_group_messages)));
183 notificationManager.createNotificationChannelGroup(
184 new NotificationChannelGroup(
185 "calls", c.getString(R.string.notification_group_calls)));
186 final NotificationChannel foregroundServiceChannel =
187 new NotificationChannel(
188 "foreground",
189 c.getString(R.string.foreground_service_channel_name),
190 NotificationManager.IMPORTANCE_MIN);
191 foregroundServiceChannel.setDescription(
192 c.getString(
193 R.string.foreground_service_channel_description,
194 c.getString(R.string.app_name)));
195 foregroundServiceChannel.setShowBadge(false);
196 foregroundServiceChannel.setGroup("status");
197 notificationManager.createNotificationChannel(foregroundServiceChannel);
198 final NotificationChannel errorChannel =
199 new NotificationChannel(
200 "error",
201 c.getString(R.string.error_channel_name),
202 NotificationManager.IMPORTANCE_LOW);
203 errorChannel.setDescription(c.getString(R.string.error_channel_description));
204 errorChannel.setShowBadge(false);
205 errorChannel.setGroup("status");
206 notificationManager.createNotificationChannel(errorChannel);
207
208 final NotificationChannel videoCompressionChannel =
209 new NotificationChannel(
210 "compression",
211 c.getString(R.string.video_compression_channel_name),
212 NotificationManager.IMPORTANCE_LOW);
213 videoCompressionChannel.setShowBadge(false);
214 videoCompressionChannel.setGroup("status");
215 notificationManager.createNotificationChannel(videoCompressionChannel);
216
217 final NotificationChannel exportChannel =
218 new NotificationChannel(
219 "backup",
220 c.getString(R.string.backup_channel_name),
221 NotificationManager.IMPORTANCE_LOW);
222 exportChannel.setShowBadge(false);
223 exportChannel.setGroup("status");
224 notificationManager.createNotificationChannel(exportChannel);
225
226 createInitialIncomingCallChannelIfNecessary(c);
227
228 final NotificationChannel ongoingCallsChannel =
229 new NotificationChannel(
230 "ongoing_calls",
231 c.getString(R.string.ongoing_calls_channel_name),
232 NotificationManager.IMPORTANCE_LOW);
233 ongoingCallsChannel.setShowBadge(false);
234 ongoingCallsChannel.setGroup("calls");
235 notificationManager.createNotificationChannel(ongoingCallsChannel);
236
237 final NotificationChannel missedCallsChannel =
238 new NotificationChannel(
239 "missed_calls",
240 c.getString(R.string.missed_calls_channel_name),
241 NotificationManager.IMPORTANCE_HIGH);
242 missedCallsChannel.setShowBadge(true);
243 missedCallsChannel.setSound(null, null);
244 missedCallsChannel.setLightColor(LED_COLOR);
245 missedCallsChannel.enableLights(true);
246 missedCallsChannel.setGroup("calls");
247 notificationManager.createNotificationChannel(missedCallsChannel);
248
249 final NotificationChannel messagesChannel =
250 new NotificationChannel(
251 MESSAGES_NOTIFICATION_CHANNEL,
252 c.getString(R.string.messages_channel_name),
253 NotificationManager.IMPORTANCE_HIGH);
254 messagesChannel.setShowBadge(true);
255 messagesChannel.setSound(
256 RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION),
257 new AudioAttributes.Builder()
258 .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
259 .setUsage(AudioAttributes.USAGE_NOTIFICATION)
260 .build());
261 messagesChannel.setLightColor(LED_COLOR);
262 final int dat = 70;
263 final long[] pattern = {0, 3 * dat, dat, dat};
264 messagesChannel.setVibrationPattern(pattern);
265 messagesChannel.enableVibration(true);
266 messagesChannel.enableLights(true);
267 messagesChannel.setGroup("chats");
268 notificationManager.createNotificationChannel(messagesChannel);
269 final NotificationChannel silentMessagesChannel =
270 new NotificationChannel(
271 "silent_messages",
272 c.getString(R.string.silent_messages_channel_name),
273 NotificationManager.IMPORTANCE_LOW);
274 silentMessagesChannel.setDescription(
275 c.getString(R.string.silent_messages_channel_description));
276 silentMessagesChannel.setShowBadge(true);
277 silentMessagesChannel.setLightColor(LED_COLOR);
278 silentMessagesChannel.enableLights(true);
279 silentMessagesChannel.setGroup("chats");
280 notificationManager.createNotificationChannel(silentMessagesChannel);
281
282 final NotificationChannel deliveryFailedChannel =
283 new NotificationChannel(
284 "delivery_failed",
285 c.getString(R.string.delivery_failed_channel_name),
286 NotificationManager.IMPORTANCE_DEFAULT);
287 deliveryFailedChannel.setShowBadge(false);
288 deliveryFailedChannel.setSound(
289 RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION),
290 new AudioAttributes.Builder()
291 .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
292 .setUsage(AudioAttributes.USAGE_NOTIFICATION)
293 .build());
294 deliveryFailedChannel.setGroup("chats");
295 notificationManager.createNotificationChannel(deliveryFailedChannel);
296 }
297
298 @RequiresApi(api = Build.VERSION_CODES.O)
299 private static void createInitialIncomingCallChannelIfNecessary(final Context context) {
300 final var currentIteration = getCurrentIncomingCallChannelIteration(context);
301 if (currentIteration.isPresent()) {
302 return;
303 }
304 createInitialIncomingCallChannel(context);
305 }
306
307 @RequiresApi(api = Build.VERSION_CODES.O)
308 public static Optional<Integer> getCurrentIncomingCallChannelIteration(final Context context) {
309 final var notificationManager = context.getSystemService(NotificationManager.class);
310 for (final NotificationChannel channel : notificationManager.getNotificationChannels()) {
311 final String id = channel.getId();
312 if (Strings.isNullOrEmpty(id)) {
313 continue;
314 }
315 if (id.startsWith(INCOMING_CALLS_NOTIFICATION_CHANNEL_PREFIX)) {
316 final var parts = Splitter.on('#').splitToList(id);
317 if (parts.size() == 2) {
318 final var iteration = Ints.tryParse(parts.get(1));
319 if (iteration != null) {
320 return Optional.of(iteration);
321 }
322 }
323 }
324 }
325 return Optional.absent();
326 }
327
328 @RequiresApi(api = Build.VERSION_CODES.O)
329 public static Optional<NotificationChannel> getCurrentIncomingCallChannel(
330 final Context context) {
331 final var iteration = getCurrentIncomingCallChannelIteration(context);
332 return iteration.transform(
333 i -> {
334 final var notificationManager =
335 context.getSystemService(NotificationManager.class);
336 return notificationManager.getNotificationChannel(
337 INCOMING_CALLS_NOTIFICATION_CHANNEL_PREFIX + i);
338 });
339 }
340
341 @RequiresApi(api = Build.VERSION_CODES.O)
342 private static void createInitialIncomingCallChannel(final Context context) {
343 final var appSettings = new AppSettings(context);
344 final var ringtoneUri = appSettings.getRingtone();
345 createIncomingCallChannel(context, ringtoneUri, 0);
346 }
347
348 @RequiresApi(api = Build.VERSION_CODES.O)
349 public static void recreateIncomingCallChannel(final Context context, final Uri ringtone) {
350 final var currentIteration = getCurrentIncomingCallChannelIteration(context);
351 final int nextIteration;
352 if (currentIteration.isPresent()) {
353 final var notificationManager = context.getSystemService(NotificationManager.class);
354 notificationManager.deleteNotificationChannel(
355 INCOMING_CALLS_NOTIFICATION_CHANNEL_PREFIX + currentIteration.get());
356 nextIteration = currentIteration.get() + 1;
357 } else {
358 nextIteration = 0;
359 }
360 createIncomingCallChannel(context, ringtone, nextIteration);
361 }
362
363 @RequiresApi(api = Build.VERSION_CODES.O)
364 private static void createIncomingCallChannel(
365 final Context context, final Uri ringtoneUri, final int iteration) {
366 final var notificationManager = context.getSystemService(NotificationManager.class);
367 final var id = INCOMING_CALLS_NOTIFICATION_CHANNEL_PREFIX + iteration;
368 Log.d(Config.LOGTAG, "creating incoming call channel with id " + id);
369 final NotificationChannel incomingCallsChannel =
370 new NotificationChannel(
371 id,
372 context.getString(R.string.incoming_calls_channel_name),
373 NotificationManager.IMPORTANCE_HIGH);
374 incomingCallsChannel.setSound(
375 ringtoneUri,
376 new AudioAttributes.Builder()
377 .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
378 .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
379 .build());
380 incomingCallsChannel.setShowBadge(false);
381 incomingCallsChannel.setLightColor(LED_COLOR);
382 incomingCallsChannel.enableLights(true);
383 incomingCallsChannel.setGroup("calls");
384 incomingCallsChannel.setBypassDnd(true);
385 incomingCallsChannel.enableVibration(true);
386 incomingCallsChannel.setVibrationPattern(CALL_PATTERN);
387 notificationManager.createNotificationChannel(incomingCallsChannel);
388 }
389
390 private boolean notifyMessage(final Message message) {
391 final Conversation conversation = (Conversation) message.getConversation();
392 final var chatRequestsPref = mXmppConnectionService.getStringPreference("chat_requests", R.string.default_chat_requests);
393 return message.getStatus() == Message.STATUS_RECEIVED
394 && !conversation.isMuted()
395 && (conversation.alwaysNotify() || (wasHighlightedOrPrivate(message) || (conversation.notifyReplies() && wasReplyToMe(message))))
396 && !conversation.isChatRequest(chatRequestsPref)
397 && message.getType() != Message.TYPE_RTP_SESSION;
398 }
399
400 private boolean notifyMissedCall(final Message message) {
401 return message.getType() == Message.TYPE_RTP_SESSION
402 && message.getStatus() == Message.STATUS_RECEIVED;
403 }
404
405 private boolean isQuietHours(Account account) {
406 return isQuietHours(mXmppConnectionService, account);
407 }
408
409 public static boolean isQuietHours(Context context, Account account) {
410 // if (mXmppConnectionService.getAccounts().size() < 2) account = null;
411 final var suffix = account == null ? "" : ":" + account.getUuid();
412 final var preferences = PreferenceManager.getDefaultSharedPreferences(context);
413 if (!preferences.getBoolean("enable_quiet_hours" + suffix, context.getResources().getBoolean(R.bool.enable_quiet_hours))) {
414 return false;
415 }
416 final long startTime =
417 TimePreference.minutesToTimestamp(
418 preferences.getLong("quiet_hours_start" + suffix, TimePreference.DEFAULT_VALUE));
419 final long endTime =
420 TimePreference.minutesToTimestamp(
421 preferences.getLong("quiet_hours_end" + suffix, TimePreference.DEFAULT_VALUE));
422 final long nowTime = Calendar.getInstance().getTimeInMillis();
423
424 if (endTime < startTime) {
425 return nowTime > startTime || nowTime < endTime;
426 } else {
427 return nowTime > startTime && nowTime < endTime;
428 }
429 }
430
431 public void pushFromBacklog(final Message message) {
432 if (notifyMessage(message)) {
433 synchronized (notifications) {
434 getBacklogMessageCounter((Conversation) message.getConversation())
435 .incrementAndGet();
436 pushToStack(message);
437 }
438 } else if (notifyMissedCall(message)) {
439 synchronized (mMissedCalls) {
440 pushMissedCall(message);
441 }
442 }
443 }
444
445 private AtomicInteger getBacklogMessageCounter(Conversation conversation) {
446 synchronized (mBacklogMessageCounter) {
447 if (!mBacklogMessageCounter.containsKey(conversation)) {
448 mBacklogMessageCounter.put(conversation, new AtomicInteger(0));
449 }
450 return mBacklogMessageCounter.get(conversation);
451 }
452 }
453
454 void pushFromDirectReply(final Message message) {
455 synchronized (notifications) {
456 pushToStack(message);
457 updateNotification(false);
458 }
459 }
460
461 public void finishBacklog(boolean notify, Account account) {
462 synchronized (notifications) {
463 mXmppConnectionService.updateUnreadCountBadge();
464 if (account == null || !notify) {
465 updateNotification(notify);
466 } else {
467 final int count;
468 final List<String> conversations;
469 synchronized (this.mBacklogMessageCounter) {
470 conversations = getBacklogConversations(account);
471 count = getBacklogMessageCount(account);
472 }
473 updateNotification(count > 0, conversations);
474 }
475 }
476 synchronized (mMissedCalls) {
477 updateMissedCallNotifications(mMissedCalls.keySet());
478 }
479 }
480
481 private List<String> getBacklogConversations(Account account) {
482 final List<String> conversations = new ArrayList<>();
483 for (Map.Entry<Conversation, AtomicInteger> entry : mBacklogMessageCounter.entrySet()) {
484 if (entry.getKey().getAccount() == account) {
485 conversations.add(entry.getKey().getUuid());
486 }
487 }
488 return conversations;
489 }
490
491 private int getBacklogMessageCount(Account account) {
492 int count = 0;
493 for (Iterator<Map.Entry<Conversation, AtomicInteger>> it =
494 mBacklogMessageCounter.entrySet().iterator();
495 it.hasNext(); ) {
496 Map.Entry<Conversation, AtomicInteger> entry = it.next();
497 if (entry.getKey().getAccount() == account) {
498 count += entry.getValue().get();
499 it.remove();
500 }
501 }
502 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": backlog message count=" + count);
503 return count;
504 }
505
506 void finishBacklog() {
507 finishBacklog(false, null);
508 }
509
510 private void pushToStack(final Message message) {
511 final String conversationUuid = message.getConversationUuid();
512 if (notifications.containsKey(conversationUuid)) {
513 notifications.get(conversationUuid).add(message);
514 } else {
515 final ArrayList<Message> mList = new ArrayList<>();
516 mList.add(message);
517 notifications.put(conversationUuid, mList);
518 }
519 }
520
521 public void push(final Message message) {
522 synchronized (CATCHUP_LOCK) {
523 final XmppConnection connection =
524 message.getConversation().getAccount().getXmppConnection();
525 if (connection != null && connection.isWaitingForSmCatchup()) {
526 connection.incrementSmCatchupMessageCounter();
527 pushFromBacklog(message);
528 } else {
529 pushNow(message);
530 }
531 }
532 }
533
534 public void push(final Message reactingTo, final Jid counterpart, final String occupantId, final Collection<String> newReactions) {
535 if (newReactions.isEmpty()) return;
536
537 final var message = reactingTo.reply();
538 final var quoteable = reactingTo.getQuoteableBody();
539 final var parentTxt = reactingTo.isOOb() ? "media" : "'" + (quoteable.length() > 35 ? quoteable.substring(0, 35) + "…" : quoteable) + "'";
540 message.appendBody(String.join(" ", newReactions) + " to " + parentTxt);
541 message.setCounterpart(counterpart);
542 message.setOccupantId(occupantId);
543 message.setStatus(Message.STATUS_RECEIVED);
544 synchronized (CATCHUP_LOCK) {
545 final XmppConnection connection =
546 message.getConversation().getAccount().getXmppConnection();
547 if (connection != null && connection.isWaitingForSmCatchup()) {
548 connection.incrementSmCatchupMessageCounter();
549 pushFromBacklog(message);
550 } else {
551 pushNow(message);
552 }
553 }
554 }
555
556 public void pushFailedDelivery(final Message message) {
557 final Conversation conversation = (Conversation) message.getConversation();
558 final boolean isScreenLocked = !mXmppConnectionService.isScreenLocked();
559 if (this.mIsInForeground
560 && isScreenLocked
561 && this.mOpenConversation == message.getConversation()) {
562 Log.d(
563 Config.LOGTAG,
564 message.getConversation().getAccount().getJid().asBareJid()
565 + ": suppressing failed delivery notification because conversation is open");
566 return;
567 }
568 final PendingIntent pendingIntent = createContentIntent(conversation);
569 final int notificationId =
570 generateRequestCode(conversation, 0) + DELIVERY_FAILED_NOTIFICATION_ID;
571 final int failedDeliveries = conversation.countFailedDeliveries();
572 final Notification notification =
573 new Builder(mXmppConnectionService, "delivery_failed")
574 .setContentTitle(conversation.getName())
575 .setAutoCancel(true)
576 .setSmallIcon(R.drawable.ic_error_24dp)
577 .setContentText(
578 mXmppConnectionService
579 .getResources()
580 .getQuantityText(
581 R.plurals.some_messages_could_not_be_delivered,
582 failedDeliveries))
583 .setGroup("delivery_failed")
584 .setContentIntent(pendingIntent)
585 .build();
586 final Notification summaryNotification =
587 new Builder(mXmppConnectionService, "delivery_failed")
588 .setContentTitle(
589 mXmppConnectionService.getString(R.string.failed_deliveries))
590 .setContentText(
591 mXmppConnectionService
592 .getResources()
593 .getQuantityText(
594 R.plurals.some_messages_could_not_be_delivered,
595 1024))
596 .setSmallIcon(R.drawable.ic_error_24dp)
597 .setGroup("delivery_failed")
598 .setGroupSummary(true)
599 .setAutoCancel(true)
600 .build();
601 notify(notificationId, notification);
602 notify(DELIVERY_FAILED_NOTIFICATION_ID, summaryNotification);
603 }
604
605 public synchronized void startRinging(final AbstractJingleConnection.Id id, final Set<Media> media) {
606 if (isQuietHours(id.getContact().getAccount())) return;
607
608 showIncomingCallNotification(id, media, false);
609 }
610
611 private void showIncomingCallNotification(
612 final AbstractJingleConnection.Id id,
613 final Set<Media> media,
614 final boolean onlyAlertOnce) {
615 final Intent fullScreenIntent =
616 new Intent(mXmppConnectionService, RtpSessionActivity.class);
617 fullScreenIntent.putExtra(
618 RtpSessionActivity.EXTRA_ACCOUNT,
619 id.account.getJid().asBareJid().toEscapedString());
620 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_WITH, id.with.toEscapedString());
621 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.sessionId);
622 fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
623 fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
624 final int channelIteration;
625 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
626 channelIteration = getCurrentIncomingCallChannelIteration(mXmppConnectionService).or(0);
627 } else {
628 channelIteration = 0;
629 }
630 final var channelId = INCOMING_CALLS_NOTIFICATION_CHANNEL_PREFIX + channelIteration;
631 Log.d(
632 Config.LOGTAG,
633 "showing incoming call notification on channel "
634 + channelId
635 + ", onlyAlertOnce="
636 + onlyAlertOnce);
637 final NotificationCompat.Builder builder =
638 new NotificationCompat.Builder(
639 mXmppConnectionService, channelId);
640 final Contact contact = id.getContact();
641 builder.addPerson(getPerson(contact));
642 ShortcutInfoCompat info = mXmppConnectionService.getShortcutService().getShortcutInfoCompat(contact);
643 builder.setShortcutInfo(info);
644 if (Build.VERSION.SDK_INT >= 30) {
645 mXmppConnectionService.getSystemService(ShortcutManager.class).pushDynamicShortcut(info.toShortcutInfo());
646 }
647 if (mXmppConnectionService.getAccounts().size() > 1) {
648 builder.setSubText(contact.getAccount().getJid().asBareJid().toString());
649 }
650 NotificationCompat.CallStyle style = NotificationCompat.CallStyle.forIncomingCall(
651 getPerson(contact),
652 createCallAction(
653 id.sessionId,
654 XmppConnectionService.ACTION_DISMISS_CALL,
655 102),
656 createPendingRtpSession(id, RtpSessionActivity.ACTION_ACCEPT_CALL, 103)
657 );
658 if (media.contains(Media.VIDEO)) {
659 style.setIsVideo(true);
660 builder.setSmallIcon(R.drawable.ic_videocam_24dp);
661 builder.setContentTitle(
662 mXmppConnectionService.getString(R.string.rtp_state_incoming_video_call));
663 } else {
664 style.setIsVideo(false);
665 builder.setSmallIcon(R.drawable.ic_call_24dp);
666 builder.setContentTitle(
667 mXmppConnectionService.getString(R.string.rtp_state_incoming_call));
668 }
669 builder.setStyle(style);
670 builder.setLargeIcon(FileBackend.drawDrawable(
671 mXmppConnectionService
672 .getAvatarService()
673 .get(contact, AvatarService.getSystemUiAvatarSize(mXmppConnectionService))));
674 final Uri systemAccount = contact.getSystemAccount();
675 if (systemAccount != null) {
676 builder.addPerson(systemAccount.toString());
677 }
678 if (!onlyAlertOnce) {
679 final var appSettings = new AppSettings(mXmppConnectionService);
680 final var ringtone = appSettings.getRingtone();
681 if (ringtone != null) {
682 builder.setSound(ringtone, AudioManager.STREAM_RING);
683 }
684 builder.setVibrate(CALL_PATTERN);
685 }
686 builder.setOnlyAlertOnce(onlyAlertOnce);
687 builder.setContentText(id.account.getRoster().getContact(id.with).getDisplayName());
688 builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
689 builder.setPriority(NotificationCompat.PRIORITY_HIGH);
690 builder.setCategory(NotificationCompat.CATEGORY_CALL);
691 final PendingIntent pendingIntent = createPendingRtpSession(id, Intent.ACTION_VIEW, 101);
692 builder.setFullScreenIntent(pendingIntent, true);
693 builder.setContentIntent(pendingIntent); // old androids need this?
694 builder.setOngoing(true);
695 builder.addAction(
696 new NotificationCompat.Action.Builder(
697 R.drawable.ic_call_end_24dp,
698 mXmppConnectionService.getString(R.string.dismiss_call),
699 createCallAction(
700 id.sessionId,
701 XmppConnectionService.ACTION_DISMISS_CALL,
702 102))
703 .build());
704 builder.addAction(
705 new NotificationCompat.Action.Builder(
706 R.drawable.ic_call_24dp,
707 mXmppConnectionService.getString(R.string.answer_call),
708 createPendingRtpSession(
709 id, RtpSessionActivity.ACTION_ACCEPT_CALL, 103))
710 .build());
711 modifyIncomingCall(builder, id.account);
712 final Notification notification = builder.build();
713 notification.audioAttributes = new AudioAttributes.Builder()
714 .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
715 .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
716 .build();
717 notification.flags = notification.flags | Notification.FLAG_INSISTENT;
718 notify(INCOMING_CALL_NOTIFICATION_ID, notification);
719 }
720
721 public Notification getOngoingCallNotification(
722 final XmppConnectionService.OngoingCall ongoingCall) {
723 final AbstractJingleConnection.Id id = ongoingCall.id;
724 final NotificationCompat.Builder builder =
725 new NotificationCompat.Builder(mXmppConnectionService, "ongoing_calls");
726 final Contact contact = id.account.getRoster().getContact(id.with);
727 NotificationCompat.CallStyle style = NotificationCompat.CallStyle.forOngoingCall(
728 getPerson(contact),
729 createCallAction(id.sessionId, XmppConnectionService.ACTION_END_CALL, 104)
730 );
731 if (ongoingCall.media.contains(Media.VIDEO)) {
732 style.setIsVideo(true);
733 builder.setSmallIcon(R.drawable.ic_videocam_24dp);
734 if (ongoingCall.reconnecting) {
735 builder.setContentTitle(
736 mXmppConnectionService.getString(R.string.reconnecting_video_call));
737 } else {
738 builder.setContentTitle(
739 mXmppConnectionService.getString(R.string.ongoing_video_call));
740 }
741 } else {
742 style.setIsVideo(false);
743 builder.setSmallIcon(R.drawable.ic_call_24dp);
744 if (ongoingCall.reconnecting) {
745 builder.setContentTitle(
746 mXmppConnectionService.getString(R.string.reconnecting_call));
747 } else {
748 builder.setContentTitle(mXmppConnectionService.getString(R.string.ongoing_call));
749 }
750 }
751 builder.setStyle(style);
752 builder.setContentText(contact.getDisplayName());
753 builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
754 builder.setPriority(NotificationCompat.PRIORITY_HIGH);
755 builder.setCategory(NotificationCompat.CATEGORY_CALL);
756 builder.setContentIntent(createPendingRtpSession(id, Intent.ACTION_VIEW, 101));
757 builder.setOngoing(true);
758 builder.addAction(
759 new NotificationCompat.Action.Builder(
760 R.drawable.ic_call_end_24dp,
761 mXmppConnectionService.getString(R.string.hang_up),
762 createCallAction(
763 id.sessionId, XmppConnectionService.ACTION_END_CALL, 104))
764 .build());
765 builder.setLocalOnly(true);
766 return builder.build();
767 }
768
769 private PendingIntent createPendingRtpSession(
770 final AbstractJingleConnection.Id id, final String action, final int requestCode) {
771 final Intent fullScreenIntent =
772 new Intent(mXmppConnectionService, RtpSessionActivity.class);
773 fullScreenIntent.setAction(action);
774 fullScreenIntent.putExtra(
775 RtpSessionActivity.EXTRA_ACCOUNT,
776 id.account.getJid().asBareJid().toEscapedString());
777 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_WITH, id.with.toEscapedString());
778 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.sessionId);
779 return PendingIntent.getActivity(
780 mXmppConnectionService,
781 requestCode,
782 fullScreenIntent,
783 s()
784 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
785 : PendingIntent.FLAG_UPDATE_CURRENT);
786 }
787
788 public void cancelIncomingCallNotification() {
789 cancel(INCOMING_CALL_NOTIFICATION_ID);
790 }
791
792 public boolean stopSoundAndVibration() {
793 final var jingleRtpConnection =
794 mXmppConnectionService.getJingleConnectionManager().getOngoingRtpConnection();
795 if (jingleRtpConnection == null) {
796 return false;
797 }
798 final var notificationManager = mXmppConnectionService.getSystemService(NotificationManager.class);
799 if (Iterables.any(
800 Arrays.asList(notificationManager.getActiveNotifications()),
801 n -> n.getId() == INCOMING_CALL_NOTIFICATION_ID)) {
802 Log.d(Config.LOGTAG, "stopping sound and vibration for incoming call notification");
803 showIncomingCallNotification(
804 jingleRtpConnection.getId(), jingleRtpConnection.getMedia(), true);
805 return true;
806 }
807 return false;
808 }
809
810 public static void cancelIncomingCallNotification(final Context context) {
811 final NotificationManagerCompat notificationManager =
812 NotificationManagerCompat.from(context);
813 try {
814 notificationManager.cancel(INCOMING_CALL_NOTIFICATION_ID);
815 } catch (RuntimeException e) {
816 Log.d(Config.LOGTAG, "unable to cancel incoming call notification after crash", e);
817 }
818 }
819
820 private void pushNow(final Message message) {
821 mXmppConnectionService.updateUnreadCountBadge();
822 if (!notifyMessage(message)) {
823 Log.d(
824 Config.LOGTAG,
825 message.getConversation().getAccount().getJid().asBareJid()
826 + ": suppressing notification because turned off");
827 return;
828 }
829 final boolean isScreenLocked = mXmppConnectionService.isScreenLocked();
830 if (this.mIsInForeground
831 && !isScreenLocked
832 && this.mOpenConversation == message.getConversation()) {
833 Log.d(
834 Config.LOGTAG,
835 message.getConversation().getAccount().getJid().asBareJid()
836 + ": suppressing notification because conversation is open");
837 return;
838 }
839 synchronized (notifications) {
840 pushToStack(message);
841 final Conversational conversation = message.getConversation();
842 final Account account = conversation.getAccount();
843 final boolean doNotify =
844 (!(this.mIsInForeground && this.mOpenConversation == null) || isScreenLocked)
845 && !account.inGracePeriod()
846 && !this.inMiniGracePeriod(account);
847 updateNotification(doNotify, Collections.singletonList(conversation.getUuid()));
848 }
849 }
850
851 private void pushMissedCall(final Message message) {
852 final Conversational conversation = message.getConversation();
853 final MissedCallsInfo info = mMissedCalls.get(conversation);
854 if (info == null) {
855 mMissedCalls.put(conversation, new MissedCallsInfo(message.getTimeSent()));
856 } else {
857 info.newMissedCall(message.getTimeSent());
858 }
859 }
860
861 public void pushMissedCallNow(final Message message) {
862 synchronized (mMissedCalls) {
863 pushMissedCall(message);
864 updateMissedCallNotifications(Collections.singleton(message.getConversation()));
865 }
866 }
867
868 public void clear(final Conversation conversation) {
869 clearMessages(conversation);
870 clearMissedCalls(conversation);
871 }
872
873 public void clearMessages() {
874 synchronized (notifications) {
875 for (ArrayList<Message> messages : notifications.values()) {
876 markAsReadIfHasDirectReply(messages);
877 markAsNotificationDismissed(messages);
878 }
879 notifications.clear();
880 updateNotification(false);
881 }
882 }
883
884 public void clearMessages(final Conversation conversation) {
885 synchronized (this.mBacklogMessageCounter) {
886 this.mBacklogMessageCounter.remove(conversation);
887 }
888 synchronized (notifications) {
889 markAsReadIfHasDirectReply(conversation);
890 markAsNotificationDismissed(conversation);
891 if (notifications.remove(conversation.getUuid()) != null) {
892 cancel(conversation.getUuid(), NOTIFICATION_ID);
893 updateNotification(false, null, true);
894 }
895 }
896 }
897
898 public void clearMissedCall(final Message message) {
899 synchronized (mMissedCalls) {
900 final Iterator<Map.Entry<Conversational, MissedCallsInfo>> iterator =
901 mMissedCalls.entrySet().iterator();
902 while (iterator.hasNext()) {
903 final Map.Entry<Conversational, MissedCallsInfo> entry = iterator.next();
904 final Conversational conversational = entry.getKey();
905 final MissedCallsInfo missedCallsInfo = entry.getValue();
906 if (conversational.getUuid().equals(message.getConversation().getUuid())) {
907 if (missedCallsInfo.removeMissedCall()) {
908 cancel(conversational.getUuid(), MISSED_CALL_NOTIFICATION_ID);
909 Log.d(
910 Config.LOGTAG,
911 conversational.getAccount().getJid().asBareJid()
912 + ": dismissed missed call because call was picked up on other device");
913 iterator.remove();
914 }
915 }
916 }
917 updateMissedCallNotifications(null);
918 }
919 }
920
921 public void clearMissedCalls() {
922 synchronized (mMissedCalls) {
923 for (final Conversational conversation : mMissedCalls.keySet()) {
924 cancel(conversation.getUuid(), MISSED_CALL_NOTIFICATION_ID);
925 }
926 mMissedCalls.clear();
927 updateMissedCallNotifications(null);
928 }
929 }
930
931 public void clearMissedCalls(final Conversation conversation) {
932 synchronized (mMissedCalls) {
933 if (mMissedCalls.remove(conversation) != null) {
934 cancel(conversation.getUuid(), MISSED_CALL_NOTIFICATION_ID);
935 updateMissedCallNotifications(null);
936 }
937 }
938 }
939
940 private void markAsReadIfHasDirectReply(final Conversation conversation) {
941 markAsReadIfHasDirectReply(notifications.get(conversation.getUuid()));
942 }
943
944 private void markAsReadIfHasDirectReply(final ArrayList<Message> messages) {
945 if (messages != null && !messages.isEmpty()) {
946 Message last = messages.get(messages.size() - 1);
947 if (last.getStatus() != Message.STATUS_RECEIVED) {
948 if (mXmppConnectionService.markRead((Conversation) last.getConversation(), false)) {
949 mXmppConnectionService.updateConversationUi();
950 }
951 }
952 }
953 }
954
955 private void markAsNotificationDismissed(final Conversation conversation) {
956 markAsNotificationDismissed(notifications.get(conversation.getUuid()));
957 }
958
959 private void markAsNotificationDismissed(final ArrayList<Message> messages) {
960 if (messages != null && !messages.isEmpty()) {
961 mXmppConnectionService.markNotificationDismissed(messages);
962 }
963 }
964
965 private void setNotificationColor(final Builder mBuilder, Account account) {
966 int color;
967 if (account != null && mXmppConnectionService.getAccounts().size() > 1) {
968 color = account.getColor(false);
969 } else {
970 TypedValue typedValue = new TypedValue();
971 mXmppConnectionService.getTheme().resolveAttribute(com.google.android.material.R.attr.colorPrimary, typedValue, true);
972 color = typedValue.data;
973 }
974 mBuilder.setColor(color);
975 }
976
977 public void updateNotification() {
978 synchronized (notifications) {
979 updateNotification(false);
980 }
981 }
982
983 private void updateNotification(final boolean notify) {
984 updateNotification(notify, null, false);
985 }
986
987 private void updateNotification(final boolean notify, final List<String> conversations) {
988 updateNotification(notify, conversations, false);
989 }
990
991 private void updateNotification(
992 final boolean notify, final List<String> conversations, final boolean summaryOnly) {
993 final SharedPreferences preferences =
994 PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
995
996 final boolean notifyOnlyOneChild =
997 notify
998 && conversations != null
999 && conversations.size()
1000 == 1; // if this check is changed to > 0 catchup messages will
1001 // create one notification per conversation
1002
1003 if (notifications.isEmpty()) {
1004 cancel(NOTIFICATION_ID);
1005 } else {
1006 if (notify) {
1007 this.markLastNotification();
1008 }
1009 final Builder mBuilder;
1010 if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
1011 final Account account = notifications.values().iterator().next().get(0).getConversation().getAccount();
1012 mBuilder = buildSingleConversations(notifications.values().iterator().next(), notify, isQuietHours(account));
1013 modifyForSoundVibrationAndLight(mBuilder, notify, preferences, account);
1014 notify(NOTIFICATION_ID, mBuilder.build());
1015 } else {
1016 mBuilder = buildMultipleConversation(notify, isQuietHours(null));
1017 if (notifyOnlyOneChild) {
1018 mBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
1019 }
1020 modifyForSoundVibrationAndLight(mBuilder, notify, preferences, null);
1021 if (!summaryOnly) {
1022 for (Map.Entry<String, ArrayList<Message>> entry : notifications.entrySet()) {
1023 String uuid = entry.getKey();
1024 final boolean notifyThis =
1025 notifyOnlyOneChild ? conversations.contains(uuid) : notify;
1026 final Account account = entry.getValue().isEmpty() ? null : entry.getValue().get(0).getConversation().getAccount();
1027 Builder singleBuilder =
1028 buildSingleConversations(entry.getValue(), notifyThis, isQuietHours(account));
1029 if (!notifyOnlyOneChild) {
1030 singleBuilder.setGroupAlertBehavior(
1031 NotificationCompat.GROUP_ALERT_SUMMARY);
1032 }
1033 modifyForSoundVibrationAndLight(singleBuilder, notifyThis, preferences, account);
1034 singleBuilder.setGroup(MESSAGES_GROUP);
1035 notify(entry.getKey(), NOTIFICATION_ID, singleBuilder.build());
1036 }
1037 }
1038 notify(NOTIFICATION_ID, mBuilder.build());
1039 }
1040 }
1041 }
1042
1043 private void updateMissedCallNotifications(final Set<Conversational> update) {
1044 if (mMissedCalls.isEmpty()) {
1045 cancel(MISSED_CALL_NOTIFICATION_ID);
1046 return;
1047 }
1048 if (mMissedCalls.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
1049 final Conversational conversation = mMissedCalls.keySet().iterator().next();
1050 final MissedCallsInfo info = mMissedCalls.values().iterator().next();
1051 final Notification notification = missedCall(conversation, info);
1052 notify(MISSED_CALL_NOTIFICATION_ID, notification);
1053 } else {
1054 final Notification summary = missedCallsSummary();
1055 notify(MISSED_CALL_NOTIFICATION_ID, summary);
1056 if (update != null) {
1057 for (final Conversational conversation : update) {
1058 final MissedCallsInfo info = mMissedCalls.get(conversation);
1059 if (info != null) {
1060 final Notification notification = missedCall(conversation, info);
1061 notify(conversation.getUuid(), MISSED_CALL_NOTIFICATION_ID, notification);
1062 }
1063 }
1064 }
1065 }
1066 }
1067
1068 private void modifyForSoundVibrationAndLight(
1069 Builder mBuilder, boolean notify, SharedPreferences preferences, Account account) {
1070 final Resources resources = mXmppConnectionService.getResources();
1071 final String ringtone =
1072 preferences.getString(
1073 AppSettings.NOTIFICATION_RINGTONE,
1074 resources.getString(R.string.notification_ringtone));
1075 final boolean vibrate =
1076 preferences.getBoolean(
1077 AppSettings.NOTIFICATION_VIBRATE,
1078 resources.getBoolean(R.bool.vibrate_on_notification));
1079 final boolean led =
1080 preferences.getBoolean(
1081 AppSettings.NOTIFICATION_LED, resources.getBoolean(R.bool.led));
1082 final boolean headsup =
1083 preferences.getBoolean(
1084 AppSettings.NOTIFICATION_HEADS_UP, resources.getBoolean(R.bool.headsup_notifications));
1085 if (notify && !isQuietHours(account)) {
1086 if (vibrate) {
1087 final int dat = 70;
1088 final long[] pattern = {0, 3 * dat, dat, dat};
1089 mBuilder.setVibrate(pattern);
1090 } else {
1091 mBuilder.setVibrate(new long[] {0});
1092 }
1093 Uri uri = Uri.parse(ringtone);
1094 try {
1095 mBuilder.setSound(fixRingtoneUri(uri));
1096 } catch (SecurityException e) {
1097 Log.d(Config.LOGTAG, "unable to use custom notification sound " + uri.toString());
1098 }
1099 } else {
1100 mBuilder.setLocalOnly(true);
1101 }
1102 mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
1103 mBuilder.setPriority(
1104 notify
1105 ? (headsup
1106 ? NotificationCompat.PRIORITY_HIGH
1107 : NotificationCompat.PRIORITY_DEFAULT)
1108 : NotificationCompat.PRIORITY_LOW);
1109 setNotificationColor(mBuilder, account);
1110 mBuilder.setDefaults(0);
1111 if (led) {
1112 mBuilder.setLights(LED_COLOR, 2000, 3000);
1113 }
1114 }
1115
1116 private void modifyIncomingCall(final Builder mBuilder, Account account) {
1117 mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
1118 setNotificationColor(mBuilder, account);
1119 if (Build.VERSION.SDK_INT >= 26 && account != null && mXmppConnectionService.getAccounts().size() > 1) {
1120 mBuilder.setColorized(true);
1121 }
1122 mBuilder.setLights(LED_COLOR, 2000, 3000);
1123 }
1124
1125 private Uri fixRingtoneUri(Uri uri) {
1126 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && "file".equals(uri.getScheme())) {
1127 final var file = new File(uri.getPath());
1128 return FileBackend.getUriForFile(mXmppConnectionService, file, file.getName());
1129 } else {
1130 return uri;
1131 }
1132 }
1133
1134 private Notification missedCallsSummary() {
1135 final Builder publicBuilder = buildMissedCallsSummary(true);
1136 final Builder builder = buildMissedCallsSummary(false);
1137 builder.setPublicVersion(publicBuilder.build());
1138 return builder.build();
1139 }
1140
1141 private Builder buildMissedCallsSummary(boolean publicVersion) {
1142 final Builder builder =
1143 new NotificationCompat.Builder(mXmppConnectionService, "missed_calls");
1144 int totalCalls = 0;
1145 final List<String> names = new ArrayList<>();
1146 long lastTime = 0;
1147 for (final Map.Entry<Conversational, MissedCallsInfo> entry : mMissedCalls.entrySet()) {
1148 final Conversational conversation = entry.getKey();
1149 final MissedCallsInfo missedCallsInfo = entry.getValue();
1150 names.add(conversation.getContact().getDisplayName());
1151 totalCalls += missedCallsInfo.getNumberOfCalls();
1152 lastTime = Math.max(lastTime, missedCallsInfo.getLastTime());
1153 }
1154 final String title =
1155 (totalCalls == 1)
1156 ? mXmppConnectionService.getString(R.string.missed_call)
1157 : (mMissedCalls.size() == 1)
1158 ? mXmppConnectionService
1159 .getResources()
1160 .getQuantityString(
1161 R.plurals.n_missed_calls, totalCalls, totalCalls)
1162 : mXmppConnectionService
1163 .getResources()
1164 .getQuantityString(
1165 R.plurals.n_missed_calls_from_m_contacts,
1166 mMissedCalls.size(),
1167 totalCalls,
1168 mMissedCalls.size());
1169 builder.setContentTitle(title);
1170 builder.setTicker(title);
1171 if (!publicVersion) {
1172 builder.setContentText(Joiner.on(", ").join(names));
1173 }
1174 builder.setSmallIcon(R.drawable.ic_call_missed_24db);
1175 builder.setGroupSummary(true);
1176 builder.setGroup(MISSED_CALLS_GROUP);
1177 builder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
1178 builder.setCategory(NotificationCompat.CATEGORY_CALL);
1179 builder.setWhen(lastTime);
1180 if (!mMissedCalls.isEmpty()) {
1181 final Conversational firstConversation = mMissedCalls.keySet().iterator().next();
1182 builder.setContentIntent(createContentIntent(firstConversation));
1183 }
1184 builder.setDeleteIntent(createMissedCallsDeleteIntent(null));
1185 modifyMissedCall(builder, null);
1186 return builder;
1187 }
1188
1189 private Notification missedCall(final Conversational conversation, final MissedCallsInfo info) {
1190 final Builder publicBuilder = buildMissedCall(conversation, info, true);
1191 final Builder builder = buildMissedCall(conversation, info, false);
1192 builder.setPublicVersion(publicBuilder.build());
1193 return builder.build();
1194 }
1195
1196 private Builder buildMissedCall(
1197 final Conversational conversation, final MissedCallsInfo info, boolean publicVersion) {
1198 final Builder builder =
1199 new NotificationCompat.Builder(mXmppConnectionService, isQuietHours(conversation.getAccount()) ? "quiet_hours" : "missed_calls");
1200 final String title =
1201 (info.getNumberOfCalls() == 1)
1202 ? mXmppConnectionService.getString(R.string.missed_call)
1203 : mXmppConnectionService
1204 .getResources()
1205 .getQuantityString(
1206 R.plurals.n_missed_calls,
1207 info.getNumberOfCalls(),
1208 info.getNumberOfCalls());
1209 builder.setContentTitle(title);
1210 if (mXmppConnectionService.getAccounts().size() > 1) {
1211 builder.setSubText(conversation.getAccount().getJid().asBareJid().toString());
1212 }
1213 final String name = conversation.getContact().getDisplayName();
1214 if (publicVersion) {
1215 builder.setTicker(title);
1216 } else {
1217 builder.setTicker(
1218 mXmppConnectionService
1219 .getResources()
1220 .getQuantityString(
1221 R.plurals.n_missed_calls_from_x,
1222 info.getNumberOfCalls(),
1223 info.getNumberOfCalls(),
1224 name));
1225 builder.setContentText(name);
1226 }
1227 builder.setSmallIcon(R.drawable.ic_call_missed_24db);
1228 builder.setGroup(MISSED_CALLS_GROUP);
1229 builder.setCategory(NotificationCompat.CATEGORY_CALL);
1230 builder.setWhen(info.getLastTime());
1231 builder.setContentIntent(createContentIntent(conversation));
1232 builder.setDeleteIntent(createMissedCallsDeleteIntent(conversation));
1233 if (!publicVersion && conversation instanceof Conversation) {
1234 builder.setLargeIcon(FileBackend.drawDrawable(
1235 mXmppConnectionService
1236 .getAvatarService()
1237 .get(
1238 (Conversation) conversation,
1239 AvatarService.getSystemUiAvatarSize(mXmppConnectionService))));
1240 }
1241 modifyMissedCall(builder, conversation.getAccount());
1242 return builder;
1243 }
1244
1245 private void modifyMissedCall(final Builder builder, Account account) {
1246 final SharedPreferences preferences =
1247 PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
1248 final Resources resources = mXmppConnectionService.getResources();
1249 final boolean led = preferences.getBoolean("led", resources.getBoolean(R.bool.led));
1250 if (led) {
1251 builder.setLights(LED_COLOR, 2000, 3000);
1252 }
1253 builder.setPriority(isQuietHours(account) ? NotificationCompat.PRIORITY_LOW : NotificationCompat.PRIORITY_HIGH);
1254 builder.setSound(null);
1255 setNotificationColor(builder, account);
1256 }
1257
1258 private Builder buildMultipleConversation(final boolean notify, final boolean quietHours) {
1259 final Builder mBuilder =
1260 new NotificationCompat.Builder(
1261 mXmppConnectionService,
1262 notify && !quietHours ? MESSAGES_NOTIFICATION_CHANNEL : "silent_messages");
1263 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
1264 style.setBigContentTitle(
1265 mXmppConnectionService
1266 .getResources()
1267 .getQuantityString(
1268 R.plurals.x_unread_conversations,
1269 notifications.size(),
1270 notifications.size()));
1271 final List<String> names = new ArrayList<>();
1272 Conversation conversation = null;
1273 for (final ArrayList<Message> messages : notifications.values()) {
1274 if (messages.isEmpty()) {
1275 continue;
1276 }
1277 conversation = (Conversation) messages.get(0).getConversation();
1278 final String name = conversation.getName().toString();
1279 SpannableString styledString;
1280 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
1281 int count = messages.size();
1282 styledString =
1283 new SpannableString(
1284 name
1285 + ": "
1286 + mXmppConnectionService
1287 .getResources()
1288 .getQuantityString(
1289 R.plurals.x_messages, count, count));
1290 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
1291 style.addLine(styledString);
1292 } else {
1293 styledString =
1294 new SpannableString(
1295 name
1296 + ": "
1297 + UIHelper.getMessagePreview(
1298 mXmppConnectionService, messages.get(0))
1299 .first);
1300 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
1301 style.addLine(styledString);
1302 }
1303 names.add(name);
1304 }
1305 final String contentTitle =
1306 mXmppConnectionService
1307 .getResources()
1308 .getQuantityString(
1309 R.plurals.x_unread_conversations,
1310 notifications.size(),
1311 notifications.size());
1312 mBuilder.setContentTitle(contentTitle);
1313 mBuilder.setTicker(contentTitle);
1314 mBuilder.setContentText(Joiner.on(", ").join(names));
1315 mBuilder.setStyle(style);
1316 if (conversation != null) {
1317 mBuilder.setContentIntent(createContentIntent(conversation));
1318 }
1319 mBuilder.setGroupSummary(true);
1320 mBuilder.setGroup(MESSAGES_GROUP);
1321 mBuilder.setDeleteIntent(createDeleteIntent(null));
1322 mBuilder.setSmallIcon(R.drawable.ic_notification);
1323 return mBuilder;
1324 }
1325
1326 private Builder buildSingleConversations(
1327 final ArrayList<Message> messages, final boolean notify, final boolean quietHours) {
1328 final var channel = notify && !quietHours ? MESSAGES_NOTIFICATION_CHANNEL : "silent_messages";
1329 final Builder notificationBuilder =
1330 new NotificationCompat.Builder(mXmppConnectionService, channel);
1331 if (messages.isEmpty()) {
1332 return notificationBuilder;
1333 }
1334 final Conversation conversation = (Conversation) messages.get(0).getConversation();
1335 notificationBuilder.setLargeIcon(FileBackend.drawDrawable(
1336 mXmppConnectionService
1337 .getAvatarService()
1338 .get(
1339 conversation,
1340 AvatarService.getSystemUiAvatarSize(mXmppConnectionService))));
1341 notificationBuilder.setContentTitle(conversation.getName());
1342 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
1343 int count = messages.size();
1344 notificationBuilder.setContentText(
1345 mXmppConnectionService
1346 .getResources()
1347 .getQuantityString(R.plurals.x_messages, count, count));
1348 } else {
1349 final Message message;
1350 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P
1351 && (message = getImage(messages)) != null) {
1352 modifyForImage(notificationBuilder, message, messages);
1353 } else {
1354 modifyForTextOnly(notificationBuilder, messages);
1355 }
1356 RemoteInput remoteInput =
1357 new RemoteInput.Builder("text_reply")
1358 .setLabel(UIHelper.getMessageHint(mXmppConnectionService, conversation))
1359 .build();
1360 PendingIntent markAsReadPendingIntent = createReadPendingIntent(conversation);
1361 NotificationCompat.Action markReadAction =
1362 new NotificationCompat.Action.Builder(
1363 R.drawable.ic_mark_chat_read_24dp,
1364 mXmppConnectionService.getString(R.string.mark_as_read),
1365 markAsReadPendingIntent)
1366 .setSemanticAction(
1367 NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ)
1368 .setShowsUserInterface(false)
1369 .build();
1370 final String replyLabel = mXmppConnectionService.getString(R.string.reply);
1371 final String lastMessageUuid = Iterables.getLast(messages).getUuid();
1372 final NotificationCompat.Action replyAction =
1373 new NotificationCompat.Action.Builder(
1374 R.drawable.ic_send_24dp,
1375 replyLabel,
1376 createReplyIntent(conversation, lastMessageUuid, false))
1377 .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY)
1378 .setShowsUserInterface(false)
1379 .addRemoteInput(remoteInput)
1380 .build();
1381 final NotificationCompat.Action wearReplyAction =
1382 new NotificationCompat.Action.Builder(
1383 R.drawable.ic_reply_24dp,
1384 replyLabel,
1385 createReplyIntent(conversation, lastMessageUuid, true))
1386 .addRemoteInput(remoteInput)
1387 .build();
1388 notificationBuilder.extend(
1389 new NotificationCompat.WearableExtender().addAction(wearReplyAction));
1390 int addedActionsCount = 1;
1391 notificationBuilder.addAction(markReadAction);
1392 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1393 notificationBuilder.addAction(replyAction);
1394 ++addedActionsCount;
1395 }
1396
1397 if (displaySnoozeAction(messages)) {
1398 String label = mXmppConnectionService.getString(R.string.snooze);
1399 PendingIntent pendingSnoozeIntent = createSnoozeIntent(conversation);
1400 NotificationCompat.Action snoozeAction =
1401 new NotificationCompat.Action.Builder(
1402 R.drawable.ic_notifications_paused_24dp,
1403 label,
1404 pendingSnoozeIntent)
1405 .build();
1406 notificationBuilder.addAction(snoozeAction);
1407 ++addedActionsCount;
1408 }
1409 if (addedActionsCount < 3) {
1410 final Message firstLocationMessage = getFirstLocationMessage(messages);
1411 if (firstLocationMessage != null) {
1412 final PendingIntent pendingShowLocationIntent =
1413 createShowLocationIntent(firstLocationMessage);
1414 if (pendingShowLocationIntent != null) {
1415 final String label =
1416 mXmppConnectionService
1417 .getResources()
1418 .getString(R.string.show_location);
1419 NotificationCompat.Action locationAction =
1420 new NotificationCompat.Action.Builder(
1421 R.drawable.ic_location_pin_24dp,
1422 label,
1423 pendingShowLocationIntent)
1424 .build();
1425 notificationBuilder.addAction(locationAction);
1426 ++addedActionsCount;
1427 }
1428 }
1429 }
1430 if (addedActionsCount < 3) {
1431 Message firstDownloadableMessage = getFirstDownloadableMessage(messages);
1432 if (firstDownloadableMessage != null) {
1433 String label =
1434 mXmppConnectionService
1435 .getResources()
1436 .getString(
1437 R.string.download_x_file,
1438 UIHelper.getFileDescriptionString(
1439 mXmppConnectionService,
1440 firstDownloadableMessage));
1441 PendingIntent pendingDownloadIntent =
1442 createDownloadIntent(firstDownloadableMessage);
1443 NotificationCompat.Action downloadAction =
1444 new NotificationCompat.Action.Builder(
1445 R.drawable.ic_download_24dp,
1446 label,
1447 pendingDownloadIntent)
1448 .build();
1449 notificationBuilder.addAction(downloadAction);
1450 ++addedActionsCount;
1451 }
1452 }
1453 }
1454 final ShortcutInfoCompat info;
1455 if (conversation.getMode() == Conversation.MODE_SINGLE) {
1456 final Contact contact = conversation.getContact();
1457 final Uri systemAccount = contact.getSystemAccount();
1458 if (systemAccount != null) {
1459 notificationBuilder.addPerson(systemAccount.toString());
1460 }
1461 info = mXmppConnectionService.getShortcutService().getShortcutInfoCompat(contact);
1462 } else {
1463 info =
1464 mXmppConnectionService
1465 .getShortcutService()
1466 .getShortcutInfoCompat(conversation.getMucOptions());
1467 }
1468 notificationBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
1469 notificationBuilder.setSmallIcon(R.drawable.ic_notification);
1470 notificationBuilder.setDeleteIntent(createDeleteIntent(conversation));
1471 notificationBuilder.setContentIntent(createContentIntent(conversation));
1472 if (mXmppConnectionService.getAccounts().size() > 1) {
1473 notificationBuilder.setSubText(conversation.getAccount().getJid().asBareJid().toString());
1474 }
1475 if (channel.equals(MESSAGES_NOTIFICATION_CHANNEL)) {
1476 // when do not want 'customized' notifications for silent notifications in their
1477 // respective channels
1478 notificationBuilder.setShortcutInfo(info);
1479 if (Build.VERSION.SDK_INT >= 30) {
1480 mXmppConnectionService
1481 .getSystemService(ShortcutManager.class)
1482 .pushDynamicShortcut(info.toShortcutInfo());
1483 // mBuilder.setBubbleMetadata(new NotificationCompat.BubbleMetadata.Builder(info.getId()).build());
1484 }
1485 }
1486 return notificationBuilder;
1487 }
1488
1489 private void modifyForImage(
1490 final Builder builder, final Message message, final ArrayList<Message> messages) {
1491 try {
1492 final Bitmap bitmap = mXmppConnectionService.getFileBackend().getThumbnailBitmap(message, mXmppConnectionService.getResources(), getPixel(288));
1493 final ArrayList<Message> tmp = new ArrayList<>();
1494 for (final Message msg : messages) {
1495 if (msg.getType() == Message.TYPE_TEXT && msg.getTransferable() == null) {
1496 tmp.add(msg);
1497 }
1498 }
1499 final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
1500 bigPictureStyle.bigPicture(bitmap);
1501 if (tmp.size() > 0) {
1502 CharSequence text = getMergedBodies(tmp);
1503 bigPictureStyle.setSummaryText(text);
1504 builder.setContentText(text);
1505 builder.setTicker(text);
1506 } else {
1507 final String description =
1508 UIHelper.getFileDescriptionString(mXmppConnectionService, message);
1509 builder.setContentText(description);
1510 builder.setTicker(description);
1511 }
1512 builder.setStyle(bigPictureStyle);
1513 } catch (final IOException e) {
1514 modifyForTextOnly(builder, messages);
1515 }
1516 }
1517
1518 private Person getPerson(Message message) {
1519 final Contact contact = message.getContact();
1520 final Person.Builder builder = new Person.Builder();
1521 if (contact != null) {
1522 builder.setName(contact.getDisplayName());
1523 final Uri uri = contact.getSystemAccount();
1524 if (uri != null) {
1525 builder.setUri(uri.toString());
1526 }
1527 } else {
1528 builder.setName(UIHelper.getMessageDisplayName(message));
1529 }
1530 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
1531 final Jid jid = contact == null ? message.getCounterpart() : contact.getJid();
1532 builder.setKey(jid.toString());
1533 final Conversation c = mXmppConnectionService.find(message.getConversation().getAccount(), jid);
1534 if (c != null) {
1535 builder.setImportant(c.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false));
1536 }
1537 builder.setIcon(
1538 IconCompat.createWithBitmap(FileBackend.drawDrawable(
1539 mXmppConnectionService
1540 .getAvatarService()
1541 .get(
1542 message,
1543 AvatarService.getSystemUiAvatarSize(
1544 mXmppConnectionService),
1545 false))));
1546 }
1547 return builder.build();
1548 }
1549
1550 private Person getPerson(Contact contact) {
1551 final Person.Builder builder = new Person.Builder();
1552 builder.setName(contact.getDisplayName());
1553 final Uri uri = contact.getSystemAccount();
1554 if (uri != null) {
1555 builder.setUri(uri.toString());
1556 }
1557 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
1558 final Jid jid = contact.getJid();
1559 builder.setKey(jid.toString());
1560 final Conversation c = mXmppConnectionService.find(contact.getAccount(), jid);
1561 if (c != null) {
1562 builder.setImportant(c.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false));
1563 }
1564 builder.setIcon(
1565 IconCompat.createWithBitmap(FileBackend.drawDrawable(
1566 mXmppConnectionService
1567 .getAvatarService()
1568 .get(
1569 contact,
1570 AvatarService.getSystemUiAvatarSize(
1571 mXmppConnectionService),
1572 false))));
1573 }
1574 return builder.build();
1575 }
1576
1577 private void modifyForTextOnly(final Builder builder, final ArrayList<Message> messages) {
1578 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1579 final Conversation conversation = (Conversation) messages.get(0).getConversation();
1580 final Person.Builder meBuilder =
1581 new Person.Builder().setName(mXmppConnectionService.getString(R.string.me));
1582 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
1583 meBuilder.setIcon(
1584 IconCompat.createWithBitmap(FileBackend.drawDrawable(
1585 mXmppConnectionService
1586 .getAvatarService()
1587 .get(
1588 conversation.getAccount(),
1589 AvatarService.getSystemUiAvatarSize(
1590 mXmppConnectionService)))));
1591 }
1592 final Person me = meBuilder.build();
1593 NotificationCompat.MessagingStyle messagingStyle =
1594 new NotificationCompat.MessagingStyle(me);
1595 final boolean multiple = conversation.getMode() == Conversation.MODE_MULTI || messages.get(0).getTrueCounterpart() != null;
1596 if (multiple) {
1597 messagingStyle.setConversationTitle(conversation.getName());
1598 }
1599 for (Message message : messages) {
1600 final Person sender =
1601 message.getStatus() == Message.STATUS_RECEIVED ? getPerson(message) : null;
1602 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && isImageMessage(message)) {
1603 final Uri dataUri =
1604 FileBackend.getMediaUri(
1605 mXmppConnectionService,
1606 mXmppConnectionService.getFileBackend().getFile(message));
1607 NotificationCompat.MessagingStyle.Message imageMessage =
1608 new NotificationCompat.MessagingStyle.Message(
1609 UIHelper.getMessagePreview(mXmppConnectionService, message)
1610 .first,
1611 message.getTimeSent(),
1612 sender);
1613 if (dataUri != null) {
1614 imageMessage.setData(message.getMimeType(), dataUri);
1615 }
1616 messagingStyle.addMessage(imageMessage);
1617 } else {
1618 messagingStyle.addMessage(
1619 UIHelper.getMessagePreview(mXmppConnectionService, message).first,
1620 message.getTimeSent(),
1621 sender);
1622 }
1623 }
1624 messagingStyle.setGroupConversation(multiple);
1625 builder.setStyle(messagingStyle);
1626 } else {
1627 if (messages.get(0).getConversation().getMode() == Conversation.MODE_SINGLE && messages.get(0).getTrueCounterpart() == null) {
1628 builder.setStyle(
1629 new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
1630 final CharSequence preview =
1631 UIHelper.getMessagePreview(
1632 mXmppConnectionService, messages.get(messages.size() - 1))
1633 .first;
1634 builder.setContentText(preview);
1635 builder.setTicker(preview);
1636 builder.setNumber(messages.size());
1637 } else {
1638 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
1639 SpannableString styledString;
1640 for (Message message : messages) {
1641 final String name = UIHelper.getMessageDisplayName(message);
1642 styledString = new SpannableString(name + ": " + message.getBody());
1643 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
1644 style.addLine(styledString);
1645 }
1646 builder.setStyle(style);
1647 int count = messages.size();
1648 if (count == 1) {
1649 final String name = UIHelper.getMessageDisplayName(messages.get(0));
1650 styledString = new SpannableString(name + ": " + messages.get(0).getBody());
1651 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
1652 builder.setContentText(styledString);
1653 builder.setTicker(styledString);
1654 } else {
1655 final String text =
1656 mXmppConnectionService
1657 .getResources()
1658 .getQuantityString(R.plurals.x_messages, count, count);
1659 builder.setContentText(text);
1660 builder.setTicker(text);
1661 }
1662 }
1663 }
1664 }
1665
1666 private Message getImage(final Iterable<Message> messages) {
1667 Message image = null;
1668 for (final Message message : messages) {
1669 if (message.getStatus() != Message.STATUS_RECEIVED) {
1670 return null;
1671 }
1672 if (isImageMessage(message)) {
1673 image = message;
1674 }
1675 }
1676 return image;
1677 }
1678
1679 private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
1680 for (final Message message : messages) {
1681 if (message.getTransferable() != null
1682 || (message.getType() == Message.TYPE_TEXT && message.treatAsDownloadable())) {
1683 return message;
1684 }
1685 }
1686 return null;
1687 }
1688
1689 private Message getFirstLocationMessage(final Iterable<Message> messages) {
1690 for (final Message message : messages) {
1691 if (message.isGeoUri()) {
1692 return message;
1693 }
1694 }
1695 return null;
1696 }
1697
1698 private CharSequence getMergedBodies(final ArrayList<Message> messages) {
1699 final StringBuilder text = new StringBuilder();
1700 for (Message message : messages) {
1701 if (text.length() != 0) {
1702 text.append("\n");
1703 }
1704 text.append(UIHelper.getMessagePreview(mXmppConnectionService, message).first);
1705 }
1706 return text.toString();
1707 }
1708
1709 private PendingIntent createShowLocationIntent(final Message message) {
1710 Iterable<Intent> intents =
1711 GeoHelper.createGeoIntentsFromMessage(mXmppConnectionService, message);
1712 for (final Intent intent : intents) {
1713 if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
1714 return PendingIntent.getActivity(
1715 mXmppConnectionService,
1716 generateRequestCode(message.getConversation(), 18),
1717 intent,
1718 s()
1719 ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1720 : PendingIntent.FLAG_UPDATE_CURRENT);
1721 }
1722 }
1723 return null;
1724 }
1725
1726 private PendingIntent createContentIntent(
1727 final String conversationUuid, final String downloadMessageUuid) {
1728 final Intent viewConversationIntent =
1729 new Intent(mXmppConnectionService, ConversationsActivity.class);
1730 viewConversationIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
1731 viewConversationIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversationUuid);
1732 if (downloadMessageUuid != null) {
1733 viewConversationIntent.putExtra(
1734 ConversationsActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
1735 return PendingIntent.getActivity(
1736 mXmppConnectionService,
1737 generateRequestCode(conversationUuid, 8),
1738 viewConversationIntent,
1739 s()
1740 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1741 : PendingIntent.FLAG_UPDATE_CURRENT);
1742 } else {
1743 return PendingIntent.getActivity(
1744 mXmppConnectionService,
1745 generateRequestCode(conversationUuid, 10),
1746 viewConversationIntent,
1747 s()
1748 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1749 : PendingIntent.FLAG_UPDATE_CURRENT);
1750 }
1751 }
1752
1753 private int generateRequestCode(String uuid, int actionId) {
1754 return (actionId * NOTIFICATION_ID_MULTIPLIER)
1755 + (uuid.hashCode() % NOTIFICATION_ID_MULTIPLIER);
1756 }
1757
1758 private int generateRequestCode(Conversational conversation, int actionId) {
1759 return generateRequestCode(conversation.getUuid(), actionId);
1760 }
1761
1762 private PendingIntent createDownloadIntent(final Message message) {
1763 return createContentIntent(message.getConversationUuid(), message.getUuid());
1764 }
1765
1766 private PendingIntent createContentIntent(final Conversational conversation) {
1767 return createContentIntent(conversation.getUuid(), null);
1768 }
1769
1770 private PendingIntent createDeleteIntent(final Conversation conversation) {
1771 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1772 intent.setAction(XmppConnectionService.ACTION_CLEAR_MESSAGE_NOTIFICATION);
1773 if (conversation != null) {
1774 intent.putExtra("uuid", conversation.getUuid());
1775 return PendingIntent.getService(
1776 mXmppConnectionService,
1777 generateRequestCode(conversation, 20),
1778 intent,
1779 s()
1780 ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1781 : PendingIntent.FLAG_UPDATE_CURRENT);
1782 }
1783 return PendingIntent.getService(
1784 mXmppConnectionService,
1785 0,
1786 intent,
1787 s()
1788 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1789 : PendingIntent.FLAG_UPDATE_CURRENT);
1790 }
1791
1792 private PendingIntent createMissedCallsDeleteIntent(final Conversational conversation) {
1793 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1794 intent.setAction(XmppConnectionService.ACTION_CLEAR_MISSED_CALL_NOTIFICATION);
1795 if (conversation != null) {
1796 intent.putExtra("uuid", conversation.getUuid());
1797 return PendingIntent.getService(
1798 mXmppConnectionService,
1799 generateRequestCode(conversation, 21),
1800 intent,
1801 s()
1802 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1803 : PendingIntent.FLAG_UPDATE_CURRENT);
1804 }
1805 return PendingIntent.getService(
1806 mXmppConnectionService,
1807 1,
1808 intent,
1809 s()
1810 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1811 : PendingIntent.FLAG_UPDATE_CURRENT);
1812 }
1813
1814 private PendingIntent createReplyIntent(
1815 final Conversation conversation,
1816 final String lastMessageUuid,
1817 final boolean dismissAfterReply) {
1818 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1819 intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
1820 intent.putExtra("uuid", conversation.getUuid());
1821 intent.putExtra("dismiss_notification", dismissAfterReply);
1822 intent.putExtra("last_message_uuid", lastMessageUuid);
1823 final int id = generateRequestCode(conversation, dismissAfterReply ? 12 : 14);
1824 return PendingIntent.getService(
1825 mXmppConnectionService,
1826 id,
1827 intent,
1828 s()
1829 ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1830 : PendingIntent.FLAG_UPDATE_CURRENT);
1831 }
1832
1833 private PendingIntent createReadPendingIntent(Conversation conversation) {
1834 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1835 intent.setAction(XmppConnectionService.ACTION_MARK_AS_READ);
1836 intent.putExtra("uuid", conversation.getUuid());
1837 intent.setPackage(mXmppConnectionService.getPackageName());
1838 return PendingIntent.getService(
1839 mXmppConnectionService,
1840 generateRequestCode(conversation, 16),
1841 intent,
1842 s()
1843 ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1844 : PendingIntent.FLAG_UPDATE_CURRENT);
1845 }
1846
1847 private PendingIntent createCallAction(String sessionId, final String action, int requestCode) {
1848 return pendingServiceIntent(
1849 mXmppConnectionService,
1850 action,
1851 requestCode,
1852 ImmutableMap.of(RtpSessionActivity.EXTRA_SESSION_ID, sessionId));
1853 }
1854
1855 private PendingIntent createSnoozeIntent(final Conversation conversation) {
1856 return pendingServiceIntent(
1857 mXmppConnectionService,
1858 XmppConnectionService.ACTION_SNOOZE,
1859 generateRequestCode(conversation, 22),
1860 ImmutableMap.of("uuid", conversation.getUuid()));
1861 }
1862
1863 private static PendingIntent pendingServiceIntent(
1864 final Context context, final String action, final int requestCode) {
1865 return pendingServiceIntent(context, action, requestCode, ImmutableMap.of());
1866 }
1867
1868 private static PendingIntent pendingServiceIntent(
1869 final Context context,
1870 final String action,
1871 final int requestCode,
1872 final Map<String, String> extras) {
1873 final Intent intent = new Intent(context, XmppConnectionService.class);
1874 intent.setAction(action);
1875 for (final Map.Entry<String, String> entry : extras.entrySet()) {
1876 intent.putExtra(entry.getKey(), entry.getValue());
1877 }
1878 return PendingIntent.getService(
1879 context,
1880 requestCode,
1881 intent,
1882 s()
1883 ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1884 : PendingIntent.FLAG_UPDATE_CURRENT);
1885 }
1886
1887 private boolean wasHighlightedOrPrivate(final Message message) {
1888 if (message.getConversation() instanceof Conversation) {
1889 Conversation conversation = (Conversation) message.getConversation();
1890 final MucOptions.User sender = conversation.getMucOptions().findUserByFullJid(message.getCounterpart());
1891 final boolean muted = message.getStatus() == Message.STATUS_RECEIVED && mXmppConnectionService.isMucUserMuted(new MucOptions.User(null, conversation.getJid(), message.getOccupantId(), null, null));
1892 if (muted) return false;
1893 if (sender != null && sender.getAffiliation().ranks(MucOptions.Affiliation.MEMBER) && message.isAttention()) {
1894 return true;
1895 }
1896 final String nick = conversation.getMucOptions().getActualNick();
1897 final Pattern highlight = generateNickHighlightPattern(nick);
1898 final String name = conversation.getMucOptions().getActualName();
1899 final Pattern highlightName = generateNickHighlightPattern(name);
1900 if (message.getBody() == null || (nick == null && name == null)) {
1901 return false;
1902 }
1903 final Matcher m = highlight.matcher(message.getBody(true));
1904 final Matcher m2 = highlightName.matcher(message.getBody(true));
1905 return (m.find() || m2.find() || message.isPrivateMessage());
1906 } else {
1907 return false;
1908 }
1909 }
1910
1911 private boolean wasReplyToMe(final Message message) {
1912 final Element reply = message.getReply();
1913 if (reply == null || reply.getAttribute("id") == null) return false;
1914 final Message parent = ((Conversation) message.getConversation()).findMessageWithRemoteIdAndCounterpart(reply.getAttribute("id"), null);
1915 if (parent == null) return false;
1916 return parent.getStatus() >= Message.STATUS_SEND;
1917 }
1918
1919 public void setOpenConversation(final Conversation conversation) {
1920 this.mOpenConversation = conversation;
1921 }
1922
1923 public void setIsInForeground(final boolean foreground) {
1924 this.mIsInForeground = foreground;
1925 }
1926
1927 private int getPixel(final int dp) {
1928 final DisplayMetrics metrics = mXmppConnectionService.getResources().getDisplayMetrics();
1929 return ((int) (dp * metrics.density));
1930 }
1931
1932 private void markLastNotification() {
1933 this.mLastNotification = SystemClock.elapsedRealtime();
1934 }
1935
1936 private boolean inMiniGracePeriod(final Account account) {
1937 final int miniGrace =
1938 account.getStatus() == Account.State.ONLINE
1939 ? Config.MINI_GRACE_PERIOD
1940 : Config.MINI_GRACE_PERIOD * 2;
1941 return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
1942 }
1943
1944 Notification createForegroundNotification() {
1945 final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1946 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.app_name));
1947 final List<Account> accounts = mXmppConnectionService.getAccounts();
1948 final int enabled;
1949 final int connected;
1950 if (accounts == null) {
1951 enabled = 0;
1952 connected = 0;
1953 } else {
1954 enabled = Iterables.size(Iterables.filter(accounts, Account::isEnabled));
1955 connected = Iterables.size(Iterables.filter(accounts, Account::isOnlineAndConnected));
1956 }
1957 mBuilder.setContentText(
1958 mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
1959 final PendingIntent openIntent = createOpenConversationsIntent();
1960 if (openIntent != null) {
1961 mBuilder.setContentIntent(openIntent);
1962 }
1963 mBuilder.setWhen(0)
1964 .setPriority(Notification.PRIORITY_MIN)
1965 .setSmallIcon(connected >= enabled ? R.drawable.ic_link_24dp : R.drawable.ic_link_off_24dp)
1966 .setLocalOnly(true);
1967
1968 if (Compatibility.runsTwentySix()) {
1969 mBuilder.setChannelId("foreground");
1970 mBuilder.addAction(
1971 R.drawable.ic_logout_24dp,
1972 mXmppConnectionService.getString(R.string.log_out),
1973 pendingServiceIntent(
1974 mXmppConnectionService,
1975 XmppConnectionService.ACTION_TEMPORARILY_DISABLE,
1976 87));
1977 mBuilder.addAction(
1978 R.drawable.ic_notifications_off_24dp,
1979 mXmppConnectionService.getString(R.string.hide_notification),
1980 pendingNotificationSettingsIntent(mXmppConnectionService));
1981 }
1982
1983 return mBuilder.build();
1984 }
1985
1986 @RequiresApi(api = Build.VERSION_CODES.O)
1987 private static PendingIntent pendingNotificationSettingsIntent(final Context context) {
1988 final Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
1989 intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
1990 intent.putExtra(Settings.EXTRA_CHANNEL_ID, "foreground");
1991 return PendingIntent.getActivity(
1992 context,
1993 89,
1994 intent,
1995 s()
1996 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1997 : PendingIntent.FLAG_UPDATE_CURRENT);
1998 }
1999
2000 private PendingIntent createOpenConversationsIntent() {
2001 try {
2002 return PendingIntent.getActivity(
2003 mXmppConnectionService,
2004 0,
2005 new Intent(mXmppConnectionService, ConversationsActivity.class),
2006 s()
2007 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
2008 : PendingIntent.FLAG_UPDATE_CURRENT);
2009 } catch (RuntimeException e) {
2010 return null;
2011 }
2012 }
2013
2014 void updateErrorNotification() {
2015 if (Config.SUPPRESS_ERROR_NOTIFICATION) {
2016 cancel(ERROR_NOTIFICATION_ID);
2017 return;
2018 }
2019 final boolean showAllErrors = QuickConversationsService.isConversations();
2020 final List<Account> errors = new ArrayList<>();
2021 boolean torNotAvailable = false;
2022 for (final Account account : mXmppConnectionService.getAccounts()) {
2023 if (account.hasErrorStatus()
2024 && account.showErrorNotification()
2025 && (showAllErrors
2026 || account.getLastErrorStatus() == Account.State.UNAUTHORIZED)) {
2027 errors.add(account);
2028 torNotAvailable |= account.getStatus() == Account.State.TOR_NOT_AVAILABLE;
2029 }
2030 }
2031 if (mXmppConnectionService.foregroundNotificationNeedsUpdatingWhenErrorStateChanges()) {
2032 try {
2033 notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
2034 } catch (final RuntimeException e) {
2035 Log.d(
2036 Config.LOGTAG,
2037 "not refreshing foreground service notification because service has died",
2038 e);
2039 }
2040 }
2041 final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
2042 if (errors.isEmpty()) {
2043 cancel(ERROR_NOTIFICATION_ID);
2044 return;
2045 } else if (errors.size() == 1) {
2046 mBuilder.setContentTitle(
2047 mXmppConnectionService.getString(R.string.problem_connecting_to_account));
2048 mBuilder.setContentText(errors.get(0).getJid().asBareJid().toEscapedString());
2049 } else {
2050 mBuilder.setContentTitle(
2051 mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
2052 mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
2053 }
2054 try {
2055 mBuilder.addAction(
2056 R.drawable.ic_autorenew_24dp,
2057 mXmppConnectionService.getString(R.string.try_again),
2058 pendingServiceIntent(
2059 mXmppConnectionService, XmppConnectionService.ACTION_TRY_AGAIN, 45));
2060 mBuilder.setDeleteIntent(
2061 pendingServiceIntent(
2062 mXmppConnectionService,
2063 XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS,
2064 69));
2065 } catch (final RuntimeException e) {
2066 Log.d(
2067 Config.LOGTAG,
2068 "not including some actions in error notification because service has died",
2069 e);
2070 }
2071 if (torNotAvailable) {
2072 if (TorServiceUtils.isOrbotInstalled(mXmppConnectionService)) {
2073 mBuilder.addAction(
2074 R.drawable.ic_play_circle_24dp,
2075 mXmppConnectionService.getString(R.string.start_orbot),
2076 PendingIntent.getActivity(
2077 mXmppConnectionService,
2078 147,
2079 TorServiceUtils.LAUNCH_INTENT,
2080 s()
2081 ? PendingIntent.FLAG_IMMUTABLE
2082 | PendingIntent.FLAG_UPDATE_CURRENT
2083 : PendingIntent.FLAG_UPDATE_CURRENT));
2084 } else {
2085 mBuilder.addAction(
2086 R.drawable.ic_download_24dp,
2087 mXmppConnectionService.getString(R.string.install_orbot),
2088 PendingIntent.getActivity(
2089 mXmppConnectionService,
2090 146,
2091 TorServiceUtils.INSTALL_INTENT,
2092 s()
2093 ? PendingIntent.FLAG_IMMUTABLE
2094 | PendingIntent.FLAG_UPDATE_CURRENT
2095 : PendingIntent.FLAG_UPDATE_CURRENT));
2096 }
2097 }
2098 mBuilder.setVisibility(Notification.VISIBILITY_PRIVATE);
2099 mBuilder.setSmallIcon(R.drawable.ic_warning_24dp);
2100 mBuilder.setLocalOnly(true);
2101 mBuilder.setPriority(Notification.PRIORITY_LOW);
2102 final Intent intent;
2103 if (AccountUtils.MANAGE_ACCOUNT_ACTIVITY != null) {
2104 intent = new Intent(mXmppConnectionService, AccountUtils.MANAGE_ACCOUNT_ACTIVITY);
2105 } else {
2106 intent = new Intent(mXmppConnectionService, EditAccountActivity.class);
2107 intent.putExtra("jid", errors.get(0).getJid().asBareJid().toEscapedString());
2108 intent.putExtra(EditAccountActivity.EXTRA_OPENED_FROM_NOTIFICATION, true);
2109 }
2110 mBuilder.setContentIntent(
2111 PendingIntent.getActivity(
2112 mXmppConnectionService,
2113 145,
2114 intent,
2115 s()
2116 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
2117 : PendingIntent.FLAG_UPDATE_CURRENT));
2118 if (Compatibility.runsTwentySix()) {
2119 mBuilder.setChannelId("error");
2120 }
2121 notify(ERROR_NOTIFICATION_ID, mBuilder.build());
2122 }
2123
2124 void updateFileAddingNotification(final int current, final Message message) {
2125
2126 final Notification notification = videoTranscoding(current, message);
2127 notify(ONGOING_VIDEO_TRANSCODING_NOTIFICATION_ID, notification);
2128 }
2129
2130 private Notification videoTranscoding(final int current, @Nullable final Message message) {
2131 final Notification.Builder builder = new Notification.Builder(mXmppConnectionService);
2132 builder.setContentTitle(mXmppConnectionService.getString(R.string.transcoding_video));
2133 if (current >= 0) {
2134 builder.setProgress(100, current, false);
2135 } else {
2136 builder.setProgress(100, 0, true);
2137 }
2138 builder.setSmallIcon(R.drawable.ic_hourglass_top_24dp);
2139 if (message != null) {
2140 builder.setContentIntent(createContentIntent(message.getConversation()));
2141 }
2142 builder.setOngoing(true);
2143 if (Compatibility.runsTwentySix()) {
2144 builder.setChannelId("compression");
2145 }
2146 return builder.build();
2147 }
2148
2149 public Notification getIndeterminateVideoTranscoding() {
2150 return videoTranscoding(-1, null);
2151 }
2152
2153 private void notify(final String tag, final int id, final Notification notification) {
2154 if (ActivityCompat.checkSelfPermission(
2155 mXmppConnectionService, Manifest.permission.POST_NOTIFICATIONS)
2156 != PackageManager.PERMISSION_GRANTED) {
2157 return;
2158 }
2159 final var notificationManager =
2160 mXmppConnectionService.getSystemService(NotificationManager.class);
2161 try {
2162 notificationManager.notify(tag, id, notification);
2163 } catch (final RuntimeException e) {
2164 Log.d(Config.LOGTAG, "unable to make notification", e);
2165 }
2166 }
2167
2168 public void notify(final int id, final Notification notification) {
2169 if (ActivityCompat.checkSelfPermission(
2170 mXmppConnectionService, Manifest.permission.POST_NOTIFICATIONS)
2171 != PackageManager.PERMISSION_GRANTED) {
2172 return;
2173 }
2174 final var notificationManager =
2175 mXmppConnectionService.getSystemService(NotificationManager.class);
2176 try {
2177 notificationManager.notify(id, notification);
2178 } catch (final RuntimeException e) {
2179 Log.d(Config.LOGTAG, "unable to make notification", e);
2180 }
2181 }
2182
2183 public void cancel(final int id) {
2184 final NotificationManagerCompat notificationManager =
2185 NotificationManagerCompat.from(mXmppConnectionService);
2186 try {
2187 notificationManager.cancel(id);
2188 } catch (RuntimeException e) {
2189 Log.d(Config.LOGTAG, "unable to cancel notification", e);
2190 }
2191 }
2192
2193 private void cancel(String tag, int id) {
2194 final NotificationManagerCompat notificationManager =
2195 NotificationManagerCompat.from(mXmppConnectionService);
2196 try {
2197 notificationManager.cancel(tag, id);
2198 } catch (RuntimeException e) {
2199 Log.d(Config.LOGTAG, "unable to cancel notification", e);
2200 }
2201 }
2202
2203 private static class MissedCallsInfo {
2204 private int numberOfCalls;
2205 private long lastTime;
2206
2207 MissedCallsInfo(final long time) {
2208 numberOfCalls = 1;
2209 lastTime = time;
2210 }
2211
2212 public void newMissedCall(final long time) {
2213 ++numberOfCalls;
2214 lastTime = time;
2215 }
2216
2217 public boolean removeMissedCall() {
2218 --numberOfCalls;
2219 return numberOfCalls <= 0;
2220 }
2221
2222 public int getNumberOfCalls() {
2223 return numberOfCalls;
2224 }
2225
2226 public long getLastTime() {
2227 return lastTime;
2228 }
2229 }
2230}