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