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 return FileBackend.getUriForFile(mXmppConnectionService, new File(uri.getPath()));
1128 } else {
1129 return uri;
1130 }
1131 }
1132
1133 private Notification missedCallsSummary() {
1134 final Builder publicBuilder = buildMissedCallsSummary(true);
1135 final Builder builder = buildMissedCallsSummary(false);
1136 builder.setPublicVersion(publicBuilder.build());
1137 return builder.build();
1138 }
1139
1140 private Builder buildMissedCallsSummary(boolean publicVersion) {
1141 final Builder builder =
1142 new NotificationCompat.Builder(mXmppConnectionService, "missed_calls");
1143 int totalCalls = 0;
1144 final List<String> names = new ArrayList<>();
1145 long lastTime = 0;
1146 for (final Map.Entry<Conversational, MissedCallsInfo> entry : mMissedCalls.entrySet()) {
1147 final Conversational conversation = entry.getKey();
1148 final MissedCallsInfo missedCallsInfo = entry.getValue();
1149 names.add(conversation.getContact().getDisplayName());
1150 totalCalls += missedCallsInfo.getNumberOfCalls();
1151 lastTime = Math.max(lastTime, missedCallsInfo.getLastTime());
1152 }
1153 final String title =
1154 (totalCalls == 1)
1155 ? mXmppConnectionService.getString(R.string.missed_call)
1156 : (mMissedCalls.size() == 1)
1157 ? mXmppConnectionService
1158 .getResources()
1159 .getQuantityString(
1160 R.plurals.n_missed_calls, totalCalls, totalCalls)
1161 : mXmppConnectionService
1162 .getResources()
1163 .getQuantityString(
1164 R.plurals.n_missed_calls_from_m_contacts,
1165 mMissedCalls.size(),
1166 totalCalls,
1167 mMissedCalls.size());
1168 builder.setContentTitle(title);
1169 builder.setTicker(title);
1170 if (!publicVersion) {
1171 builder.setContentText(Joiner.on(", ").join(names));
1172 }
1173 builder.setSmallIcon(R.drawable.ic_call_missed_24db);
1174 builder.setGroupSummary(true);
1175 builder.setGroup(MISSED_CALLS_GROUP);
1176 builder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
1177 builder.setCategory(NotificationCompat.CATEGORY_CALL);
1178 builder.setWhen(lastTime);
1179 if (!mMissedCalls.isEmpty()) {
1180 final Conversational firstConversation = mMissedCalls.keySet().iterator().next();
1181 builder.setContentIntent(createContentIntent(firstConversation));
1182 }
1183 builder.setDeleteIntent(createMissedCallsDeleteIntent(null));
1184 modifyMissedCall(builder, null);
1185 return builder;
1186 }
1187
1188 private Notification missedCall(final Conversational conversation, final MissedCallsInfo info) {
1189 final Builder publicBuilder = buildMissedCall(conversation, info, true);
1190 final Builder builder = buildMissedCall(conversation, info, false);
1191 builder.setPublicVersion(publicBuilder.build());
1192 return builder.build();
1193 }
1194
1195 private Builder buildMissedCall(
1196 final Conversational conversation, final MissedCallsInfo info, boolean publicVersion) {
1197 final Builder builder =
1198 new NotificationCompat.Builder(mXmppConnectionService, isQuietHours(conversation.getAccount()) ? "quiet_hours" : "missed_calls");
1199 final String title =
1200 (info.getNumberOfCalls() == 1)
1201 ? mXmppConnectionService.getString(R.string.missed_call)
1202 : mXmppConnectionService
1203 .getResources()
1204 .getQuantityString(
1205 R.plurals.n_missed_calls,
1206 info.getNumberOfCalls(),
1207 info.getNumberOfCalls());
1208 builder.setContentTitle(title);
1209 if (mXmppConnectionService.getAccounts().size() > 1) {
1210 builder.setSubText(conversation.getAccount().getJid().asBareJid().toString());
1211 }
1212 final String name = conversation.getContact().getDisplayName();
1213 if (publicVersion) {
1214 builder.setTicker(title);
1215 } else {
1216 builder.setTicker(
1217 mXmppConnectionService
1218 .getResources()
1219 .getQuantityString(
1220 R.plurals.n_missed_calls_from_x,
1221 info.getNumberOfCalls(),
1222 info.getNumberOfCalls(),
1223 name));
1224 builder.setContentText(name);
1225 }
1226 builder.setSmallIcon(R.drawable.ic_call_missed_24db);
1227 builder.setGroup(MISSED_CALLS_GROUP);
1228 builder.setCategory(NotificationCompat.CATEGORY_CALL);
1229 builder.setWhen(info.getLastTime());
1230 builder.setContentIntent(createContentIntent(conversation));
1231 builder.setDeleteIntent(createMissedCallsDeleteIntent(conversation));
1232 if (!publicVersion && conversation instanceof Conversation) {
1233 builder.setLargeIcon(FileBackend.drawDrawable(
1234 mXmppConnectionService
1235 .getAvatarService()
1236 .get(
1237 (Conversation) conversation,
1238 AvatarService.getSystemUiAvatarSize(mXmppConnectionService))));
1239 }
1240 modifyMissedCall(builder, conversation.getAccount());
1241 return builder;
1242 }
1243
1244 private void modifyMissedCall(final Builder builder, Account account) {
1245 final SharedPreferences preferences =
1246 PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
1247 final Resources resources = mXmppConnectionService.getResources();
1248 final boolean led = preferences.getBoolean("led", resources.getBoolean(R.bool.led));
1249 if (led) {
1250 builder.setLights(LED_COLOR, 2000, 3000);
1251 }
1252 builder.setPriority(isQuietHours(account) ? NotificationCompat.PRIORITY_LOW : NotificationCompat.PRIORITY_HIGH);
1253 builder.setSound(null);
1254 setNotificationColor(builder, account);
1255 }
1256
1257 private Builder buildMultipleConversation(final boolean notify, final boolean quietHours) {
1258 final Builder mBuilder =
1259 new NotificationCompat.Builder(
1260 mXmppConnectionService,
1261 notify && !quietHours ? MESSAGES_NOTIFICATION_CHANNEL : "silent_messages");
1262 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
1263 style.setBigContentTitle(
1264 mXmppConnectionService
1265 .getResources()
1266 .getQuantityString(
1267 R.plurals.x_unread_conversations,
1268 notifications.size(),
1269 notifications.size()));
1270 final List<String> names = new ArrayList<>();
1271 Conversation conversation = null;
1272 for (final ArrayList<Message> messages : notifications.values()) {
1273 if (messages.isEmpty()) {
1274 continue;
1275 }
1276 conversation = (Conversation) messages.get(0).getConversation();
1277 final String name = conversation.getName().toString();
1278 SpannableString styledString;
1279 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
1280 int count = messages.size();
1281 styledString =
1282 new SpannableString(
1283 name
1284 + ": "
1285 + mXmppConnectionService
1286 .getResources()
1287 .getQuantityString(
1288 R.plurals.x_messages, count, count));
1289 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
1290 style.addLine(styledString);
1291 } else {
1292 styledString =
1293 new SpannableString(
1294 name
1295 + ": "
1296 + UIHelper.getMessagePreview(
1297 mXmppConnectionService, messages.get(0))
1298 .first);
1299 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
1300 style.addLine(styledString);
1301 }
1302 names.add(name);
1303 }
1304 final String contentTitle =
1305 mXmppConnectionService
1306 .getResources()
1307 .getQuantityString(
1308 R.plurals.x_unread_conversations,
1309 notifications.size(),
1310 notifications.size());
1311 mBuilder.setContentTitle(contentTitle);
1312 mBuilder.setTicker(contentTitle);
1313 mBuilder.setContentText(Joiner.on(", ").join(names));
1314 mBuilder.setStyle(style);
1315 if (conversation != null) {
1316 mBuilder.setContentIntent(createContentIntent(conversation));
1317 }
1318 mBuilder.setGroupSummary(true);
1319 mBuilder.setGroup(MESSAGES_GROUP);
1320 mBuilder.setDeleteIntent(createDeleteIntent(null));
1321 mBuilder.setSmallIcon(R.drawable.ic_notification);
1322 return mBuilder;
1323 }
1324
1325 private Builder buildSingleConversations(
1326 final ArrayList<Message> messages, final boolean notify, final boolean quietHours) {
1327 final var channel = notify && !quietHours ? MESSAGES_NOTIFICATION_CHANNEL : "silent_messages";
1328 final Builder notificationBuilder =
1329 new NotificationCompat.Builder(mXmppConnectionService, channel);
1330 if (messages.isEmpty()) {
1331 return notificationBuilder;
1332 }
1333 final Conversation conversation = (Conversation) messages.get(0).getConversation();
1334 notificationBuilder.setLargeIcon(FileBackend.drawDrawable(
1335 mXmppConnectionService
1336 .getAvatarService()
1337 .get(
1338 conversation,
1339 AvatarService.getSystemUiAvatarSize(mXmppConnectionService))));
1340 notificationBuilder.setContentTitle(conversation.getName());
1341 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
1342 int count = messages.size();
1343 notificationBuilder.setContentText(
1344 mXmppConnectionService
1345 .getResources()
1346 .getQuantityString(R.plurals.x_messages, count, count));
1347 } else {
1348 final Message message;
1349 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P
1350 && (message = getImage(messages)) != null) {
1351 modifyForImage(notificationBuilder, message, messages);
1352 } else {
1353 modifyForTextOnly(notificationBuilder, messages);
1354 }
1355 RemoteInput remoteInput =
1356 new RemoteInput.Builder("text_reply")
1357 .setLabel(UIHelper.getMessageHint(mXmppConnectionService, conversation))
1358 .build();
1359 PendingIntent markAsReadPendingIntent = createReadPendingIntent(conversation);
1360 NotificationCompat.Action markReadAction =
1361 new NotificationCompat.Action.Builder(
1362 R.drawable.ic_mark_chat_read_24dp,
1363 mXmppConnectionService.getString(R.string.mark_as_read),
1364 markAsReadPendingIntent)
1365 .setSemanticAction(
1366 NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ)
1367 .setShowsUserInterface(false)
1368 .build();
1369 final String replyLabel = mXmppConnectionService.getString(R.string.reply);
1370 final String lastMessageUuid = Iterables.getLast(messages).getUuid();
1371 final NotificationCompat.Action replyAction =
1372 new NotificationCompat.Action.Builder(
1373 R.drawable.ic_send_24dp,
1374 replyLabel,
1375 createReplyIntent(conversation, lastMessageUuid, false))
1376 .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY)
1377 .setShowsUserInterface(false)
1378 .addRemoteInput(remoteInput)
1379 .build();
1380 final NotificationCompat.Action wearReplyAction =
1381 new NotificationCompat.Action.Builder(
1382 R.drawable.ic_reply_24dp,
1383 replyLabel,
1384 createReplyIntent(conversation, lastMessageUuid, true))
1385 .addRemoteInput(remoteInput)
1386 .build();
1387 notificationBuilder.extend(
1388 new NotificationCompat.WearableExtender().addAction(wearReplyAction));
1389 int addedActionsCount = 1;
1390 notificationBuilder.addAction(markReadAction);
1391 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1392 notificationBuilder.addAction(replyAction);
1393 ++addedActionsCount;
1394 }
1395
1396 if (displaySnoozeAction(messages)) {
1397 String label = mXmppConnectionService.getString(R.string.snooze);
1398 PendingIntent pendingSnoozeIntent = createSnoozeIntent(conversation);
1399 NotificationCompat.Action snoozeAction =
1400 new NotificationCompat.Action.Builder(
1401 R.drawable.ic_notifications_paused_24dp,
1402 label,
1403 pendingSnoozeIntent)
1404 .build();
1405 notificationBuilder.addAction(snoozeAction);
1406 ++addedActionsCount;
1407 }
1408 if (addedActionsCount < 3) {
1409 final Message firstLocationMessage = getFirstLocationMessage(messages);
1410 if (firstLocationMessage != null) {
1411 final PendingIntent pendingShowLocationIntent =
1412 createShowLocationIntent(firstLocationMessage);
1413 if (pendingShowLocationIntent != null) {
1414 final String label =
1415 mXmppConnectionService
1416 .getResources()
1417 .getString(R.string.show_location);
1418 NotificationCompat.Action locationAction =
1419 new NotificationCompat.Action.Builder(
1420 R.drawable.ic_location_pin_24dp,
1421 label,
1422 pendingShowLocationIntent)
1423 .build();
1424 notificationBuilder.addAction(locationAction);
1425 ++addedActionsCount;
1426 }
1427 }
1428 }
1429 if (addedActionsCount < 3) {
1430 Message firstDownloadableMessage = getFirstDownloadableMessage(messages);
1431 if (firstDownloadableMessage != null) {
1432 String label =
1433 mXmppConnectionService
1434 .getResources()
1435 .getString(
1436 R.string.download_x_file,
1437 UIHelper.getFileDescriptionString(
1438 mXmppConnectionService,
1439 firstDownloadableMessage));
1440 PendingIntent pendingDownloadIntent =
1441 createDownloadIntent(firstDownloadableMessage);
1442 NotificationCompat.Action downloadAction =
1443 new NotificationCompat.Action.Builder(
1444 R.drawable.ic_download_24dp,
1445 label,
1446 pendingDownloadIntent)
1447 .build();
1448 notificationBuilder.addAction(downloadAction);
1449 ++addedActionsCount;
1450 }
1451 }
1452 }
1453 final ShortcutInfoCompat info;
1454 if (conversation.getMode() == Conversation.MODE_SINGLE) {
1455 final Contact contact = conversation.getContact();
1456 final Uri systemAccount = contact.getSystemAccount();
1457 if (systemAccount != null) {
1458 notificationBuilder.addPerson(systemAccount.toString());
1459 }
1460 info = mXmppConnectionService.getShortcutService().getShortcutInfoCompat(contact);
1461 } else {
1462 info =
1463 mXmppConnectionService
1464 .getShortcutService()
1465 .getShortcutInfoCompat(conversation.getMucOptions());
1466 }
1467 notificationBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
1468 notificationBuilder.setSmallIcon(R.drawable.ic_notification);
1469 notificationBuilder.setDeleteIntent(createDeleteIntent(conversation));
1470 notificationBuilder.setContentIntent(createContentIntent(conversation));
1471 if (mXmppConnectionService.getAccounts().size() > 1) {
1472 notificationBuilder.setSubText(conversation.getAccount().getJid().asBareJid().toString());
1473 }
1474 if (channel.equals(MESSAGES_NOTIFICATION_CHANNEL)) {
1475 // when do not want 'customized' notifications for silent notifications in their
1476 // respective channels
1477 notificationBuilder.setShortcutInfo(info);
1478 if (Build.VERSION.SDK_INT >= 30) {
1479 mXmppConnectionService
1480 .getSystemService(ShortcutManager.class)
1481 .pushDynamicShortcut(info.toShortcutInfo());
1482 // mBuilder.setBubbleMetadata(new NotificationCompat.BubbleMetadata.Builder(info.getId()).build());
1483 }
1484 }
1485 return notificationBuilder;
1486 }
1487
1488 private void modifyForImage(
1489 final Builder builder, final Message message, final ArrayList<Message> messages) {
1490 try {
1491 final Bitmap bitmap = mXmppConnectionService.getFileBackend().getThumbnailBitmap(message, mXmppConnectionService.getResources(), getPixel(288));
1492 final ArrayList<Message> tmp = new ArrayList<>();
1493 for (final Message msg : messages) {
1494 if (msg.getType() == Message.TYPE_TEXT && msg.getTransferable() == null) {
1495 tmp.add(msg);
1496 }
1497 }
1498 final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
1499 bigPictureStyle.bigPicture(bitmap);
1500 if (tmp.size() > 0) {
1501 CharSequence text = getMergedBodies(tmp);
1502 bigPictureStyle.setSummaryText(text);
1503 builder.setContentText(text);
1504 builder.setTicker(text);
1505 } else {
1506 final String description =
1507 UIHelper.getFileDescriptionString(mXmppConnectionService, message);
1508 builder.setContentText(description);
1509 builder.setTicker(description);
1510 }
1511 builder.setStyle(bigPictureStyle);
1512 } catch (final IOException e) {
1513 modifyForTextOnly(builder, messages);
1514 }
1515 }
1516
1517 private Person getPerson(Message message) {
1518 final Contact contact = message.getContact();
1519 final Person.Builder builder = new Person.Builder();
1520 if (contact != null) {
1521 builder.setName(contact.getDisplayName());
1522 final Uri uri = contact.getSystemAccount();
1523 if (uri != null) {
1524 builder.setUri(uri.toString());
1525 }
1526 } else {
1527 builder.setName(UIHelper.getMessageDisplayName(message));
1528 }
1529 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
1530 final Jid jid = contact == null ? message.getCounterpart() : contact.getJid();
1531 builder.setKey(jid.toString());
1532 final Conversation c = mXmppConnectionService.find(message.getConversation().getAccount(), jid);
1533 if (c != null) {
1534 builder.setImportant(c.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false));
1535 }
1536 builder.setIcon(
1537 IconCompat.createWithBitmap(FileBackend.drawDrawable(
1538 mXmppConnectionService
1539 .getAvatarService()
1540 .get(
1541 message,
1542 AvatarService.getSystemUiAvatarSize(
1543 mXmppConnectionService),
1544 false))));
1545 }
1546 return builder.build();
1547 }
1548
1549 private Person getPerson(Contact contact) {
1550 final Person.Builder builder = new Person.Builder();
1551 builder.setName(contact.getDisplayName());
1552 final Uri uri = contact.getSystemAccount();
1553 if (uri != null) {
1554 builder.setUri(uri.toString());
1555 }
1556 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
1557 final Jid jid = contact.getJid();
1558 builder.setKey(jid.toString());
1559 final Conversation c = mXmppConnectionService.find(contact.getAccount(), jid);
1560 if (c != null) {
1561 builder.setImportant(c.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false));
1562 }
1563 builder.setIcon(
1564 IconCompat.createWithBitmap(FileBackend.drawDrawable(
1565 mXmppConnectionService
1566 .getAvatarService()
1567 .get(
1568 contact,
1569 AvatarService.getSystemUiAvatarSize(
1570 mXmppConnectionService),
1571 false))));
1572 }
1573 return builder.build();
1574 }
1575
1576 private void modifyForTextOnly(final Builder builder, final ArrayList<Message> messages) {
1577 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1578 final Conversation conversation = (Conversation) messages.get(0).getConversation();
1579 final Person.Builder meBuilder =
1580 new Person.Builder().setName(mXmppConnectionService.getString(R.string.me));
1581 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
1582 meBuilder.setIcon(
1583 IconCompat.createWithBitmap(FileBackend.drawDrawable(
1584 mXmppConnectionService
1585 .getAvatarService()
1586 .get(
1587 conversation.getAccount(),
1588 AvatarService.getSystemUiAvatarSize(
1589 mXmppConnectionService)))));
1590 }
1591 final Person me = meBuilder.build();
1592 NotificationCompat.MessagingStyle messagingStyle =
1593 new NotificationCompat.MessagingStyle(me);
1594 final boolean multiple = conversation.getMode() == Conversation.MODE_MULTI || messages.get(0).getTrueCounterpart() != null;
1595 if (multiple) {
1596 messagingStyle.setConversationTitle(conversation.getName());
1597 }
1598 for (Message message : messages) {
1599 final Person sender =
1600 message.getStatus() == Message.STATUS_RECEIVED ? getPerson(message) : null;
1601 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && isImageMessage(message)) {
1602 final Uri dataUri =
1603 FileBackend.getMediaUri(
1604 mXmppConnectionService,
1605 mXmppConnectionService.getFileBackend().getFile(message));
1606 NotificationCompat.MessagingStyle.Message imageMessage =
1607 new NotificationCompat.MessagingStyle.Message(
1608 UIHelper.getMessagePreview(mXmppConnectionService, message)
1609 .first,
1610 message.getTimeSent(),
1611 sender);
1612 if (dataUri != null) {
1613 imageMessage.setData(message.getMimeType(), dataUri);
1614 }
1615 messagingStyle.addMessage(imageMessage);
1616 } else {
1617 messagingStyle.addMessage(
1618 UIHelper.getMessagePreview(mXmppConnectionService, message).first,
1619 message.getTimeSent(),
1620 sender);
1621 }
1622 }
1623 messagingStyle.setGroupConversation(multiple);
1624 builder.setStyle(messagingStyle);
1625 } else {
1626 if (messages.get(0).getConversation().getMode() == Conversation.MODE_SINGLE && messages.get(0).getTrueCounterpart() == null) {
1627 builder.setStyle(
1628 new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
1629 final CharSequence preview =
1630 UIHelper.getMessagePreview(
1631 mXmppConnectionService, messages.get(messages.size() - 1))
1632 .first;
1633 builder.setContentText(preview);
1634 builder.setTicker(preview);
1635 builder.setNumber(messages.size());
1636 } else {
1637 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
1638 SpannableString styledString;
1639 for (Message message : messages) {
1640 final String name = UIHelper.getMessageDisplayName(message);
1641 styledString = new SpannableString(name + ": " + message.getBody());
1642 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
1643 style.addLine(styledString);
1644 }
1645 builder.setStyle(style);
1646 int count = messages.size();
1647 if (count == 1) {
1648 final String name = UIHelper.getMessageDisplayName(messages.get(0));
1649 styledString = new SpannableString(name + ": " + messages.get(0).getBody());
1650 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
1651 builder.setContentText(styledString);
1652 builder.setTicker(styledString);
1653 } else {
1654 final String text =
1655 mXmppConnectionService
1656 .getResources()
1657 .getQuantityString(R.plurals.x_messages, count, count);
1658 builder.setContentText(text);
1659 builder.setTicker(text);
1660 }
1661 }
1662 }
1663 }
1664
1665 private Message getImage(final Iterable<Message> messages) {
1666 Message image = null;
1667 for (final Message message : messages) {
1668 if (message.getStatus() != Message.STATUS_RECEIVED) {
1669 return null;
1670 }
1671 if (isImageMessage(message)) {
1672 image = message;
1673 }
1674 }
1675 return image;
1676 }
1677
1678 private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
1679 for (final Message message : messages) {
1680 if (message.getTransferable() != null
1681 || (message.getType() == Message.TYPE_TEXT && message.treatAsDownloadable())) {
1682 return message;
1683 }
1684 }
1685 return null;
1686 }
1687
1688 private Message getFirstLocationMessage(final Iterable<Message> messages) {
1689 for (final Message message : messages) {
1690 if (message.isGeoUri()) {
1691 return message;
1692 }
1693 }
1694 return null;
1695 }
1696
1697 private CharSequence getMergedBodies(final ArrayList<Message> messages) {
1698 final StringBuilder text = new StringBuilder();
1699 for (Message message : messages) {
1700 if (text.length() != 0) {
1701 text.append("\n");
1702 }
1703 text.append(UIHelper.getMessagePreview(mXmppConnectionService, message).first);
1704 }
1705 return text.toString();
1706 }
1707
1708 private PendingIntent createShowLocationIntent(final Message message) {
1709 Iterable<Intent> intents =
1710 GeoHelper.createGeoIntentsFromMessage(mXmppConnectionService, message);
1711 for (final Intent intent : intents) {
1712 if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
1713 return PendingIntent.getActivity(
1714 mXmppConnectionService,
1715 generateRequestCode(message.getConversation(), 18),
1716 intent,
1717 s()
1718 ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1719 : PendingIntent.FLAG_UPDATE_CURRENT);
1720 }
1721 }
1722 return null;
1723 }
1724
1725 private PendingIntent createContentIntent(
1726 final String conversationUuid, final String downloadMessageUuid) {
1727 final Intent viewConversationIntent =
1728 new Intent(mXmppConnectionService, ConversationsActivity.class);
1729 viewConversationIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
1730 viewConversationIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversationUuid);
1731 if (downloadMessageUuid != null) {
1732 viewConversationIntent.putExtra(
1733 ConversationsActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
1734 return PendingIntent.getActivity(
1735 mXmppConnectionService,
1736 generateRequestCode(conversationUuid, 8),
1737 viewConversationIntent,
1738 s()
1739 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1740 : PendingIntent.FLAG_UPDATE_CURRENT);
1741 } else {
1742 return PendingIntent.getActivity(
1743 mXmppConnectionService,
1744 generateRequestCode(conversationUuid, 10),
1745 viewConversationIntent,
1746 s()
1747 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1748 : PendingIntent.FLAG_UPDATE_CURRENT);
1749 }
1750 }
1751
1752 private int generateRequestCode(String uuid, int actionId) {
1753 return (actionId * NOTIFICATION_ID_MULTIPLIER)
1754 + (uuid.hashCode() % NOTIFICATION_ID_MULTIPLIER);
1755 }
1756
1757 private int generateRequestCode(Conversational conversation, int actionId) {
1758 return generateRequestCode(conversation.getUuid(), actionId);
1759 }
1760
1761 private PendingIntent createDownloadIntent(final Message message) {
1762 return createContentIntent(message.getConversationUuid(), message.getUuid());
1763 }
1764
1765 private PendingIntent createContentIntent(final Conversational conversation) {
1766 return createContentIntent(conversation.getUuid(), null);
1767 }
1768
1769 private PendingIntent createDeleteIntent(final Conversation conversation) {
1770 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1771 intent.setAction(XmppConnectionService.ACTION_CLEAR_MESSAGE_NOTIFICATION);
1772 if (conversation != null) {
1773 intent.putExtra("uuid", conversation.getUuid());
1774 return PendingIntent.getService(
1775 mXmppConnectionService,
1776 generateRequestCode(conversation, 20),
1777 intent,
1778 s()
1779 ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1780 : PendingIntent.FLAG_UPDATE_CURRENT);
1781 }
1782 return PendingIntent.getService(
1783 mXmppConnectionService,
1784 0,
1785 intent,
1786 s()
1787 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1788 : PendingIntent.FLAG_UPDATE_CURRENT);
1789 }
1790
1791 private PendingIntent createMissedCallsDeleteIntent(final Conversational conversation) {
1792 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1793 intent.setAction(XmppConnectionService.ACTION_CLEAR_MISSED_CALL_NOTIFICATION);
1794 if (conversation != null) {
1795 intent.putExtra("uuid", conversation.getUuid());
1796 return PendingIntent.getService(
1797 mXmppConnectionService,
1798 generateRequestCode(conversation, 21),
1799 intent,
1800 s()
1801 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1802 : PendingIntent.FLAG_UPDATE_CURRENT);
1803 }
1804 return PendingIntent.getService(
1805 mXmppConnectionService,
1806 1,
1807 intent,
1808 s()
1809 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1810 : PendingIntent.FLAG_UPDATE_CURRENT);
1811 }
1812
1813 private PendingIntent createReplyIntent(
1814 final Conversation conversation,
1815 final String lastMessageUuid,
1816 final boolean dismissAfterReply) {
1817 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1818 intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
1819 intent.putExtra("uuid", conversation.getUuid());
1820 intent.putExtra("dismiss_notification", dismissAfterReply);
1821 intent.putExtra("last_message_uuid", lastMessageUuid);
1822 final int id = generateRequestCode(conversation, dismissAfterReply ? 12 : 14);
1823 return PendingIntent.getService(
1824 mXmppConnectionService,
1825 id,
1826 intent,
1827 s()
1828 ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1829 : PendingIntent.FLAG_UPDATE_CURRENT);
1830 }
1831
1832 private PendingIntent createReadPendingIntent(Conversation conversation) {
1833 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1834 intent.setAction(XmppConnectionService.ACTION_MARK_AS_READ);
1835 intent.putExtra("uuid", conversation.getUuid());
1836 intent.setPackage(mXmppConnectionService.getPackageName());
1837 return PendingIntent.getService(
1838 mXmppConnectionService,
1839 generateRequestCode(conversation, 16),
1840 intent,
1841 s()
1842 ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1843 : PendingIntent.FLAG_UPDATE_CURRENT);
1844 }
1845
1846 private PendingIntent createCallAction(String sessionId, final String action, int requestCode) {
1847 return pendingServiceIntent(
1848 mXmppConnectionService,
1849 action,
1850 requestCode,
1851 ImmutableMap.of(RtpSessionActivity.EXTRA_SESSION_ID, sessionId));
1852 }
1853
1854 private PendingIntent createSnoozeIntent(final Conversation conversation) {
1855 return pendingServiceIntent(
1856 mXmppConnectionService,
1857 XmppConnectionService.ACTION_SNOOZE,
1858 generateRequestCode(conversation, 22),
1859 ImmutableMap.of("uuid", conversation.getUuid()));
1860 }
1861
1862 private static PendingIntent pendingServiceIntent(
1863 final Context context, final String action, final int requestCode) {
1864 return pendingServiceIntent(context, action, requestCode, ImmutableMap.of());
1865 }
1866
1867 private static PendingIntent pendingServiceIntent(
1868 final Context context,
1869 final String action,
1870 final int requestCode,
1871 final Map<String, String> extras) {
1872 final Intent intent = new Intent(context, XmppConnectionService.class);
1873 intent.setAction(action);
1874 for (final Map.Entry<String, String> entry : extras.entrySet()) {
1875 intent.putExtra(entry.getKey(), entry.getValue());
1876 }
1877 return PendingIntent.getService(
1878 context,
1879 requestCode,
1880 intent,
1881 s()
1882 ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1883 : PendingIntent.FLAG_UPDATE_CURRENT);
1884 }
1885
1886 private boolean wasHighlightedOrPrivate(final Message message) {
1887 if (message.getConversation() instanceof Conversation) {
1888 Conversation conversation = (Conversation) message.getConversation();
1889 final MucOptions.User sender = conversation.getMucOptions().findUserByFullJid(message.getCounterpart());
1890 final boolean muted = message.getStatus() == Message.STATUS_RECEIVED && mXmppConnectionService.isMucUserMuted(new MucOptions.User(null, conversation.getJid(), message.getOccupantId(), null, null));
1891 if (muted) return false;
1892 if (sender != null && sender.getAffiliation().ranks(MucOptions.Affiliation.MEMBER) && message.isAttention()) {
1893 return true;
1894 }
1895 final String nick = conversation.getMucOptions().getActualNick();
1896 final Pattern highlight = generateNickHighlightPattern(nick);
1897 final String name = conversation.getMucOptions().getActualName();
1898 final Pattern highlightName = generateNickHighlightPattern(name);
1899 if (message.getBody() == null || (nick == null && name == null)) {
1900 return false;
1901 }
1902 final Matcher m = highlight.matcher(message.getBody(true));
1903 final Matcher m2 = highlightName.matcher(message.getBody(true));
1904 return (m.find() || m2.find() || message.isPrivateMessage());
1905 } else {
1906 return false;
1907 }
1908 }
1909
1910 private boolean wasReplyToMe(final Message message) {
1911 final Element reply = message.getReply();
1912 if (reply == null || reply.getAttribute("id") == null) return false;
1913 final Message parent = ((Conversation) message.getConversation()).findMessageWithRemoteIdAndCounterpart(reply.getAttribute("id"), null);
1914 if (parent == null) return false;
1915 return parent.getStatus() >= Message.STATUS_SEND;
1916 }
1917
1918 public void setOpenConversation(final Conversation conversation) {
1919 this.mOpenConversation = conversation;
1920 }
1921
1922 public void setIsInForeground(final boolean foreground) {
1923 this.mIsInForeground = foreground;
1924 }
1925
1926 private int getPixel(final int dp) {
1927 final DisplayMetrics metrics = mXmppConnectionService.getResources().getDisplayMetrics();
1928 return ((int) (dp * metrics.density));
1929 }
1930
1931 private void markLastNotification() {
1932 this.mLastNotification = SystemClock.elapsedRealtime();
1933 }
1934
1935 private boolean inMiniGracePeriod(final Account account) {
1936 final int miniGrace =
1937 account.getStatus() == Account.State.ONLINE
1938 ? Config.MINI_GRACE_PERIOD
1939 : Config.MINI_GRACE_PERIOD * 2;
1940 return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
1941 }
1942
1943 Notification createForegroundNotification() {
1944 final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1945 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.app_name));
1946 final List<Account> accounts = mXmppConnectionService.getAccounts();
1947 final int enabled;
1948 final int connected;
1949 if (accounts == null) {
1950 enabled = 0;
1951 connected = 0;
1952 } else {
1953 enabled = Iterables.size(Iterables.filter(accounts, Account::isEnabled));
1954 connected = Iterables.size(Iterables.filter(accounts, Account::isOnlineAndConnected));
1955 }
1956 mBuilder.setContentText(
1957 mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
1958 final PendingIntent openIntent = createOpenConversationsIntent();
1959 if (openIntent != null) {
1960 mBuilder.setContentIntent(openIntent);
1961 }
1962 mBuilder.setWhen(0)
1963 .setPriority(Notification.PRIORITY_MIN)
1964 .setSmallIcon(connected >= enabled ? R.drawable.ic_link_24dp : R.drawable.ic_link_off_24dp)
1965 .setLocalOnly(true);
1966
1967 if (Compatibility.runsTwentySix()) {
1968 mBuilder.setChannelId("foreground");
1969 mBuilder.addAction(
1970 R.drawable.ic_logout_24dp,
1971 mXmppConnectionService.getString(R.string.log_out),
1972 pendingServiceIntent(
1973 mXmppConnectionService,
1974 XmppConnectionService.ACTION_TEMPORARILY_DISABLE,
1975 87));
1976 mBuilder.addAction(
1977 R.drawable.ic_notifications_off_24dp,
1978 mXmppConnectionService.getString(R.string.hide_notification),
1979 pendingNotificationSettingsIntent(mXmppConnectionService));
1980 }
1981
1982 return mBuilder.build();
1983 }
1984
1985 @RequiresApi(api = Build.VERSION_CODES.O)
1986 private static PendingIntent pendingNotificationSettingsIntent(final Context context) {
1987 final Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
1988 intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
1989 intent.putExtra(Settings.EXTRA_CHANNEL_ID, "foreground");
1990 return PendingIntent.getActivity(
1991 context,
1992 89,
1993 intent,
1994 s()
1995 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1996 : PendingIntent.FLAG_UPDATE_CURRENT);
1997 }
1998
1999 private PendingIntent createOpenConversationsIntent() {
2000 try {
2001 return PendingIntent.getActivity(
2002 mXmppConnectionService,
2003 0,
2004 new Intent(mXmppConnectionService, ConversationsActivity.class),
2005 s()
2006 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
2007 : PendingIntent.FLAG_UPDATE_CURRENT);
2008 } catch (RuntimeException e) {
2009 return null;
2010 }
2011 }
2012
2013 void updateErrorNotification() {
2014 if (Config.SUPPRESS_ERROR_NOTIFICATION) {
2015 cancel(ERROR_NOTIFICATION_ID);
2016 return;
2017 }
2018 final boolean showAllErrors = QuickConversationsService.isConversations();
2019 final List<Account> errors = new ArrayList<>();
2020 boolean torNotAvailable = false;
2021 for (final Account account : mXmppConnectionService.getAccounts()) {
2022 if (account.hasErrorStatus()
2023 && account.showErrorNotification()
2024 && (showAllErrors
2025 || account.getLastErrorStatus() == Account.State.UNAUTHORIZED)) {
2026 errors.add(account);
2027 torNotAvailable |= account.getStatus() == Account.State.TOR_NOT_AVAILABLE;
2028 }
2029 }
2030 if (mXmppConnectionService.foregroundNotificationNeedsUpdatingWhenErrorStateChanges()) {
2031 try {
2032 notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
2033 } catch (final RuntimeException e) {
2034 Log.d(
2035 Config.LOGTAG,
2036 "not refreshing foreground service notification because service has died",
2037 e);
2038 }
2039 }
2040 final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
2041 if (errors.isEmpty()) {
2042 cancel(ERROR_NOTIFICATION_ID);
2043 return;
2044 } else if (errors.size() == 1) {
2045 mBuilder.setContentTitle(
2046 mXmppConnectionService.getString(R.string.problem_connecting_to_account));
2047 mBuilder.setContentText(errors.get(0).getJid().asBareJid().toEscapedString());
2048 } else {
2049 mBuilder.setContentTitle(
2050 mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
2051 mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
2052 }
2053 try {
2054 mBuilder.addAction(
2055 R.drawable.ic_autorenew_24dp,
2056 mXmppConnectionService.getString(R.string.try_again),
2057 pendingServiceIntent(
2058 mXmppConnectionService, XmppConnectionService.ACTION_TRY_AGAIN, 45));
2059 mBuilder.setDeleteIntent(
2060 pendingServiceIntent(
2061 mXmppConnectionService,
2062 XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS,
2063 69));
2064 } catch (final RuntimeException e) {
2065 Log.d(
2066 Config.LOGTAG,
2067 "not including some actions in error notification because service has died",
2068 e);
2069 }
2070 if (torNotAvailable) {
2071 if (TorServiceUtils.isOrbotInstalled(mXmppConnectionService)) {
2072 mBuilder.addAction(
2073 R.drawable.ic_play_circle_24dp,
2074 mXmppConnectionService.getString(R.string.start_orbot),
2075 PendingIntent.getActivity(
2076 mXmppConnectionService,
2077 147,
2078 TorServiceUtils.LAUNCH_INTENT,
2079 s()
2080 ? PendingIntent.FLAG_IMMUTABLE
2081 | PendingIntent.FLAG_UPDATE_CURRENT
2082 : PendingIntent.FLAG_UPDATE_CURRENT));
2083 } else {
2084 mBuilder.addAction(
2085 R.drawable.ic_download_24dp,
2086 mXmppConnectionService.getString(R.string.install_orbot),
2087 PendingIntent.getActivity(
2088 mXmppConnectionService,
2089 146,
2090 TorServiceUtils.INSTALL_INTENT,
2091 s()
2092 ? PendingIntent.FLAG_IMMUTABLE
2093 | PendingIntent.FLAG_UPDATE_CURRENT
2094 : PendingIntent.FLAG_UPDATE_CURRENT));
2095 }
2096 }
2097 mBuilder.setVisibility(Notification.VISIBILITY_PRIVATE);
2098 mBuilder.setSmallIcon(R.drawable.ic_warning_24dp);
2099 mBuilder.setLocalOnly(true);
2100 mBuilder.setPriority(Notification.PRIORITY_LOW);
2101 final Intent intent;
2102 if (AccountUtils.MANAGE_ACCOUNT_ACTIVITY != null) {
2103 intent = new Intent(mXmppConnectionService, AccountUtils.MANAGE_ACCOUNT_ACTIVITY);
2104 } else {
2105 intent = new Intent(mXmppConnectionService, EditAccountActivity.class);
2106 intent.putExtra("jid", errors.get(0).getJid().asBareJid().toEscapedString());
2107 intent.putExtra(EditAccountActivity.EXTRA_OPENED_FROM_NOTIFICATION, true);
2108 }
2109 mBuilder.setContentIntent(
2110 PendingIntent.getActivity(
2111 mXmppConnectionService,
2112 145,
2113 intent,
2114 s()
2115 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
2116 : PendingIntent.FLAG_UPDATE_CURRENT));
2117 if (Compatibility.runsTwentySix()) {
2118 mBuilder.setChannelId("error");
2119 }
2120 notify(ERROR_NOTIFICATION_ID, mBuilder.build());
2121 }
2122
2123 void updateFileAddingNotification(final int current, final Message message) {
2124
2125 final Notification notification = videoTranscoding(current, message);
2126 notify(ONGOING_VIDEO_TRANSCODING_NOTIFICATION_ID, notification);
2127 }
2128
2129 private Notification videoTranscoding(final int current, @Nullable final Message message) {
2130 final Notification.Builder builder = new Notification.Builder(mXmppConnectionService);
2131 builder.setContentTitle(mXmppConnectionService.getString(R.string.transcoding_video));
2132 if (current >= 0) {
2133 builder.setProgress(100, current, false);
2134 } else {
2135 builder.setProgress(100, 0, true);
2136 }
2137 builder.setSmallIcon(R.drawable.ic_hourglass_top_24dp);
2138 if (message != null) {
2139 builder.setContentIntent(createContentIntent(message.getConversation()));
2140 }
2141 builder.setOngoing(true);
2142 if (Compatibility.runsTwentySix()) {
2143 builder.setChannelId("compression");
2144 }
2145 return builder.build();
2146 }
2147
2148 public Notification getIndeterminateVideoTranscoding() {
2149 return videoTranscoding(-1, null);
2150 }
2151
2152 private void notify(final String tag, final int id, final Notification notification) {
2153 if (ActivityCompat.checkSelfPermission(
2154 mXmppConnectionService, Manifest.permission.POST_NOTIFICATIONS)
2155 != PackageManager.PERMISSION_GRANTED) {
2156 return;
2157 }
2158 final var notificationManager =
2159 mXmppConnectionService.getSystemService(NotificationManager.class);
2160 try {
2161 notificationManager.notify(tag, id, notification);
2162 } catch (final RuntimeException e) {
2163 Log.d(Config.LOGTAG, "unable to make notification", e);
2164 }
2165 }
2166
2167 public void notify(final int id, final Notification notification) {
2168 if (ActivityCompat.checkSelfPermission(
2169 mXmppConnectionService, Manifest.permission.POST_NOTIFICATIONS)
2170 != PackageManager.PERMISSION_GRANTED) {
2171 return;
2172 }
2173 final var notificationManager =
2174 mXmppConnectionService.getSystemService(NotificationManager.class);
2175 try {
2176 notificationManager.notify(id, notification);
2177 } catch (final RuntimeException e) {
2178 Log.d(Config.LOGTAG, "unable to make notification", e);
2179 }
2180 }
2181
2182 public void cancel(final int id) {
2183 final NotificationManagerCompat notificationManager =
2184 NotificationManagerCompat.from(mXmppConnectionService);
2185 try {
2186 notificationManager.cancel(id);
2187 } catch (RuntimeException e) {
2188 Log.d(Config.LOGTAG, "unable to cancel notification", e);
2189 }
2190 }
2191
2192 private void cancel(String tag, int id) {
2193 final NotificationManagerCompat notificationManager =
2194 NotificationManagerCompat.from(mXmppConnectionService);
2195 try {
2196 notificationManager.cancel(tag, id);
2197 } catch (RuntimeException e) {
2198 Log.d(Config.LOGTAG, "unable to cancel notification", e);
2199 }
2200 }
2201
2202 private static class MissedCallsInfo {
2203 private int numberOfCalls;
2204 private long lastTime;
2205
2206 MissedCallsInfo(final long time) {
2207 numberOfCalls = 1;
2208 lastTime = time;
2209 }
2210
2211 public void newMissedCall(final long time) {
2212 ++numberOfCalls;
2213 lastTime = time;
2214 }
2215
2216 public boolean removeMissedCall() {
2217 --numberOfCalls;
2218 return numberOfCalls <= 0;
2219 }
2220
2221 public int getNumberOfCalls() {
2222 return numberOfCalls;
2223 }
2224
2225 public long getLastTime() {
2226 return lastTime;
2227 }
2228 }
2229}