1package eu.siacs.conversations.services;
2
3import android.Manifest;
4import static eu.siacs.conversations.utils.Compatibility.s;
5
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.Bundle;
25import android.os.SystemClock;
26import android.os.Vibrator;
27import android.preference.PreferenceManager;
28import android.telecom.PhoneAccountHandle;
29import android.telecom.TelecomManager;
30import android.text.SpannableString;
31import android.text.style.StyleSpan;
32import android.util.DisplayMetrics;
33import android.util.Log;
34import android.util.TypedValue;
35
36import androidx.annotation.RequiresApi;
37import androidx.core.app.NotificationCompat;
38import androidx.core.app.NotificationCompat.BigPictureStyle;
39import androidx.core.app.NotificationCompat.Builder;
40import androidx.core.app.NotificationManagerCompat;
41import androidx.core.app.Person;
42import androidx.core.app.RemoteInput;
43import androidx.core.content.ContextCompat;
44import androidx.core.content.pm.ShortcutInfoCompat;
45import androidx.core.graphics.drawable.IconCompat;
46
47import com.google.common.base.Joiner;
48import com.google.common.base.Strings;
49import com.google.common.collect.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.entities.MucOptions;
78import eu.siacs.conversations.persistance.FileBackend;
79import eu.siacs.conversations.ui.ConversationsActivity;
80import eu.siacs.conversations.ui.EditAccountActivity;
81import eu.siacs.conversations.ui.RtpSessionActivity;
82import eu.siacs.conversations.ui.TimePreference;
83import eu.siacs.conversations.utils.AccountUtils;
84import eu.siacs.conversations.utils.Compatibility;
85import eu.siacs.conversations.utils.GeoHelper;
86import eu.siacs.conversations.utils.TorServiceUtils;
87import eu.siacs.conversations.utils.UIHelper;
88import eu.siacs.conversations.xmpp.Jid;
89import eu.siacs.conversations.xmpp.XmppConnection;
90import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
91import eu.siacs.conversations.xmpp.jingle.Media;
92
93public class NotificationService {
94
95 private static final ScheduledExecutorService SCHEDULED_EXECUTOR_SERVICE =
96 Executors.newSingleThreadScheduledExecutor();
97
98 public static final Object CATCHUP_LOCK = new Object();
99
100 private static final int LED_COLOR = 0xff7401cf;
101
102 private static final long[] CALL_PATTERN = {0, 500, 300, 600};
103
104 private static final String MESSAGES_GROUP = "eu.siacs.conversations.messages";
105 private static final String MISSED_CALLS_GROUP = "eu.siacs.conversations.missed_calls";
106 private static final int NOTIFICATION_ID_MULTIPLIER = 1024 * 1024;
107 static final int FOREGROUND_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 4;
108 private static final int NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 2;
109 private static final int ERROR_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 6;
110 private static final int INCOMING_CALL_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 8;
111 public static final int ONGOING_CALL_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 10;
112 public static final int MISSED_CALL_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 12;
113 private static final int DELIVERY_FAILED_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 13;
114 private final XmppConnectionService mXmppConnectionService;
115 private final LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<>();
116 private final HashMap<Conversation, AtomicInteger> mBacklogMessageCounter = new HashMap<>();
117 private final LinkedHashMap<Conversational, MissedCallsInfo> mMissedCalls =
118 new LinkedHashMap<>();
119 private Conversation mOpenConversation;
120 private boolean mIsInForeground;
121 private long mLastNotification;
122
123 private static final String INCOMING_CALLS_NOTIFICATION_CHANNEL = "incoming_calls_channel";
124 private 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",
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 private synchronized boolean tryRingingWithDialerUI(final AbstractJingleConnection.Id id, final Set<Media> media) {
508 if (Build.VERSION.SDK_INT < 23) return false;
509
510 if (!mXmppConnectionService.getPreferences().getBoolean("dialler_integration_incoming", true)) return false;
511
512 if (mXmppConnectionService.checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
513 // We cannot request audio permission in Dialer UI
514 // when Dialer is shown over keyguard, the user cannot even necessarily
515 // see notifications.
516 return false;
517 }
518
519 if (media.size() != 1 || !media.contains(Media.AUDIO)) {
520 // Currently our ConnectionService only handles single audio calls
521 Log.w(Config.LOGTAG, "only audio calls can be handled by cheogram connection service");
522 return false;
523 }
524
525 PhoneAccountHandle handle = null;
526 for (Contact contact : id.account.getRoster().getContacts()) {
527 if (!contact.getJid().getDomain().equals(id.with.getDomain())) {
528 continue;
529 }
530
531 if (!contact.getPresences().anyIdentity("gateway", "pstn")) {
532 continue;
533 }
534
535 handle = contact.phoneAccountHandle();
536 break;
537 }
538
539 if (handle == null) {
540 Log.w(Config.LOGTAG, "Could not find phone account handle for " + id.account.getJid().toString());
541 return false;
542 }
543
544 Bundle callInfo = new Bundle();
545 callInfo.putString("account", id.account.getJid().toString());
546 callInfo.putString("with", id.with.toString());
547 callInfo.putString("sessionId", id.sessionId);
548
549 TelecomManager telecomManager = mXmppConnectionService.getSystemService(TelecomManager.class);
550
551 try {
552 telecomManager.addNewIncomingCall(handle, callInfo);
553 } catch (SecurityException e) {
554 // If the account is not registered or enabled, it could result in a security exception
555 // Just fall back to the built-in UI in this case.
556 Log.w(Config.LOGTAG, e);
557 return false;
558 }
559
560 return true;
561 }
562
563 public synchronized void startRinging(final AbstractJingleConnection.Id id, final Set<Media> media) {
564 if (tryRingingWithDialerUI(id, media)) {
565 return;
566 }
567
568 showIncomingCallNotification(id, media);
569 final NotificationManager notificationManager =
570 (NotificationManager)
571 mXmppConnectionService.getSystemService(Context.NOTIFICATION_SERVICE);
572 final int currentInterruptionFilter;
573 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && notificationManager != null) {
574 currentInterruptionFilter = notificationManager.getCurrentInterruptionFilter();
575 } else {
576 currentInterruptionFilter = 1; // INTERRUPTION_FILTER_ALL
577 }
578 if (currentInterruptionFilter != 1) {
579 Log.d(
580 Config.LOGTAG,
581 "do not ring or vibrate because interruption filter has been set to "
582 + currentInterruptionFilter);
583 return;
584 }
585 final ScheduledFuture<?> currentVibrationFuture = this.vibrationFuture;
586 this.vibrationFuture =
587 SCHEDULED_EXECUTOR_SERVICE.scheduleAtFixedRate(
588 new VibrationRunnable(), 0, 3, TimeUnit.SECONDS);
589 if (currentVibrationFuture != null) {
590 currentVibrationFuture.cancel(true);
591 }
592 final SharedPreferences preferences =
593 PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
594 final Resources resources = mXmppConnectionService.getResources();
595 final String ringtonePreference =
596 preferences.getString(
597 "call_ringtone", resources.getString(R.string.incoming_call_ringtone));
598 if (Strings.isNullOrEmpty(ringtonePreference)) {
599 Log.d(Config.LOGTAG, "ringtone has been set to none");
600 return;
601 }
602 final Uri uri = Uri.parse(ringtonePreference);
603 this.currentlyPlayingRingtone = RingtoneManager.getRingtone(mXmppConnectionService, uri);
604 if (this.currentlyPlayingRingtone == null) {
605 Log.d(Config.LOGTAG, "unable to find ringtone for uri " + uri);
606 return;
607 }
608 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
609 this.currentlyPlayingRingtone.setLooping(true);
610 }
611 this.currentlyPlayingRingtone.play();
612 }
613
614 private void showIncomingCallNotification(
615 final AbstractJingleConnection.Id id, final Set<Media> media) {
616 final Intent fullScreenIntent =
617 new Intent(mXmppConnectionService, RtpSessionActivity.class);
618 fullScreenIntent.putExtra(
619 RtpSessionActivity.EXTRA_ACCOUNT,
620 id.account.getJid().asBareJid().toEscapedString());
621 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_WITH, id.with.toEscapedString());
622 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.sessionId);
623 fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
624 fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
625 final NotificationCompat.Builder builder =
626 new NotificationCompat.Builder(
627 mXmppConnectionService, INCOMING_CALLS_NOTIFICATION_CHANNEL);
628 if (media.contains(Media.VIDEO)) {
629 builder.setSmallIcon(R.drawable.ic_videocam_white_24dp);
630 builder.setContentTitle(
631 mXmppConnectionService.getString(R.string.rtp_state_incoming_video_call));
632 } else {
633 builder.setSmallIcon(R.drawable.ic_call_white_24dp);
634 builder.setContentTitle(
635 mXmppConnectionService.getString(R.string.rtp_state_incoming_call));
636 }
637 final Contact contact = id.getContact();
638 builder.addPerson(getPerson(contact));
639 ShortcutInfoCompat info = mXmppConnectionService.getShortcutService().getShortcutInfoCompat(contact);
640 builder.setShortcutInfo(info);
641 if (Build.VERSION.SDK_INT >= 30) {
642 mXmppConnectionService.getSystemService(ShortcutManager.class).pushDynamicShortcut(info.toShortcutInfo());
643 }
644 if (mXmppConnectionService.getAccounts().size() > 1) {
645 builder.setSubText(contact.getAccount().getJid().asBareJid().toString());
646 }
647 builder.setLargeIcon(
648 mXmppConnectionService
649 .getAvatarService()
650 .get(contact, AvatarService.getSystemUiAvatarSize(mXmppConnectionService)));
651 final Uri systemAccount = contact.getSystemAccount();
652 if (systemAccount != null) {
653 builder.addPerson(systemAccount.toString());
654 }
655 builder.setContentText(id.account.getRoster().getContact(id.with).getDisplayName());
656 builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
657 builder.setPriority(NotificationCompat.PRIORITY_HIGH);
658 builder.setCategory(NotificationCompat.CATEGORY_CALL);
659 PendingIntent pendingIntent = createPendingRtpSession(id, Intent.ACTION_VIEW, 101);
660 builder.setFullScreenIntent(pendingIntent, true);
661 builder.setContentIntent(pendingIntent); // old androids need this?
662 builder.setOngoing(true);
663 builder.addAction(
664 new NotificationCompat.Action.Builder(
665 R.drawable.ic_call_end_white_48dp,
666 mXmppConnectionService.getString(R.string.dismiss_call),
667 createCallAction(
668 id.sessionId,
669 XmppConnectionService.ACTION_DISMISS_CALL,
670 102))
671 .build());
672 builder.addAction(
673 new NotificationCompat.Action.Builder(
674 R.drawable.ic_call_white_24dp,
675 mXmppConnectionService.getString(R.string.answer_call),
676 createPendingRtpSession(
677 id, RtpSessionActivity.ACTION_ACCEPT_CALL, 103))
678 .build());
679 modifyIncomingCall(builder);
680 final Notification notification = builder.build();
681 notification.flags = notification.flags | Notification.FLAG_INSISTENT;
682 notify(INCOMING_CALL_NOTIFICATION_ID, notification);
683 }
684
685 public Notification getOngoingCallNotification(
686 final XmppConnectionService.OngoingCall ongoingCall) {
687 final AbstractJingleConnection.Id id = ongoingCall.id;
688 final NotificationCompat.Builder builder =
689 new NotificationCompat.Builder(mXmppConnectionService, "ongoing_calls");
690 if (ongoingCall.media.contains(Media.VIDEO)) {
691 builder.setSmallIcon(R.drawable.ic_videocam_white_24dp);
692 if (ongoingCall.reconnecting) {
693 builder.setContentTitle(
694 mXmppConnectionService.getString(R.string.reconnecting_video_call));
695 } else {
696 builder.setContentTitle(
697 mXmppConnectionService.getString(R.string.ongoing_video_call));
698 }
699 } else {
700 builder.setSmallIcon(R.drawable.ic_call_white_24dp);
701 if (ongoingCall.reconnecting) {
702 builder.setContentTitle(
703 mXmppConnectionService.getString(R.string.reconnecting_call));
704 } else {
705 builder.setContentTitle(mXmppConnectionService.getString(R.string.ongoing_call));
706 }
707 }
708 builder.setContentText(id.account.getRoster().getContact(id.with).getDisplayName());
709 builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
710 builder.setPriority(NotificationCompat.PRIORITY_HIGH);
711 builder.setCategory(NotificationCompat.CATEGORY_CALL);
712 builder.setContentIntent(createPendingRtpSession(id, Intent.ACTION_VIEW, 101));
713 builder.setOngoing(true);
714 builder.addAction(
715 new NotificationCompat.Action.Builder(
716 R.drawable.ic_call_end_white_48dp,
717 mXmppConnectionService.getString(R.string.hang_up),
718 createCallAction(
719 id.sessionId, XmppConnectionService.ACTION_END_CALL, 104))
720 .build());
721 return builder.build();
722 }
723
724 private PendingIntent createPendingRtpSession(
725 final AbstractJingleConnection.Id id, final String action, final int requestCode) {
726 final Intent fullScreenIntent =
727 new Intent(mXmppConnectionService, RtpSessionActivity.class);
728 fullScreenIntent.setAction(action);
729 fullScreenIntent.putExtra(
730 RtpSessionActivity.EXTRA_ACCOUNT,
731 id.account.getJid().asBareJid().toEscapedString());
732 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_WITH, id.with.toEscapedString());
733 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.sessionId);
734 return PendingIntent.getActivity(
735 mXmppConnectionService,
736 requestCode,
737 fullScreenIntent,
738 s()
739 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
740 : PendingIntent.FLAG_UPDATE_CURRENT);
741 }
742
743 public void cancelIncomingCallNotification() {
744 stopSoundAndVibration();
745 cancel(INCOMING_CALL_NOTIFICATION_ID);
746 }
747
748 public boolean stopSoundAndVibration() {
749 int stopped = 0;
750 if (this.currentlyPlayingRingtone != null) {
751 if (this.currentlyPlayingRingtone.isPlaying()) {
752 Log.d(Config.LOGTAG, "stop playing ring tone");
753 ++stopped;
754 }
755 this.currentlyPlayingRingtone.stop();
756 }
757 if (this.vibrationFuture != null && !this.vibrationFuture.isCancelled()) {
758 Log.d(Config.LOGTAG, "stop vibration");
759 this.vibrationFuture.cancel(true);
760 ++stopped;
761 }
762 return stopped > 0;
763 }
764
765 public static void cancelIncomingCallNotification(final Context context) {
766 final NotificationManagerCompat notificationManager =
767 NotificationManagerCompat.from(context);
768 try {
769 notificationManager.cancel(INCOMING_CALL_NOTIFICATION_ID);
770 } catch (RuntimeException e) {
771 Log.d(Config.LOGTAG, "unable to cancel incoming call notification after crash", e);
772 }
773 }
774
775 private void pushNow(final Message message) {
776 mXmppConnectionService.updateUnreadCountBadge();
777 if (!notifyMessage(message)) {
778 Log.d(
779 Config.LOGTAG,
780 message.getConversation().getAccount().getJid().asBareJid()
781 + ": suppressing notification because turned off");
782 return;
783 }
784 final boolean isScreenLocked = mXmppConnectionService.isScreenLocked();
785 if (this.mIsInForeground
786 && !isScreenLocked
787 && this.mOpenConversation == message.getConversation()) {
788 Log.d(
789 Config.LOGTAG,
790 message.getConversation().getAccount().getJid().asBareJid()
791 + ": suppressing notification because conversation is open");
792 return;
793 }
794 synchronized (notifications) {
795 pushToStack(message);
796 final Conversational conversation = message.getConversation();
797 final Account account = conversation.getAccount();
798 final boolean doNotify =
799 (!(this.mIsInForeground && this.mOpenConversation == null) || isScreenLocked)
800 && !account.inGracePeriod()
801 && !this.inMiniGracePeriod(account);
802 updateNotification(doNotify, Collections.singletonList(conversation.getUuid()));
803 }
804 }
805
806 private void pushMissedCall(final Message message) {
807 final Conversational conversation = message.getConversation();
808 final MissedCallsInfo info = mMissedCalls.get(conversation);
809 if (info == null) {
810 mMissedCalls.put(conversation, new MissedCallsInfo(message.getTimeSent()));
811 } else {
812 info.newMissedCall(message.getTimeSent());
813 }
814 }
815
816 public void pushMissedCallNow(final Message message) {
817 synchronized (mMissedCalls) {
818 pushMissedCall(message);
819 updateMissedCallNotifications(Collections.singleton(message.getConversation()));
820 }
821 }
822
823 public void clear(final Conversation conversation) {
824 clearMessages(conversation);
825 clearMissedCalls(conversation);
826 }
827
828 public void clearMessages() {
829 synchronized (notifications) {
830 for (ArrayList<Message> messages : notifications.values()) {
831 markAsReadIfHasDirectReply(messages);
832 }
833 notifications.clear();
834 updateNotification(false);
835 }
836 }
837
838 public void clearMessages(final Conversation conversation) {
839 synchronized (this.mBacklogMessageCounter) {
840 this.mBacklogMessageCounter.remove(conversation);
841 }
842 synchronized (notifications) {
843 markAsReadIfHasDirectReply(conversation);
844 if (notifications.remove(conversation.getUuid()) != null) {
845 cancel(conversation.getUuid(), NOTIFICATION_ID);
846 updateNotification(false, null, true);
847 }
848 }
849 }
850
851 public void clearMissedCalls() {
852 synchronized (mMissedCalls) {
853 for (final Conversational conversation : mMissedCalls.keySet()) {
854 cancel(conversation.getUuid(), MISSED_CALL_NOTIFICATION_ID);
855 }
856 mMissedCalls.clear();
857 updateMissedCallNotifications(null);
858 }
859 }
860
861 public void clearMissedCalls(final Conversation conversation) {
862 synchronized (mMissedCalls) {
863 if (mMissedCalls.remove(conversation) != null) {
864 cancel(conversation.getUuid(), MISSED_CALL_NOTIFICATION_ID);
865 updateMissedCallNotifications(null);
866 }
867 }
868 }
869
870 private void markAsReadIfHasDirectReply(final Conversation conversation) {
871 markAsReadIfHasDirectReply(notifications.get(conversation.getUuid()));
872 }
873
874 private void markAsReadIfHasDirectReply(final ArrayList<Message> messages) {
875 if (messages != null && messages.size() > 0) {
876 Message last = messages.get(messages.size() - 1);
877 if (last.getStatus() != Message.STATUS_RECEIVED) {
878 if (mXmppConnectionService.markRead((Conversation) last.getConversation(), false)) {
879 mXmppConnectionService.updateConversationUi();
880 }
881 }
882 }
883 }
884
885 private void setNotificationColor(final Builder mBuilder) {
886 TypedValue typedValue = new TypedValue();
887 mXmppConnectionService.getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
888 mBuilder.setColor(typedValue.data);
889 }
890
891 public void updateNotification() {
892 synchronized (notifications) {
893 updateNotification(false);
894 }
895 }
896
897 private void updateNotification(final boolean notify) {
898 updateNotification(notify, null, false);
899 }
900
901 private void updateNotification(final boolean notify, final List<String> conversations) {
902 updateNotification(notify, conversations, false);
903 }
904
905 private void updateNotification(
906 final boolean notify, final List<String> conversations, final boolean summaryOnly) {
907 final SharedPreferences preferences =
908 PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
909
910 final boolean quiteHours = isQuietHours();
911
912 final boolean notifyOnlyOneChild =
913 notify
914 && conversations != null
915 && conversations.size()
916 == 1; // if this check is changed to > 0 catchup messages will
917 // create one notification per conversation
918
919 if (notifications.size() == 0) {
920 cancel(NOTIFICATION_ID);
921 } else {
922 if (notify) {
923 this.markLastNotification();
924 }
925 final Builder mBuilder;
926 if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
927 mBuilder =
928 buildSingleConversations(
929 notifications.values().iterator().next(), notify, quiteHours);
930 modifyForSoundVibrationAndLight(mBuilder, notify, quiteHours, preferences);
931 notify(NOTIFICATION_ID, mBuilder.build());
932 } else {
933 mBuilder = buildMultipleConversation(notify, quiteHours);
934 if (notifyOnlyOneChild) {
935 mBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
936 }
937 modifyForSoundVibrationAndLight(mBuilder, notify, quiteHours, preferences);
938 if (!summaryOnly) {
939 for (Map.Entry<String, ArrayList<Message>> entry : notifications.entrySet()) {
940 String uuid = entry.getKey();
941 final boolean notifyThis =
942 notifyOnlyOneChild ? conversations.contains(uuid) : notify;
943 Builder singleBuilder =
944 buildSingleConversations(entry.getValue(), notifyThis, quiteHours);
945 if (!notifyOnlyOneChild) {
946 singleBuilder.setGroupAlertBehavior(
947 NotificationCompat.GROUP_ALERT_SUMMARY);
948 }
949 modifyForSoundVibrationAndLight(
950 singleBuilder, notifyThis, quiteHours, preferences);
951 singleBuilder.setGroup(MESSAGES_GROUP);
952 setNotificationColor(singleBuilder);
953 notify(entry.getKey(), NOTIFICATION_ID, singleBuilder.build());
954 }
955 }
956 notify(NOTIFICATION_ID, mBuilder.build());
957 }
958 }
959 }
960
961 private void updateMissedCallNotifications(final Set<Conversational> update) {
962 if (mMissedCalls.isEmpty()) {
963 cancel(MISSED_CALL_NOTIFICATION_ID);
964 return;
965 }
966 if (mMissedCalls.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
967 final Conversational conversation = mMissedCalls.keySet().iterator().next();
968 final MissedCallsInfo info = mMissedCalls.values().iterator().next();
969 final Notification notification = missedCall(conversation, info);
970 notify(MISSED_CALL_NOTIFICATION_ID, notification);
971 } else {
972 final Notification summary = missedCallsSummary();
973 notify(MISSED_CALL_NOTIFICATION_ID, summary);
974 if (update != null) {
975 for (final Conversational conversation : update) {
976 final MissedCallsInfo info = mMissedCalls.get(conversation);
977 if (info != null) {
978 final Notification notification = missedCall(conversation, info);
979 notify(conversation.getUuid(), MISSED_CALL_NOTIFICATION_ID, notification);
980 }
981 }
982 }
983 }
984 }
985
986 private void modifyForSoundVibrationAndLight(
987 Builder mBuilder, boolean notify, boolean quietHours, SharedPreferences preferences) {
988 final Resources resources = mXmppConnectionService.getResources();
989 final String ringtone =
990 preferences.getString(
991 "notification_ringtone",
992 resources.getString(R.string.notification_ringtone));
993 final boolean vibrate =
994 preferences.getBoolean(
995 "vibrate_on_notification",
996 resources.getBoolean(R.bool.vibrate_on_notification));
997 final boolean led = preferences.getBoolean("led", resources.getBoolean(R.bool.led));
998 final boolean headsup =
999 preferences.getBoolean(
1000 "notification_headsup", resources.getBoolean(R.bool.headsup_notifications));
1001 if (notify && !quietHours) {
1002 if (vibrate) {
1003 final int dat = 70;
1004 final long[] pattern = {0, 3 * dat, dat, dat};
1005 mBuilder.setVibrate(pattern);
1006 } else {
1007 mBuilder.setVibrate(new long[] {0});
1008 }
1009 Uri uri = Uri.parse(ringtone);
1010 try {
1011 mBuilder.setSound(fixRingtoneUri(uri));
1012 } catch (SecurityException e) {
1013 Log.d(Config.LOGTAG, "unable to use custom notification sound " + uri.toString());
1014 }
1015 } else {
1016 mBuilder.setLocalOnly(true);
1017 }
1018 mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
1019 mBuilder.setPriority(
1020 notify
1021 ? (headsup
1022 ? NotificationCompat.PRIORITY_HIGH
1023 : NotificationCompat.PRIORITY_DEFAULT)
1024 : NotificationCompat.PRIORITY_LOW);
1025 setNotificationColor(mBuilder);
1026 mBuilder.setDefaults(0);
1027 if (led) {
1028 mBuilder.setLights(LED_COLOR, 2000, 3000);
1029 }
1030 }
1031
1032 private void modifyIncomingCall(final Builder mBuilder) {
1033 mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
1034 setNotificationColor(mBuilder);
1035 mBuilder.setLights(LED_COLOR, 2000, 3000);
1036 }
1037
1038 private Uri fixRingtoneUri(Uri uri) {
1039 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && "file".equals(uri.getScheme())) {
1040 return FileBackend.getUriForFile(mXmppConnectionService, new File(uri.getPath()));
1041 } else {
1042 return uri;
1043 }
1044 }
1045
1046 private Notification missedCallsSummary() {
1047 final Builder publicBuilder = buildMissedCallsSummary(true);
1048 final Builder builder = buildMissedCallsSummary(false);
1049 builder.setPublicVersion(publicBuilder.build());
1050 return builder.build();
1051 }
1052
1053 private Builder buildMissedCallsSummary(boolean publicVersion) {
1054 final Builder builder =
1055 new NotificationCompat.Builder(mXmppConnectionService, "missed_calls");
1056 int totalCalls = 0;
1057 final List<String> names = new ArrayList<>();
1058 long lastTime = 0;
1059 for (final Map.Entry<Conversational, MissedCallsInfo> entry : mMissedCalls.entrySet()) {
1060 final Conversational conversation = entry.getKey();
1061 final MissedCallsInfo missedCallsInfo = entry.getValue();
1062 names.add(conversation.getContact().getDisplayName());
1063 totalCalls += missedCallsInfo.getNumberOfCalls();
1064 lastTime = Math.max(lastTime, missedCallsInfo.getLastTime());
1065 }
1066 final String title =
1067 (totalCalls == 1)
1068 ? mXmppConnectionService.getString(R.string.missed_call)
1069 : (mMissedCalls.size() == 1)
1070 ? mXmppConnectionService
1071 .getResources()
1072 .getQuantityString(
1073 R.plurals.n_missed_calls, totalCalls, totalCalls)
1074 : mXmppConnectionService
1075 .getResources()
1076 .getQuantityString(
1077 R.plurals.n_missed_calls_from_m_contacts,
1078 mMissedCalls.size(),
1079 totalCalls,
1080 mMissedCalls.size());
1081 builder.setContentTitle(title);
1082 builder.setTicker(title);
1083 if (!publicVersion) {
1084 builder.setContentText(Joiner.on(", ").join(names));
1085 }
1086 builder.setSmallIcon(R.drawable.ic_call_missed_white_24db);
1087 builder.setGroupSummary(true);
1088 builder.setGroup(MISSED_CALLS_GROUP);
1089 builder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
1090 builder.setCategory(NotificationCompat.CATEGORY_CALL);
1091 builder.setWhen(lastTime);
1092 if (!mMissedCalls.isEmpty()) {
1093 final Conversational firstConversation = mMissedCalls.keySet().iterator().next();
1094 builder.setContentIntent(createContentIntent(firstConversation));
1095 }
1096 builder.setDeleteIntent(createMissedCallsDeleteIntent(null));
1097 modifyMissedCall(builder);
1098 return builder;
1099 }
1100
1101 private Notification missedCall(final Conversational conversation, final MissedCallsInfo info) {
1102 final Builder publicBuilder = buildMissedCall(conversation, info, true);
1103 final Builder builder = buildMissedCall(conversation, info, false);
1104 builder.setPublicVersion(publicBuilder.build());
1105 return builder.build();
1106 }
1107
1108 private Builder buildMissedCall(
1109 final Conversational conversation, final MissedCallsInfo info, boolean publicVersion) {
1110 final Builder builder =
1111 new NotificationCompat.Builder(mXmppConnectionService, "missed_calls");
1112 final String title =
1113 (info.getNumberOfCalls() == 1)
1114 ? mXmppConnectionService.getString(R.string.missed_call)
1115 : mXmppConnectionService
1116 .getResources()
1117 .getQuantityString(
1118 R.plurals.n_missed_calls,
1119 info.getNumberOfCalls(),
1120 info.getNumberOfCalls());
1121 builder.setContentTitle(title);
1122 if (mXmppConnectionService.getAccounts().size() > 1) {
1123 builder.setSubText(conversation.getAccount().getJid().asBareJid().toString());
1124 }
1125 final String name = conversation.getContact().getDisplayName();
1126 if (publicVersion) {
1127 builder.setTicker(title);
1128 } else {
1129 builder.setTicker(
1130 mXmppConnectionService
1131 .getResources()
1132 .getQuantityString(
1133 R.plurals.n_missed_calls_from_x,
1134 info.getNumberOfCalls(),
1135 info.getNumberOfCalls(),
1136 name));
1137 builder.setContentText(name);
1138 }
1139 builder.setSmallIcon(R.drawable.ic_call_missed_white_24db);
1140 builder.setGroup(MISSED_CALLS_GROUP);
1141 builder.setCategory(NotificationCompat.CATEGORY_CALL);
1142 builder.setWhen(info.getLastTime());
1143 builder.setContentIntent(createContentIntent(conversation));
1144 builder.setDeleteIntent(createMissedCallsDeleteIntent(conversation));
1145 if (!publicVersion && conversation instanceof Conversation) {
1146 builder.setLargeIcon(
1147 mXmppConnectionService
1148 .getAvatarService()
1149 .get(
1150 (Conversation) conversation,
1151 AvatarService.getSystemUiAvatarSize(mXmppConnectionService)));
1152 }
1153 modifyMissedCall(builder);
1154 return builder;
1155 }
1156
1157 private void modifyMissedCall(final Builder builder) {
1158 final SharedPreferences preferences =
1159 PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
1160 final Resources resources = mXmppConnectionService.getResources();
1161 final boolean led = preferences.getBoolean("led", resources.getBoolean(R.bool.led));
1162 if (led) {
1163 builder.setLights(LED_COLOR, 2000, 3000);
1164 }
1165 builder.setPriority(NotificationCompat.PRIORITY_HIGH);
1166 builder.setSound(null);
1167 setNotificationColor(builder);
1168 }
1169
1170 private Builder buildMultipleConversation(final boolean notify, final boolean quietHours) {
1171 final Builder mBuilder =
1172 new NotificationCompat.Builder(
1173 mXmppConnectionService,
1174 quietHours ? "quiet_hours" : (notify ? "messages" : "silent_messages"));
1175 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
1176 style.setBigContentTitle(
1177 mXmppConnectionService
1178 .getResources()
1179 .getQuantityString(
1180 R.plurals.x_unread_conversations,
1181 notifications.size(),
1182 notifications.size()));
1183 final List<String> names = new ArrayList<>();
1184 Conversation conversation = null;
1185 for (final ArrayList<Message> messages : notifications.values()) {
1186 if (messages.isEmpty()) {
1187 continue;
1188 }
1189 conversation = (Conversation) messages.get(0).getConversation();
1190 final String name = conversation.getName().toString();
1191 SpannableString styledString;
1192 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
1193 int count = messages.size();
1194 styledString =
1195 new SpannableString(
1196 name
1197 + ": "
1198 + mXmppConnectionService
1199 .getResources()
1200 .getQuantityString(
1201 R.plurals.x_messages, count, count));
1202 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
1203 style.addLine(styledString);
1204 } else {
1205 styledString =
1206 new SpannableString(
1207 name
1208 + ": "
1209 + UIHelper.getMessagePreview(
1210 mXmppConnectionService, messages.get(0))
1211 .first);
1212 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
1213 style.addLine(styledString);
1214 }
1215 names.add(name);
1216 }
1217 final String contentTitle =
1218 mXmppConnectionService
1219 .getResources()
1220 .getQuantityString(
1221 R.plurals.x_unread_conversations,
1222 notifications.size(),
1223 notifications.size());
1224 mBuilder.setContentTitle(contentTitle);
1225 mBuilder.setTicker(contentTitle);
1226 mBuilder.setContentText(Joiner.on(", ").join(names));
1227 mBuilder.setStyle(style);
1228 if (conversation != null) {
1229 mBuilder.setContentIntent(createContentIntent(conversation));
1230 }
1231 mBuilder.setGroupSummary(true);
1232 mBuilder.setGroup(MESSAGES_GROUP);
1233 mBuilder.setDeleteIntent(createDeleteIntent(null));
1234 mBuilder.setSmallIcon(R.drawable.ic_notification);
1235 return mBuilder;
1236 }
1237
1238 private Builder buildSingleConversations(
1239 final ArrayList<Message> messages, final boolean notify, final boolean quietHours) {
1240 final Builder mBuilder =
1241 new NotificationCompat.Builder(
1242 mXmppConnectionService,
1243 quietHours ? "quiet_hours" : (notify ? "messages" : "silent_messages"));
1244 if (messages.size() >= 1) {
1245 final Conversation conversation = (Conversation) messages.get(0).getConversation();
1246 mBuilder.setLargeIcon(
1247 mXmppConnectionService
1248 .getAvatarService()
1249 .get(
1250 conversation,
1251 AvatarService.getSystemUiAvatarSize(mXmppConnectionService)));
1252 mBuilder.setContentTitle(conversation.getName());
1253 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
1254 int count = messages.size();
1255 mBuilder.setContentText(
1256 mXmppConnectionService
1257 .getResources()
1258 .getQuantityString(R.plurals.x_messages, count, count));
1259 } else {
1260 Message message;
1261 // TODO starting with Android 9 we might want to put images in MessageStyle
1262 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P
1263 && (message = getImage(messages)) != null) {
1264 modifyForImage(mBuilder, message, messages);
1265 } else {
1266 modifyForTextOnly(mBuilder, messages);
1267 }
1268 RemoteInput remoteInput =
1269 new RemoteInput.Builder("text_reply")
1270 .setLabel(
1271 UIHelper.getMessageHint(
1272 mXmppConnectionService, conversation))
1273 .build();
1274 PendingIntent markAsReadPendingIntent = createReadPendingIntent(conversation);
1275 NotificationCompat.Action markReadAction =
1276 new NotificationCompat.Action.Builder(
1277 R.drawable.ic_drafts_white_24dp,
1278 mXmppConnectionService.getString(R.string.mark_as_read),
1279 markAsReadPendingIntent)
1280 .setSemanticAction(
1281 NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ)
1282 .setShowsUserInterface(false)
1283 .build();
1284 final String replyLabel = mXmppConnectionService.getString(R.string.reply);
1285 final String lastMessageUuid = Iterables.getLast(messages).getUuid();
1286 final NotificationCompat.Action replyAction =
1287 new NotificationCompat.Action.Builder(
1288 R.drawable.ic_send_text_offline,
1289 replyLabel,
1290 createReplyIntent(conversation, lastMessageUuid, false))
1291 .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY)
1292 .setShowsUserInterface(false)
1293 .addRemoteInput(remoteInput)
1294 .build();
1295 final NotificationCompat.Action wearReplyAction =
1296 new NotificationCompat.Action.Builder(
1297 R.drawable.ic_wear_reply,
1298 replyLabel,
1299 createReplyIntent(conversation, lastMessageUuid, true))
1300 .addRemoteInput(remoteInput)
1301 .build();
1302 mBuilder.extend(
1303 new NotificationCompat.WearableExtender().addAction(wearReplyAction));
1304 int addedActionsCount = 1;
1305 mBuilder.addAction(markReadAction);
1306 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1307 mBuilder.addAction(replyAction);
1308 ++addedActionsCount;
1309 }
1310
1311 if (displaySnoozeAction(messages)) {
1312 String label = mXmppConnectionService.getString(R.string.snooze);
1313 PendingIntent pendingSnoozeIntent = createSnoozeIntent(conversation);
1314 NotificationCompat.Action snoozeAction =
1315 new NotificationCompat.Action.Builder(
1316 R.drawable.ic_notifications_paused_white_24dp,
1317 label,
1318 pendingSnoozeIntent)
1319 .build();
1320 mBuilder.addAction(snoozeAction);
1321 ++addedActionsCount;
1322 }
1323 if (addedActionsCount < 3) {
1324 final Message firstLocationMessage = getFirstLocationMessage(messages);
1325 if (firstLocationMessage != null) {
1326 final PendingIntent pendingShowLocationIntent =
1327 createShowLocationIntent(firstLocationMessage);
1328 if (pendingShowLocationIntent != null) {
1329 final String label =
1330 mXmppConnectionService
1331 .getResources()
1332 .getString(R.string.show_location);
1333 NotificationCompat.Action locationAction =
1334 new NotificationCompat.Action.Builder(
1335 R.drawable.ic_room_white_24dp,
1336 label,
1337 pendingShowLocationIntent)
1338 .build();
1339 mBuilder.addAction(locationAction);
1340 ++addedActionsCount;
1341 }
1342 }
1343 }
1344 if (addedActionsCount < 3) {
1345 Message firstDownloadableMessage = getFirstDownloadableMessage(messages);
1346 if (firstDownloadableMessage != null) {
1347 String label =
1348 mXmppConnectionService
1349 .getResources()
1350 .getString(
1351 R.string.download_x_file,
1352 UIHelper.getFileDescriptionString(
1353 mXmppConnectionService,
1354 firstDownloadableMessage));
1355 PendingIntent pendingDownloadIntent =
1356 createDownloadIntent(firstDownloadableMessage);
1357 NotificationCompat.Action downloadAction =
1358 new NotificationCompat.Action.Builder(
1359 R.drawable.ic_file_download_white_24dp,
1360 label,
1361 pendingDownloadIntent)
1362 .build();
1363 mBuilder.addAction(downloadAction);
1364 ++addedActionsCount;
1365 }
1366 }
1367 }
1368 if (conversation.getMode() == Conversation.MODE_SINGLE) {
1369 Contact contact = conversation.getContact();
1370 Uri systemAccount = contact.getSystemAccount();
1371 if (systemAccount != null) {
1372 mBuilder.addPerson(systemAccount.toString());
1373 }
1374 }
1375 mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
1376 mBuilder.setSmallIcon(R.drawable.ic_notification);
1377 mBuilder.setDeleteIntent(createDeleteIntent(conversation));
1378 mBuilder.setContentIntent(createContentIntent(conversation));
1379
1380 ShortcutInfoCompat info = mXmppConnectionService.getShortcutService().getShortcutInfoCompat(conversation.getContact());
1381 mBuilder.setShortcutInfo(info);
1382 if (Build.VERSION.SDK_INT >= 30) {
1383 mXmppConnectionService.getSystemService(ShortcutManager.class).pushDynamicShortcut(info.toShortcutInfo());
1384 // mBuilder.setBubbleMetadata(new NotificationCompat.BubbleMetadata.Builder(info.getId()).build());
1385 }
1386 }
1387 return mBuilder;
1388 }
1389
1390 private void modifyForImage(
1391 final Builder builder, final Message message, final ArrayList<Message> messages) {
1392 try {
1393 final Bitmap bitmap = mXmppConnectionService.getFileBackend().getThumbnailBitmap(message, mXmppConnectionService.getResources(), getPixel(288));
1394 final ArrayList<Message> tmp = new ArrayList<>();
1395 for (final Message msg : messages) {
1396 if (msg.getType() == Message.TYPE_TEXT && msg.getTransferable() == null) {
1397 tmp.add(msg);
1398 }
1399 }
1400 final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
1401 bigPictureStyle.bigPicture(bitmap);
1402 if (tmp.size() > 0) {
1403 CharSequence text = getMergedBodies(tmp);
1404 bigPictureStyle.setSummaryText(text);
1405 builder.setContentText(text);
1406 builder.setTicker(text);
1407 } else {
1408 final String description =
1409 UIHelper.getFileDescriptionString(mXmppConnectionService, message);
1410 builder.setContentText(description);
1411 builder.setTicker(description);
1412 }
1413 builder.setStyle(bigPictureStyle);
1414 } catch (final IOException e) {
1415 modifyForTextOnly(builder, messages);
1416 }
1417 }
1418
1419 private Person getPerson(Message message) {
1420 final Contact contact = message.getContact();
1421 final Person.Builder builder = new Person.Builder();
1422 if (contact != null) {
1423 builder.setName(contact.getDisplayName());
1424 final Uri uri = contact.getSystemAccount();
1425 if (uri != null) {
1426 builder.setUri(uri.toString());
1427 }
1428 } else {
1429 builder.setName(UIHelper.getMessageDisplayName(message));
1430 }
1431 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
1432 final Jid jid = contact == null ? message.getCounterpart() : contact.getJid();
1433 builder.setKey(jid.toString());
1434 final Conversation c = mXmppConnectionService.find(message.getConversation().getAccount(), jid);
1435 if (c != null) {
1436 builder.setImportant(c.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false));
1437 }
1438 builder.setIcon(
1439 IconCompat.createWithBitmap(
1440 mXmppConnectionService
1441 .getAvatarService()
1442 .get(
1443 message,
1444 AvatarService.getSystemUiAvatarSize(
1445 mXmppConnectionService),
1446 false)));
1447 }
1448 return builder.build();
1449 }
1450
1451 private Person getPerson(Contact contact) {
1452 final Person.Builder builder = new Person.Builder();
1453 builder.setName(contact.getDisplayName());
1454 final Uri uri = contact.getSystemAccount();
1455 if (uri != null) {
1456 builder.setUri(uri.toString());
1457 }
1458 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
1459 final Jid jid = contact.getJid();
1460 builder.setKey(jid.toString());
1461 final Conversation c = mXmppConnectionService.find(contact.getAccount(), jid);
1462 if (c != null) {
1463 builder.setImportant(c.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false));
1464 }
1465 builder.setIcon(
1466 IconCompat.createWithBitmap(
1467 mXmppConnectionService
1468 .getAvatarService()
1469 .get(
1470 contact,
1471 AvatarService.getSystemUiAvatarSize(
1472 mXmppConnectionService),
1473 false)));
1474 }
1475 return builder.build();
1476 }
1477
1478 private void modifyForTextOnly(final Builder builder, final ArrayList<Message> messages) {
1479 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1480 final Conversation conversation = (Conversation) messages.get(0).getConversation();
1481 final Person.Builder meBuilder =
1482 new Person.Builder().setName(mXmppConnectionService.getString(R.string.me));
1483 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
1484 meBuilder.setIcon(
1485 IconCompat.createWithBitmap(
1486 mXmppConnectionService
1487 .getAvatarService()
1488 .get(
1489 conversation.getAccount(),
1490 AvatarService.getSystemUiAvatarSize(
1491 mXmppConnectionService))));
1492 }
1493 final Person me = meBuilder.build();
1494 NotificationCompat.MessagingStyle messagingStyle =
1495 new NotificationCompat.MessagingStyle(me);
1496 final boolean multiple = conversation.getMode() == Conversation.MODE_MULTI || messages.get(0).getTrueCounterpart() != null;
1497 if (multiple) {
1498 messagingStyle.setConversationTitle(conversation.getName());
1499 }
1500 for (Message message : messages) {
1501 final Person sender =
1502 message.getStatus() == Message.STATUS_RECEIVED ? getPerson(message) : null;
1503 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && isImageMessage(message)) {
1504 final Uri dataUri =
1505 FileBackend.getMediaUri(
1506 mXmppConnectionService,
1507 mXmppConnectionService.getFileBackend().getFile(message));
1508 NotificationCompat.MessagingStyle.Message imageMessage =
1509 new NotificationCompat.MessagingStyle.Message(
1510 UIHelper.getMessagePreview(mXmppConnectionService, message)
1511 .first,
1512 message.getTimeSent(),
1513 sender);
1514 if (dataUri != null) {
1515 imageMessage.setData(message.getMimeType(), dataUri);
1516 }
1517 messagingStyle.addMessage(imageMessage);
1518 } else {
1519 messagingStyle.addMessage(
1520 UIHelper.getMessagePreview(mXmppConnectionService, message).first,
1521 message.getTimeSent(),
1522 sender);
1523 }
1524 }
1525 messagingStyle.setGroupConversation(multiple);
1526 builder.setStyle(messagingStyle);
1527 } else {
1528 if (messages.get(0).getConversation().getMode() == Conversation.MODE_SINGLE && messages.get(0).getTrueCounterpart() == null) {
1529 builder.setStyle(
1530 new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
1531 final CharSequence preview =
1532 UIHelper.getMessagePreview(
1533 mXmppConnectionService, messages.get(messages.size() - 1))
1534 .first;
1535 builder.setContentText(preview);
1536 builder.setTicker(preview);
1537 builder.setNumber(messages.size());
1538 } else {
1539 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
1540 SpannableString styledString;
1541 for (Message message : messages) {
1542 final String name = UIHelper.getMessageDisplayName(message);
1543 styledString = new SpannableString(name + ": " + message.getBody());
1544 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
1545 style.addLine(styledString);
1546 }
1547 builder.setStyle(style);
1548 int count = messages.size();
1549 if (count == 1) {
1550 final String name = UIHelper.getMessageDisplayName(messages.get(0));
1551 styledString = new SpannableString(name + ": " + messages.get(0).getBody());
1552 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
1553 builder.setContentText(styledString);
1554 builder.setTicker(styledString);
1555 } else {
1556 final String text =
1557 mXmppConnectionService
1558 .getResources()
1559 .getQuantityString(R.plurals.x_messages, count, count);
1560 builder.setContentText(text);
1561 builder.setTicker(text);
1562 }
1563 }
1564 }
1565 }
1566
1567 private Message getImage(final Iterable<Message> messages) {
1568 Message image = null;
1569 for (final Message message : messages) {
1570 if (message.getStatus() != Message.STATUS_RECEIVED) {
1571 return null;
1572 }
1573 if (isImageMessage(message)) {
1574 image = message;
1575 }
1576 }
1577 return image;
1578 }
1579
1580 private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
1581 for (final Message message : messages) {
1582 if (message.getTransferable() != null
1583 || (message.getType() == Message.TYPE_TEXT && message.treatAsDownloadable())) {
1584 return message;
1585 }
1586 }
1587 return null;
1588 }
1589
1590 private Message getFirstLocationMessage(final Iterable<Message> messages) {
1591 for (final Message message : messages) {
1592 if (message.isGeoUri()) {
1593 return message;
1594 }
1595 }
1596 return null;
1597 }
1598
1599 private CharSequence getMergedBodies(final ArrayList<Message> messages) {
1600 final StringBuilder text = new StringBuilder();
1601 for (Message message : messages) {
1602 if (text.length() != 0) {
1603 text.append("\n");
1604 }
1605 text.append(UIHelper.getMessagePreview(mXmppConnectionService, message).first);
1606 }
1607 return text.toString();
1608 }
1609
1610 private PendingIntent createShowLocationIntent(final Message message) {
1611 Iterable<Intent> intents =
1612 GeoHelper.createGeoIntentsFromMessage(mXmppConnectionService, message);
1613 for (final Intent intent : intents) {
1614 if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
1615 return PendingIntent.getActivity(
1616 mXmppConnectionService,
1617 generateRequestCode(message.getConversation(), 18),
1618 intent,
1619 s()
1620 ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1621 : PendingIntent.FLAG_UPDATE_CURRENT);
1622 }
1623 }
1624 return null;
1625 }
1626
1627 private PendingIntent createContentIntent(
1628 final String conversationUuid, final String downloadMessageUuid) {
1629 final Intent viewConversationIntent =
1630 new Intent(mXmppConnectionService, ConversationsActivity.class);
1631 viewConversationIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
1632 viewConversationIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversationUuid);
1633 if (downloadMessageUuid != null) {
1634 viewConversationIntent.putExtra(
1635 ConversationsActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
1636 return PendingIntent.getActivity(
1637 mXmppConnectionService,
1638 generateRequestCode(conversationUuid, 8),
1639 viewConversationIntent,
1640 s()
1641 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1642 : PendingIntent.FLAG_UPDATE_CURRENT);
1643 } else {
1644 return PendingIntent.getActivity(
1645 mXmppConnectionService,
1646 generateRequestCode(conversationUuid, 10),
1647 viewConversationIntent,
1648 s()
1649 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1650 : PendingIntent.FLAG_UPDATE_CURRENT);
1651 }
1652 }
1653
1654 private int generateRequestCode(String uuid, int actionId) {
1655 return (actionId * NOTIFICATION_ID_MULTIPLIER)
1656 + (uuid.hashCode() % NOTIFICATION_ID_MULTIPLIER);
1657 }
1658
1659 private int generateRequestCode(Conversational conversation, int actionId) {
1660 return generateRequestCode(conversation.getUuid(), actionId);
1661 }
1662
1663 private PendingIntent createDownloadIntent(final Message message) {
1664 return createContentIntent(message.getConversationUuid(), message.getUuid());
1665 }
1666
1667 private PendingIntent createContentIntent(final Conversational conversation) {
1668 return createContentIntent(conversation.getUuid(), null);
1669 }
1670
1671 private PendingIntent createDeleteIntent(final Conversation conversation) {
1672 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1673 intent.setAction(XmppConnectionService.ACTION_CLEAR_MESSAGE_NOTIFICATION);
1674 if (conversation != null) {
1675 intent.putExtra("uuid", conversation.getUuid());
1676 return PendingIntent.getService(
1677 mXmppConnectionService,
1678 generateRequestCode(conversation, 20),
1679 intent,
1680 s()
1681 ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1682 : PendingIntent.FLAG_UPDATE_CURRENT);
1683 }
1684 return PendingIntent.getService(
1685 mXmppConnectionService,
1686 0,
1687 intent,
1688 s()
1689 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1690 : PendingIntent.FLAG_UPDATE_CURRENT);
1691 }
1692
1693 private PendingIntent createMissedCallsDeleteIntent(final Conversational conversation) {
1694 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1695 intent.setAction(XmppConnectionService.ACTION_CLEAR_MISSED_CALL_NOTIFICATION);
1696 if (conversation != null) {
1697 intent.putExtra("uuid", conversation.getUuid());
1698 return PendingIntent.getService(
1699 mXmppConnectionService,
1700 generateRequestCode(conversation, 21),
1701 intent,
1702 s()
1703 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1704 : PendingIntent.FLAG_UPDATE_CURRENT);
1705 }
1706 return PendingIntent.getService(
1707 mXmppConnectionService,
1708 1,
1709 intent,
1710 s()
1711 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1712 : PendingIntent.FLAG_UPDATE_CURRENT);
1713 }
1714
1715 private PendingIntent createReplyIntent(
1716 final Conversation conversation,
1717 final String lastMessageUuid,
1718 final boolean dismissAfterReply) {
1719 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1720 intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
1721 intent.putExtra("uuid", conversation.getUuid());
1722 intent.putExtra("dismiss_notification", dismissAfterReply);
1723 intent.putExtra("last_message_uuid", lastMessageUuid);
1724 final int id = generateRequestCode(conversation, dismissAfterReply ? 12 : 14);
1725 return PendingIntent.getService(
1726 mXmppConnectionService,
1727 id,
1728 intent,
1729 s()
1730 ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1731 : PendingIntent.FLAG_UPDATE_CURRENT);
1732 }
1733
1734 private PendingIntent createReadPendingIntent(Conversation conversation) {
1735 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1736 intent.setAction(XmppConnectionService.ACTION_MARK_AS_READ);
1737 intent.putExtra("uuid", conversation.getUuid());
1738 intent.setPackage(mXmppConnectionService.getPackageName());
1739 return PendingIntent.getService(
1740 mXmppConnectionService,
1741 generateRequestCode(conversation, 16),
1742 intent,
1743 s()
1744 ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1745 : PendingIntent.FLAG_UPDATE_CURRENT);
1746 }
1747
1748 private PendingIntent createCallAction(String sessionId, final String action, int requestCode) {
1749 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1750 intent.setAction(action);
1751 intent.setPackage(mXmppConnectionService.getPackageName());
1752 intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, sessionId);
1753 return PendingIntent.getService(
1754 mXmppConnectionService,
1755 requestCode,
1756 intent,
1757 s()
1758 ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1759 : PendingIntent.FLAG_UPDATE_CURRENT);
1760 }
1761
1762 private PendingIntent createSnoozeIntent(Conversation conversation) {
1763 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1764 intent.setAction(XmppConnectionService.ACTION_SNOOZE);
1765 intent.putExtra("uuid", conversation.getUuid());
1766 intent.setPackage(mXmppConnectionService.getPackageName());
1767 return PendingIntent.getService(
1768 mXmppConnectionService,
1769 generateRequestCode(conversation, 22),
1770 intent,
1771 s()
1772 ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1773 : PendingIntent.FLAG_UPDATE_CURRENT);
1774 }
1775
1776 private PendingIntent createTryAgainIntent() {
1777 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1778 intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
1779 return PendingIntent.getService(
1780 mXmppConnectionService,
1781 45,
1782 intent,
1783 s()
1784 ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1785 : PendingIntent.FLAG_UPDATE_CURRENT);
1786 }
1787
1788 private PendingIntent createDismissErrorIntent() {
1789 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1790 intent.setAction(XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS);
1791 return PendingIntent.getService(
1792 mXmppConnectionService,
1793 69,
1794 intent,
1795 s()
1796 ? PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1797 : PendingIntent.FLAG_UPDATE_CURRENT);
1798 }
1799
1800 private boolean wasHighlightedOrPrivate(final Message message) {
1801 if (message.getConversation() instanceof Conversation) {
1802 Conversation conversation = (Conversation) message.getConversation();
1803 final MucOptions.User sender = conversation.getMucOptions().findUserByFullJid(message.getCounterpart());
1804 if (sender != null && sender.getAffiliation().ranks(MucOptions.Affiliation.MEMBER) && message.isAttention()) {
1805 return true;
1806 }
1807
1808 final String nick = conversation.getMucOptions().getActualNick();
1809 final Pattern highlight = generateNickHighlightPattern(nick);
1810 if (message.getBody() == null || nick == null) {
1811 return false;
1812 }
1813 final Matcher m = highlight.matcher(message.getBody());
1814 return (m.find() || message.isPrivateMessage());
1815 } else {
1816 return false;
1817 }
1818 }
1819
1820 public void setOpenConversation(final Conversation conversation) {
1821 this.mOpenConversation = conversation;
1822 }
1823
1824 public void setIsInForeground(final boolean foreground) {
1825 this.mIsInForeground = foreground;
1826 }
1827
1828 private int getPixel(final int dp) {
1829 final DisplayMetrics metrics = mXmppConnectionService.getResources().getDisplayMetrics();
1830 return ((int) (dp * metrics.density));
1831 }
1832
1833 private void markLastNotification() {
1834 this.mLastNotification = SystemClock.elapsedRealtime();
1835 }
1836
1837 private boolean inMiniGracePeriod(final Account account) {
1838 final int miniGrace =
1839 account.getStatus() == Account.State.ONLINE
1840 ? Config.MINI_GRACE_PERIOD
1841 : Config.MINI_GRACE_PERIOD * 2;
1842 return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
1843 }
1844
1845 Notification createForegroundNotification() {
1846 final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1847 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.app_name));
1848 final List<Account> accounts = mXmppConnectionService.getAccounts();
1849 int enabled = 0;
1850 int connected = 0;
1851 if (accounts != null) {
1852 for (Account account : accounts) {
1853 if (account.isOnlineAndConnected()) {
1854 connected++;
1855 enabled++;
1856 } else if (account.isEnabled()) {
1857 enabled++;
1858 }
1859 }
1860 }
1861 mBuilder.setContentText(
1862 mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
1863 final PendingIntent openIntent = createOpenConversationsIntent();
1864 if (openIntent != null) {
1865 mBuilder.setContentIntent(openIntent);
1866 }
1867 mBuilder.setWhen(0)
1868 .setPriority(Notification.PRIORITY_MIN)
1869 .setSmallIcon(
1870 connected > 0
1871 ? R.drawable.ic_link_white_24dp
1872 : R.drawable.ic_link_off_white_24dp)
1873 .setLocalOnly(true);
1874
1875 if (Compatibility.runsTwentySix()) {
1876 mBuilder.setChannelId("foreground");
1877 }
1878
1879 return mBuilder.build();
1880 }
1881
1882 private PendingIntent createOpenConversationsIntent() {
1883 try {
1884 return PendingIntent.getActivity(
1885 mXmppConnectionService,
1886 0,
1887 new Intent(mXmppConnectionService, ConversationsActivity.class),
1888 s()
1889 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1890 : PendingIntent.FLAG_UPDATE_CURRENT);
1891 } catch (RuntimeException e) {
1892 return null;
1893 }
1894 }
1895
1896 void updateErrorNotification() {
1897 if (Config.SUPPRESS_ERROR_NOTIFICATION) {
1898 cancel(ERROR_NOTIFICATION_ID);
1899 return;
1900 }
1901 final boolean showAllErrors = QuickConversationsService.isConversations();
1902 final List<Account> errors = new ArrayList<>();
1903 boolean torNotAvailable = false;
1904 for (final Account account : mXmppConnectionService.getAccounts()) {
1905 if (account.hasErrorStatus()
1906 && account.showErrorNotification()
1907 && (showAllErrors
1908 || account.getLastErrorStatus() == Account.State.UNAUTHORIZED)) {
1909 errors.add(account);
1910 torNotAvailable |= account.getStatus() == Account.State.TOR_NOT_AVAILABLE;
1911 }
1912 }
1913 if (mXmppConnectionService.foregroundNotificationNeedsUpdatingWhenErrorStateChanges()) {
1914 notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
1915 }
1916 final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1917 if (errors.size() == 0) {
1918 cancel(ERROR_NOTIFICATION_ID);
1919 return;
1920 } else if (errors.size() == 1) {
1921 mBuilder.setContentTitle(
1922 mXmppConnectionService.getString(R.string.problem_connecting_to_account));
1923 mBuilder.setContentText(errors.get(0).getJid().asBareJid().toEscapedString());
1924 } else {
1925 mBuilder.setContentTitle(
1926 mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
1927 mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
1928 }
1929 mBuilder.addAction(
1930 R.drawable.ic_autorenew_white_24dp,
1931 mXmppConnectionService.getString(R.string.try_again),
1932 createTryAgainIntent());
1933 if (torNotAvailable) {
1934 if (TorServiceUtils.isOrbotInstalled(mXmppConnectionService)) {
1935 mBuilder.addAction(
1936 R.drawable.ic_play_circle_filled_white_48dp,
1937 mXmppConnectionService.getString(R.string.start_orbot),
1938 PendingIntent.getActivity(
1939 mXmppConnectionService,
1940 147,
1941 TorServiceUtils.LAUNCH_INTENT,
1942 s()
1943 ? PendingIntent.FLAG_IMMUTABLE
1944 | PendingIntent.FLAG_UPDATE_CURRENT
1945 : PendingIntent.FLAG_UPDATE_CURRENT));
1946 } else {
1947 mBuilder.addAction(
1948 R.drawable.ic_file_download_white_24dp,
1949 mXmppConnectionService.getString(R.string.install_orbot),
1950 PendingIntent.getActivity(
1951 mXmppConnectionService,
1952 146,
1953 TorServiceUtils.INSTALL_INTENT,
1954 s()
1955 ? PendingIntent.FLAG_IMMUTABLE
1956 | PendingIntent.FLAG_UPDATE_CURRENT
1957 : PendingIntent.FLAG_UPDATE_CURRENT));
1958 }
1959 }
1960 mBuilder.setDeleteIntent(createDismissErrorIntent());
1961 mBuilder.setVisibility(Notification.VISIBILITY_PRIVATE);
1962 mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
1963 mBuilder.setLocalOnly(true);
1964 mBuilder.setPriority(Notification.PRIORITY_LOW);
1965 final Intent intent;
1966 if (AccountUtils.MANAGE_ACCOUNT_ACTIVITY != null) {
1967 intent = new Intent(mXmppConnectionService, AccountUtils.MANAGE_ACCOUNT_ACTIVITY);
1968 } else {
1969 intent = new Intent(mXmppConnectionService, EditAccountActivity.class);
1970 intent.putExtra("jid", errors.get(0).getJid().asBareJid().toEscapedString());
1971 intent.putExtra(EditAccountActivity.EXTRA_OPENED_FROM_NOTIFICATION, true);
1972 }
1973 mBuilder.setContentIntent(
1974 PendingIntent.getActivity(
1975 mXmppConnectionService,
1976 145,
1977 intent,
1978 s()
1979 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1980 : PendingIntent.FLAG_UPDATE_CURRENT));
1981 if (Compatibility.runsTwentySix()) {
1982 mBuilder.setChannelId("error");
1983 }
1984 notify(ERROR_NOTIFICATION_ID, mBuilder.build());
1985 }
1986
1987 void updateFileAddingNotification(int current, Message message) {
1988 Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1989 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.transcoding_video));
1990 mBuilder.setProgress(100, current, false);
1991 mBuilder.setSmallIcon(R.drawable.ic_hourglass_empty_white_24dp);
1992 mBuilder.setContentIntent(createContentIntent(message.getConversation()));
1993 mBuilder.setOngoing(true);
1994 if (Compatibility.runsTwentySix()) {
1995 mBuilder.setChannelId("compression");
1996 }
1997 Notification notification = mBuilder.build();
1998 notify(FOREGROUND_NOTIFICATION_ID, notification);
1999 }
2000
2001 private void notify(String tag, int id, Notification notification) {
2002 final NotificationManagerCompat notificationManager =
2003 NotificationManagerCompat.from(mXmppConnectionService);
2004 try {
2005 notificationManager.notify(tag, id, notification);
2006 } catch (RuntimeException e) {
2007 Log.d(Config.LOGTAG, "unable to make notification", e);
2008 }
2009 }
2010
2011 public void notify(int id, Notification notification) {
2012 final NotificationManagerCompat notificationManager =
2013 NotificationManagerCompat.from(mXmppConnectionService);
2014 try {
2015 notificationManager.notify(id, notification);
2016 } catch (RuntimeException e) {
2017 Log.d(Config.LOGTAG, "unable to make notification", e);
2018 }
2019 }
2020
2021 public void cancel(int id) {
2022 final NotificationManagerCompat notificationManager =
2023 NotificationManagerCompat.from(mXmppConnectionService);
2024 try {
2025 notificationManager.cancel(id);
2026 } catch (RuntimeException e) {
2027 Log.d(Config.LOGTAG, "unable to cancel notification", e);
2028 }
2029 }
2030
2031 private void cancel(String tag, int id) {
2032 final NotificationManagerCompat notificationManager =
2033 NotificationManagerCompat.from(mXmppConnectionService);
2034 try {
2035 notificationManager.cancel(tag, id);
2036 } catch (RuntimeException e) {
2037 Log.d(Config.LOGTAG, "unable to cancel notification", e);
2038 }
2039 }
2040
2041 private static class MissedCallsInfo {
2042 private int numberOfCalls;
2043 private long lastTime;
2044
2045 MissedCallsInfo(final long time) {
2046 numberOfCalls = 1;
2047 lastTime = time;
2048 }
2049
2050 public void newMissedCall(final long time) {
2051 ++numberOfCalls;
2052 lastTime = time;
2053 }
2054
2055 public int getNumberOfCalls() {
2056 return numberOfCalls;
2057 }
2058
2059 public long getLastTime() {
2060 return lastTime;
2061 }
2062 }
2063
2064 private class VibrationRunnable implements Runnable {
2065
2066 @Override
2067 public void run() {
2068 final Vibrator vibrator =
2069 (Vibrator) mXmppConnectionService.getSystemService(Context.VIBRATOR_SERVICE);
2070 vibrator.vibrate(CALL_PATTERN, -1);
2071 }
2072 }
2073}