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