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