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