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.CallStyle;
40import androidx.core.app.NotificationCompat.Builder;
41import androidx.core.app.NotificationManagerCompat;
42import androidx.core.app.Person;
43import androidx.core.app.RemoteInput;
44import androidx.core.content.ContextCompat;
45import androidx.core.content.pm.ShortcutInfoCompat;
46import androidx.core.graphics.drawable.IconCompat;
47
48import com.google.common.base.Joiner;
49import com.google.common.base.Strings;
50import com.google.common.collect.Iterables;
51
52import java.io.File;
53import java.io.IOException;
54import java.util.ArrayList;
55import java.util.Calendar;
56import java.util.Collections;
57import java.util.HashMap;
58import java.util.Iterator;
59import java.util.LinkedHashMap;
60import java.util.List;
61import java.util.Map;
62import java.util.Set;
63import java.util.concurrent.Executors;
64import java.util.concurrent.ScheduledExecutorService;
65import java.util.concurrent.ScheduledFuture;
66import java.util.concurrent.TimeUnit;
67import java.util.concurrent.atomic.AtomicInteger;
68import java.util.regex.Matcher;
69import java.util.regex.Pattern;
70
71import eu.siacs.conversations.Config;
72import eu.siacs.conversations.R;
73import eu.siacs.conversations.entities.Account;
74import eu.siacs.conversations.entities.Contact;
75import eu.siacs.conversations.entities.Conversation;
76import eu.siacs.conversations.entities.Conversational;
77import eu.siacs.conversations.entities.Message;
78import eu.siacs.conversations.entities.MucOptions;
79import eu.siacs.conversations.persistance.FileBackend;
80import eu.siacs.conversations.ui.ConversationsActivity;
81import eu.siacs.conversations.ui.EditAccountActivity;
82import eu.siacs.conversations.ui.RtpSessionActivity;
83import eu.siacs.conversations.ui.TimePreference;
84import eu.siacs.conversations.utils.AccountUtils;
85import eu.siacs.conversations.utils.Compatibility;
86import eu.siacs.conversations.utils.GeoHelper;
87import eu.siacs.conversations.utils.TorServiceUtils;
88import eu.siacs.conversations.utils.UIHelper;
89import eu.siacs.conversations.xmpp.Jid;
90import eu.siacs.conversations.xmpp.XmppConnection;
91import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
92import eu.siacs.conversations.xmpp.jingle.Media;
93
94public class NotificationService {
95
96 private static final ScheduledExecutorService SCHEDULED_EXECUTOR_SERVICE =
97 Executors.newSingleThreadScheduledExecutor();
98
99 public static final Object CATCHUP_LOCK = new Object();
100
101 private static final int LED_COLOR = 0xff7401cf;
102
103 private static final long[] CALL_PATTERN = {0, 500, 300, 600};
104
105 private static final String MESSAGES_GROUP = "eu.siacs.conversations.messages";
106 private static final String MISSED_CALLS_GROUP = "eu.siacs.conversations.missed_calls";
107 private static final int NOTIFICATION_ID_MULTIPLIER = 1024 * 1024;
108 static final int FOREGROUND_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 4;
109 private static final int NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 2;
110 private static final int ERROR_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 6;
111 private static final int INCOMING_CALL_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 8;
112 public static final int ONGOING_CALL_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 10;
113 public static final int MISSED_CALL_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 12;
114 private static final int DELIVERY_FAILED_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 13;
115 private final XmppConnectionService mXmppConnectionService;
116 private final LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<>();
117 private final HashMap<Conversation, AtomicInteger> mBacklogMessageCounter = new HashMap<>();
118 private final LinkedHashMap<Conversational, MissedCallsInfo> mMissedCalls =
119 new LinkedHashMap<>();
120 private Conversation mOpenConversation;
121 private boolean mIsInForeground;
122 private long mLastNotification;
123
124 private static final String INCOMING_CALLS_NOTIFICATION_CHANNEL = "incoming_calls_channel";
125 private Ringtone currentlyPlayingRingtone = null;
126 private ScheduledFuture<?> vibrationFuture;
127
128 NotificationService(final XmppConnectionService service) {
129 this.mXmppConnectionService = service;
130 }
131
132 private static boolean displaySnoozeAction(List<Message> messages) {
133 int numberOfMessagesWithoutReply = 0;
134 for (Message message : messages) {
135 if (message.getStatus() == Message.STATUS_RECEIVED) {
136 ++numberOfMessagesWithoutReply;
137 } else {
138 return false;
139 }
140 }
141 return numberOfMessagesWithoutReply >= 3;
142 }
143
144 public static Pattern generateNickHighlightPattern(final String nick) {
145 return Pattern.compile("(?<=(^|\\s))" + Pattern.quote(nick) + "(?=\\s|$|\\p{Punct})");
146 }
147
148 private static boolean isImageMessage(Message message) {
149 return message.getType() != Message.TYPE_TEXT
150 && message.getTransferable() == null
151 && !message.isDeleted()
152 && message.getEncryption() != Message.ENCRYPTION_PGP
153 && message.getFileParams().height > 0;
154 }
155
156 @RequiresApi(api = Build.VERSION_CODES.O)
157 void initializeChannels() {
158 final Context c = mXmppConnectionService;
159 final NotificationManager notificationManager =
160 c.getSystemService(NotificationManager.class);
161 if (notificationManager == null) {
162 return;
163 }
164
165 notificationManager.deleteNotificationChannel("export");
166 notificationManager.deleteNotificationChannel("incoming_calls");
167
168 notificationManager.createNotificationChannelGroup(
169 new NotificationChannelGroup(
170 "status", c.getString(R.string.notification_group_status_information)));
171 notificationManager.createNotificationChannelGroup(
172 new NotificationChannelGroup(
173 "chats", c.getString(R.string.notification_group_messages)));
174 notificationManager.createNotificationChannelGroup(
175 new NotificationChannelGroup(
176 "calls", c.getString(R.string.notification_group_calls)));
177 final NotificationChannel foregroundServiceChannel =
178 new NotificationChannel(
179 "foreground",
180 c.getString(R.string.foreground_service_channel_name),
181 NotificationManager.IMPORTANCE_MIN);
182 foregroundServiceChannel.setDescription(
183 c.getString(
184 R.string.foreground_service_channel_description,
185 c.getString(R.string.app_name)));
186 foregroundServiceChannel.setShowBadge(false);
187 foregroundServiceChannel.setGroup("status");
188 notificationManager.createNotificationChannel(foregroundServiceChannel);
189 final NotificationChannel errorChannel =
190 new NotificationChannel(
191 "error",
192 c.getString(R.string.error_channel_name),
193 NotificationManager.IMPORTANCE_LOW);
194 errorChannel.setDescription(c.getString(R.string.error_channel_description));
195 errorChannel.setShowBadge(false);
196 errorChannel.setGroup("status");
197 notificationManager.createNotificationChannel(errorChannel);
198
199 final NotificationChannel videoCompressionChannel =
200 new NotificationChannel(
201 "compression",
202 c.getString(R.string.video_compression_channel_name),
203 NotificationManager.IMPORTANCE_LOW);
204 videoCompressionChannel.setShowBadge(false);
205 videoCompressionChannel.setGroup("status");
206 notificationManager.createNotificationChannel(videoCompressionChannel);
207
208 final NotificationChannel exportChannel =
209 new NotificationChannel(
210 "backup",
211 c.getString(R.string.backup_channel_name),
212 NotificationManager.IMPORTANCE_LOW);
213 exportChannel.setShowBadge(false);
214 exportChannel.setGroup("status");
215 notificationManager.createNotificationChannel(exportChannel);
216
217 final NotificationChannel incomingCallsChannel =
218 new NotificationChannel(
219 INCOMING_CALLS_NOTIFICATION_CHANNEL,
220 c.getString(R.string.incoming_calls_channel_name),
221 NotificationManager.IMPORTANCE_HIGH);
222 incomingCallsChannel.setSound(null, null);
223 incomingCallsChannel.setShowBadge(false);
224 incomingCallsChannel.setLightColor(LED_COLOR);
225 incomingCallsChannel.enableLights(true);
226 incomingCallsChannel.setGroup("calls");
227 incomingCallsChannel.setBypassDnd(true);
228 incomingCallsChannel.enableVibration(false);
229 notificationManager.createNotificationChannel(incomingCallsChannel);
230
231 final NotificationChannel ongoingCallsChannel =
232 new NotificationChannel(
233 "ongoing_calls",
234 c.getString(R.string.ongoing_calls_channel_name),
235 NotificationManager.IMPORTANCE_LOW);
236 ongoingCallsChannel.setShowBadge(false);
237 ongoingCallsChannel.setGroup("calls");
238 notificationManager.createNotificationChannel(ongoingCallsChannel);
239
240 final NotificationChannel missedCallsChannel =
241 new NotificationChannel(
242 "missed_calls",
243 c.getString(R.string.missed_calls_channel_name),
244 NotificationManager.IMPORTANCE_HIGH);
245 missedCallsChannel.setShowBadge(true);
246 missedCallsChannel.setSound(null, null);
247 missedCallsChannel.setLightColor(LED_COLOR);
248 missedCallsChannel.enableLights(true);
249 missedCallsChannel.setGroup("calls");
250 notificationManager.createNotificationChannel(missedCallsChannel);
251
252 final NotificationChannel messagesChannel =
253 new NotificationChannel(
254 "messages",
255 c.getString(R.string.messages_channel_name),
256 NotificationManager.IMPORTANCE_HIGH);
257 messagesChannel.setShowBadge(true);
258 messagesChannel.setSound(
259 RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION),
260 new AudioAttributes.Builder()
261 .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
262 .setUsage(AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT)
263 .build());
264 messagesChannel.setLightColor(LED_COLOR);
265 final int dat = 70;
266 final long[] pattern = {0, 3 * dat, dat, dat};
267 messagesChannel.setVibrationPattern(pattern);
268 messagesChannel.enableVibration(true);
269 messagesChannel.enableLights(true);
270 messagesChannel.setGroup("chats");
271 notificationManager.createNotificationChannel(messagesChannel);
272 final NotificationChannel silentMessagesChannel =
273 new NotificationChannel(
274 "silent_messages",
275 c.getString(R.string.silent_messages_channel_name),
276 NotificationManager.IMPORTANCE_LOW);
277 silentMessagesChannel.setDescription(
278 c.getString(R.string.silent_messages_channel_description));
279 silentMessagesChannel.setShowBadge(true);
280 silentMessagesChannel.setLightColor(LED_COLOR);
281 silentMessagesChannel.enableLights(true);
282 silentMessagesChannel.setGroup("chats");
283 notificationManager.createNotificationChannel(silentMessagesChannel);
284
285 final NotificationChannel quietHoursChannel =
286 new NotificationChannel(
287 "quiet_hours",
288 c.getString(R.string.title_pref_quiet_hours),
289 NotificationManager.IMPORTANCE_LOW);
290 quietHoursChannel.setShowBadge(true);
291 quietHoursChannel.setLightColor(LED_COLOR);
292 quietHoursChannel.enableLights(true);
293 quietHoursChannel.setGroup("chats");
294 quietHoursChannel.enableVibration(false);
295 quietHoursChannel.setSound(null, null);
296
297 notificationManager.createNotificationChannel(quietHoursChannel);
298
299 final NotificationChannel deliveryFailedChannel =
300 new NotificationChannel(
301 "delivery_failed",
302 c.getString(R.string.delivery_failed_channel_name),
303 NotificationManager.IMPORTANCE_DEFAULT);
304 deliveryFailedChannel.setShowBadge(false);
305 deliveryFailedChannel.setSound(
306 RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION),
307 new AudioAttributes.Builder()
308 .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
309 .setUsage(AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT)
310 .build());
311 deliveryFailedChannel.setGroup("chats");
312 notificationManager.createNotificationChannel(deliveryFailedChannel);
313 }
314
315 private boolean notifyMessage(final Message message) {
316 final Conversation conversation = (Conversation) message.getConversation();
317 return message.getStatus() == Message.STATUS_RECEIVED
318 && !conversation.isMuted()
319 && (conversation.alwaysNotify() || wasHighlightedOrPrivate(message))
320 && (!conversation.isWithStranger() || notificationsFromStrangers())
321 && message.getType() != Message.TYPE_RTP_SESSION;
322 }
323
324 private boolean notifyMissedCall(final Message message) {
325 return message.getType() == Message.TYPE_RTP_SESSION
326 && message.getStatus() == Message.STATUS_RECEIVED;
327 }
328
329 public boolean notificationsFromStrangers() {
330 return mXmppConnectionService.getBooleanPreference(
331 "notifications_from_strangers", R.bool.notifications_from_strangers);
332 }
333
334 private boolean isQuietHours() {
335 if (!mXmppConnectionService.getBooleanPreference(
336 "enable_quiet_hours", R.bool.enable_quiet_hours)) {
337 return false;
338 }
339 final SharedPreferences preferences =
340 PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
341 final long startTime =
342 TimePreference.minutesToTimestamp(
343 preferences.getLong("quiet_hours_start", TimePreference.DEFAULT_VALUE));
344 final long endTime =
345 TimePreference.minutesToTimestamp(
346 preferences.getLong("quiet_hours_end", TimePreference.DEFAULT_VALUE));
347 final long nowTime = Calendar.getInstance().getTimeInMillis();
348
349 if (endTime < startTime) {
350 return nowTime > startTime || nowTime < endTime;
351 } else {
352 return nowTime > startTime && nowTime < endTime;
353 }
354 }
355
356 public void pushFromBacklog(final Message message) {
357 if (notifyMessage(message)) {
358 synchronized (notifications) {
359 getBacklogMessageCounter((Conversation) message.getConversation())
360 .incrementAndGet();
361 pushToStack(message);
362 }
363 } else if (notifyMissedCall(message)) {
364 synchronized (mMissedCalls) {
365 pushMissedCall(message);
366 }
367 }
368 }
369
370 private AtomicInteger getBacklogMessageCounter(Conversation conversation) {
371 synchronized (mBacklogMessageCounter) {
372 if (!mBacklogMessageCounter.containsKey(conversation)) {
373 mBacklogMessageCounter.put(conversation, new AtomicInteger(0));
374 }
375 return mBacklogMessageCounter.get(conversation);
376 }
377 }
378
379 void pushFromDirectReply(final Message message) {
380 synchronized (notifications) {
381 pushToStack(message);
382 updateNotification(false);
383 }
384 }
385
386 public void finishBacklog(boolean notify, Account account) {
387 synchronized (notifications) {
388 mXmppConnectionService.updateUnreadCountBadge();
389 if (account == null || !notify) {
390 updateNotification(notify);
391 } else {
392 final int count;
393 final List<String> conversations;
394 synchronized (this.mBacklogMessageCounter) {
395 conversations = getBacklogConversations(account);
396 count = getBacklogMessageCount(account);
397 }
398 updateNotification(count > 0, conversations);
399 }
400 }
401 synchronized (mMissedCalls) {
402 updateMissedCallNotifications(mMissedCalls.keySet());
403 }
404 }
405
406 private List<String> getBacklogConversations(Account account) {
407 final List<String> conversations = new ArrayList<>();
408 for (Map.Entry<Conversation, AtomicInteger> entry : mBacklogMessageCounter.entrySet()) {
409 if (entry.getKey().getAccount() == account) {
410 conversations.add(entry.getKey().getUuid());
411 }
412 }
413 return conversations;
414 }
415
416 private int getBacklogMessageCount(Account account) {
417 int count = 0;
418 for (Iterator<Map.Entry<Conversation, AtomicInteger>> it =
419 mBacklogMessageCounter.entrySet().iterator();
420 it.hasNext(); ) {
421 Map.Entry<Conversation, AtomicInteger> entry = it.next();
422 if (entry.getKey().getAccount() == account) {
423 count += entry.getValue().get();
424 it.remove();
425 }
426 }
427 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": backlog message count=" + count);
428 return count;
429 }
430
431 void finishBacklog() {
432 finishBacklog(false, null);
433 }
434
435 private void pushToStack(final Message message) {
436 final String conversationUuid = message.getConversationUuid();
437 if (notifications.containsKey(conversationUuid)) {
438 notifications.get(conversationUuid).add(message);
439 } else {
440 final ArrayList<Message> mList = new ArrayList<>();
441 mList.add(message);
442 notifications.put(conversationUuid, mList);
443 }
444 }
445
446 public void push(final Message message) {
447 synchronized (CATCHUP_LOCK) {
448 final XmppConnection connection =
449 message.getConversation().getAccount().getXmppConnection();
450 if (connection != null && connection.isWaitingForSmCatchup()) {
451 connection.incrementSmCatchupMessageCounter();
452 pushFromBacklog(message);
453 } else {
454 pushNow(message);
455 }
456 }
457 }
458
459 public void pushFailedDelivery(final Message message) {
460 final Conversation conversation = (Conversation) message.getConversation();
461 final boolean isScreenLocked = !mXmppConnectionService.isScreenLocked();
462 if (this.mIsInForeground
463 && isScreenLocked
464 && this.mOpenConversation == message.getConversation()) {
465 Log.d(
466 Config.LOGTAG,
467 message.getConversation().getAccount().getJid().asBareJid()
468 + ": suppressing failed delivery notification because conversation is open");
469 return;
470 }
471 final PendingIntent pendingIntent = createContentIntent(conversation);
472 final int notificationId =
473 generateRequestCode(conversation, 0) + DELIVERY_FAILED_NOTIFICATION_ID;
474 final int failedDeliveries = conversation.countFailedDeliveries();
475 final Notification notification =
476 new Builder(mXmppConnectionService, "delivery_failed")
477 .setContentTitle(conversation.getName())
478 .setAutoCancel(true)
479 .setSmallIcon(R.drawable.ic_error_white_24dp)
480 .setContentText(
481 mXmppConnectionService
482 .getResources()
483 .getQuantityText(
484 R.plurals.some_messages_could_not_be_delivered,
485 failedDeliveries))
486 .setGroup("delivery_failed")
487 .setContentIntent(pendingIntent)
488 .build();
489 final Notification summaryNotification =
490 new Builder(mXmppConnectionService, "delivery_failed")
491 .setContentTitle(
492 mXmppConnectionService.getString(R.string.failed_deliveries))
493 .setContentText(
494 mXmppConnectionService
495 .getResources()
496 .getQuantityText(
497 R.plurals.some_messages_could_not_be_delivered,
498 1024))
499 .setSmallIcon(R.drawable.ic_error_white_24dp)
500 .setGroup("delivery_failed")
501 .setGroupSummary(true)
502 .setAutoCancel(true)
503 .build();
504 notify(notificationId, notification);
505 notify(DELIVERY_FAILED_NOTIFICATION_ID, summaryNotification);
506 }
507
508 private synchronized boolean tryRingingWithDialerUI(final AbstractJingleConnection.Id id, final Set<Media> media) {
509 if (Build.VERSION.SDK_INT < 23) return false;
510
511 if (!mXmppConnectionService.getPreferences().getBoolean("dialler_integration_incoming", true)) return false;
512
513 if (mXmppConnectionService.checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
514 // We cannot request audio permission in Dialer UI
515 // when Dialer is shown over keyguard, the user cannot even necessarily
516 // see notifications.
517 return false;
518 }
519
520 if (media.size() != 1 || !media.contains(Media.AUDIO)) {
521 // Currently our ConnectionService only handles single audio calls
522 Log.w(Config.LOGTAG, "only audio calls can be handled by cheogram connection service");
523 return false;
524 }
525
526 PhoneAccountHandle handle = null;
527 for (Contact contact : id.account.getRoster().getContacts()) {
528 if (!contact.getJid().getDomain().equals(id.with.getDomain())) {
529 continue;
530 }
531
532 if (!contact.getPresences().anyIdentity("gateway", "pstn")) {
533 continue;
534 }
535
536 handle = contact.phoneAccountHandle();
537 break;
538 }
539
540 if (handle == null) {
541 Log.w(Config.LOGTAG, "Could not find phone account handle for " + id.account.getJid().toString());
542 return false;
543 }
544
545 Bundle callInfo = new Bundle();
546 callInfo.putString("account", id.account.getJid().toString());
547 callInfo.putString("with", id.with.toString());
548 callInfo.putString("sessionId", id.sessionId);
549
550 TelecomManager telecomManager = mXmppConnectionService.getSystemService(TelecomManager.class);
551
552 try {
553 telecomManager.addNewIncomingCall(handle, callInfo);
554 } catch (SecurityException e) {
555 // If the account is not registered or enabled, it could result in a security exception
556 // Just fall back to the built-in UI in this case.
557 Log.w(Config.LOGTAG, e);
558 return false;
559 }
560
561 return true;
562 }
563
564 public synchronized void startRinging(final AbstractJingleConnection.Id id, final Set<Media> media) {
565 if (tryRingingWithDialerUI(id, media)) {
566 return;
567 }
568
569 showIncomingCallNotification(id, media);
570 final NotificationManager notificationManager =
571 (NotificationManager)
572 mXmppConnectionService.getSystemService(Context.NOTIFICATION_SERVICE);
573 final int currentInterruptionFilter;
574 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && notificationManager != null) {
575 currentInterruptionFilter = notificationManager.getCurrentInterruptionFilter();
576 } else {
577 currentInterruptionFilter = 1; // INTERRUPTION_FILTER_ALL
578 }
579 if (currentInterruptionFilter != 1) {
580 Log.d(
581 Config.LOGTAG,
582 "do not ring or vibrate because interruption filter has been set to "
583 + currentInterruptionFilter);
584 return;
585 }
586 final ScheduledFuture<?> currentVibrationFuture = this.vibrationFuture;
587 this.vibrationFuture =
588 SCHEDULED_EXECUTOR_SERVICE.scheduleAtFixedRate(
589 new VibrationRunnable(), 0, 3, TimeUnit.SECONDS);
590 if (currentVibrationFuture != null) {
591 currentVibrationFuture.cancel(true);
592 }
593 final SharedPreferences preferences =
594 PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
595 final Resources resources = mXmppConnectionService.getResources();
596 final String ringtonePreference =
597 preferences.getString(
598 "call_ringtone", resources.getString(R.string.incoming_call_ringtone));
599 if (Strings.isNullOrEmpty(ringtonePreference)) {
600 Log.d(Config.LOGTAG, "ringtone has been set to none");
601 return;
602 }
603 final Uri uri = Uri.parse(ringtonePreference);
604 this.currentlyPlayingRingtone = RingtoneManager.getRingtone(mXmppConnectionService, uri);
605 if (this.currentlyPlayingRingtone == null) {
606 Log.d(Config.LOGTAG, "unable to find ringtone for uri " + uri);
607 return;
608 }
609 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
610 this.currentlyPlayingRingtone.setLooping(true);
611 }
612 this.currentlyPlayingRingtone.play();
613 }
614
615 private void showIncomingCallNotification(
616 final AbstractJingleConnection.Id id, final Set<Media> media) {
617 final Intent fullScreenIntent =
618 new Intent(mXmppConnectionService, RtpSessionActivity.class);
619 fullScreenIntent.putExtra(
620 RtpSessionActivity.EXTRA_ACCOUNT,
621 id.account.getJid().asBareJid().toEscapedString());
622 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_WITH, id.with.toEscapedString());
623 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.sessionId);
624 fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
625 fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
626 final NotificationCompat.Builder builder =
627 new NotificationCompat.Builder(
628 mXmppConnectionService, INCOMING_CALLS_NOTIFICATION_CHANNEL);
629 final Contact contact = id.getContact();
630 builder.addPerson(getPerson(contact));
631 ShortcutInfoCompat info = mXmppConnectionService.getShortcutService().getShortcutInfoCompat(contact);
632 builder.setShortcutInfo(info);
633 if (Build.VERSION.SDK_INT >= 30) {
634 mXmppConnectionService.getSystemService(ShortcutManager.class).pushDynamicShortcut(info.toShortcutInfo());
635 }
636 if (mXmppConnectionService.getAccounts().size() > 1) {
637 builder.setSubText(contact.getAccount().getJid().asBareJid().toString());
638 }
639 NotificationCompat.CallStyle style = NotificationCompat.CallStyle.forIncomingCall(
640 getPerson(contact),
641 createCallAction(
642 id.sessionId,
643 XmppConnectionService.ACTION_DISMISS_CALL,
644 102),
645 createPendingRtpSession(id, RtpSessionActivity.ACTION_ACCEPT_CALL, 103)
646 );
647 if (media.contains(Media.VIDEO)) {
648 style.setIsVideo(true);
649 builder.setSmallIcon(R.drawable.ic_videocam_white_24dp);
650 builder.setContentTitle(
651 mXmppConnectionService.getString(R.string.rtp_state_incoming_video_call));
652 } else {
653 style.setIsVideo(false);
654 builder.setSmallIcon(R.drawable.ic_call_white_24dp);
655 builder.setContentTitle(
656 mXmppConnectionService.getString(R.string.rtp_state_incoming_call));
657 }
658 builder.setStyle(style);
659 builder.setLargeIcon(
660 mXmppConnectionService
661 .getAvatarService()
662 .get(contact, AvatarService.getSystemUiAvatarSize(mXmppConnectionService)));
663 final Uri systemAccount = contact.getSystemAccount();
664 if (systemAccount != null) {
665 builder.addPerson(systemAccount.toString());
666 }
667 builder.setContentText(id.account.getRoster().getContact(id.with).getDisplayName());
668 builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
669 builder.setPriority(NotificationCompat.PRIORITY_HIGH);
670 builder.setCategory(NotificationCompat.CATEGORY_CALL);
671 PendingIntent pendingIntent = createPendingRtpSession(id, Intent.ACTION_VIEW, 101);
672 builder.setFullScreenIntent(pendingIntent, true);
673 builder.setContentIntent(pendingIntent); // old androids need this?
674 builder.setOngoing(true);
675 modifyIncomingCall(builder);
676 final Notification notification = builder.build();
677 notification.flags = notification.flags | Notification.FLAG_INSISTENT;
678 notify(INCOMING_CALL_NOTIFICATION_ID, notification);
679 }
680
681 public Notification getOngoingCallNotification(
682 final XmppConnectionService.OngoingCall ongoingCall) {
683 final AbstractJingleConnection.Id id = ongoingCall.id;
684 final NotificationCompat.Builder builder =
685 new NotificationCompat.Builder(mXmppConnectionService, "ongoing_calls");
686 final Contact contact = id.account.getRoster().getContact(id.with);
687 NotificationCompat.CallStyle style = NotificationCompat.CallStyle.forOngoingCall(
688 getPerson(contact),
689 createCallAction(id.sessionId, XmppConnectionService.ACTION_END_CALL, 104)
690 );
691 if (ongoingCall.media.contains(Media.VIDEO)) {
692 style.setIsVideo(true);
693 builder.setSmallIcon(R.drawable.ic_videocam_white_24dp);
694 if (ongoingCall.reconnecting) {
695 builder.setContentTitle(
696 mXmppConnectionService.getString(R.string.reconnecting_video_call));
697 } else {
698 builder.setContentTitle(
699 mXmppConnectionService.getString(R.string.ongoing_video_call));
700 }
701 } else {
702 style.setIsVideo(false);
703 builder.setSmallIcon(R.drawable.ic_call_white_24dp);
704 if (ongoingCall.reconnecting) {
705 builder.setContentTitle(
706 mXmppConnectionService.getString(R.string.reconnecting_call));
707 } else {
708 builder.setContentTitle(mXmppConnectionService.getString(R.string.ongoing_call));
709 }
710 }
711 builder.setStyle(style);
712 builder.setContentText(contact.getDisplayName());
713 builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
714 builder.setPriority(NotificationCompat.PRIORITY_HIGH);
715 builder.setCategory(NotificationCompat.CATEGORY_CALL);
716 builder.setContentIntent(createPendingRtpSession(id, Intent.ACTION_VIEW, 101));
717 builder.setOngoing(true);
718 return builder.build();
719 }
720
721 private PendingIntent createPendingRtpSession(
722 final AbstractJingleConnection.Id id, final String action, final int requestCode) {
723 final Intent fullScreenIntent =
724 new Intent(mXmppConnectionService, RtpSessionActivity.class);
725 fullScreenIntent.setAction(action);
726 fullScreenIntent.putExtra(
727 RtpSessionActivity.EXTRA_ACCOUNT,
728 id.account.getJid().asBareJid().toEscapedString());
729 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_WITH, id.with.toEscapedString());
730 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.sessionId);
731 return PendingIntent.getActivity(
732 mXmppConnectionService,
733 requestCode,
734 fullScreenIntent,
735 s()
736 ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
737 : PendingIntent.FLAG_UPDATE_CURRENT);
738 }
739
740 public void cancelIncomingCallNotification() {
741 stopSoundAndVibration();
742 cancel(INCOMING_CALL_NOTIFICATION_ID);
743 }
744
745 public boolean stopSoundAndVibration() {
746 int stopped = 0;
747 if (this.currentlyPlayingRingtone != null) {
748 if (this.currentlyPlayingRingtone.isPlaying()) {
749 Log.d(Config.LOGTAG, "stop playing ring tone");
750 ++stopped;
751 }
752 this.currentlyPlayingRingtone.stop();
753 }
754 if (this.vibrationFuture != null && !this.vibrationFuture.isCancelled()) {
755 Log.d(Config.LOGTAG, "stop vibration");
756 this.vibrationFuture.cancel(true);
757 ++stopped;
758 }
759 return stopped > 0;
760 }
761
762 public static void cancelIncomingCallNotification(final Context context) {
763 final NotificationManagerCompat notificationManager =
764 NotificationManagerCompat.from(context);
765 try {
766 notificationManager.cancel(INCOMING_CALL_NOTIFICATION_ID);
767 } catch (RuntimeException e) {
768 Log.d(Config.LOGTAG, "unable to cancel incoming call notification after crash", e);
769 }
770 }
771
772 private void pushNow(final Message message) {
773 mXmppConnectionService.updateUnreadCountBadge();
774 if (!notifyMessage(message)) {
775 Log.d(
776 Config.LOGTAG,
777 message.getConversation().getAccount().getJid().asBareJid()
778 + ": suppressing notification because turned off");
779 return;
780 }
781 final boolean isScreenLocked = mXmppConnectionService.isScreenLocked();
782 if (this.mIsInForeground
783 && !isScreenLocked
784 && this.mOpenConversation == message.getConversation()) {
785 Log.d(
786 Config.LOGTAG,
787 message.getConversation().getAccount().getJid().asBareJid()
788 + ": suppressing notification because conversation is open");
789 return;
790 }
791 synchronized (notifications) {
792 pushToStack(message);
793 final Conversational conversation = message.getConversation();
794 final Account account = conversation.getAccount();
795 final boolean doNotify =
796 (!(this.mIsInForeground && this.mOpenConversation == null) || isScreenLocked)
797 && !account.inGracePeriod()
798 && !this.inMiniGracePeriod(account);
799 updateNotification(doNotify, Collections.singletonList(conversation.getUuid()));
800 }
801 }
802
803 private void pushMissedCall(final Message message) {
804 final Conversational conversation = message.getConversation();
805 final MissedCallsInfo info = mMissedCalls.get(conversation);
806 if (info == null) {
807 mMissedCalls.put(conversation, new MissedCallsInfo(message.getTimeSent()));
808 } else {
809 info.newMissedCall(message.getTimeSent());
810 }
811 }
812
813 public void pushMissedCallNow(final Message message) {
814 synchronized (mMissedCalls) {
815 pushMissedCall(message);
816 updateMissedCallNotifications(Collections.singleton(message.getConversation()));
817 }
818 }
819
820 public void clear(final Conversation conversation) {
821 clearMessages(conversation);
822 clearMissedCalls(conversation);
823 }
824
825 public void clearMessages() {
826 synchronized (notifications) {
827 for (ArrayList<Message> messages : notifications.values()) {
828 markAsReadIfHasDirectReply(messages);
829 }
830 notifications.clear();
831 updateNotification(false);
832 }
833 }
834
835 public void clearMessages(final Conversation conversation) {
836 synchronized (this.mBacklogMessageCounter) {
837 this.mBacklogMessageCounter.remove(conversation);
838 }
839 synchronized (notifications) {
840 markAsReadIfHasDirectReply(conversation);
841 if (notifications.remove(conversation.getUuid()) != null) {
842 cancel(conversation.getUuid(), NOTIFICATION_ID);
843 updateNotification(false, null, true);
844 }
845 }
846 }
847
848 public void clearMissedCalls() {
849 synchronized (mMissedCalls) {
850 for (final Conversational conversation : mMissedCalls.keySet()) {
851 cancel(conversation.getUuid(), MISSED_CALL_NOTIFICATION_ID);
852 }
853 mMissedCalls.clear();
854 updateMissedCallNotifications(null);
855 }
856 }
857
858 public void clearMissedCalls(final Conversation conversation) {
859 synchronized (mMissedCalls) {
860 if (mMissedCalls.remove(conversation) != null) {
861 cancel(conversation.getUuid(), MISSED_CALL_NOTIFICATION_ID);
862 updateMissedCallNotifications(null);
863 }
864 }
865 }
866
867 private void markAsReadIfHasDirectReply(final Conversation conversation) {
868 markAsReadIfHasDirectReply(notifications.get(conversation.getUuid()));
869 }
870
871 private void markAsReadIfHasDirectReply(final ArrayList<Message> messages) {
872 if (messages != null && messages.size() > 0) {
873 Message last = messages.get(messages.size() - 1);
874 if (last.getStatus() != Message.STATUS_RECEIVED) {
875 if (mXmppConnectionService.markRead((Conversation) last.getConversation(), false)) {
876 mXmppConnectionService.updateConversationUi();
877 }
878 }
879 }
880 }
881
882 private void setNotificationColor(final Builder mBuilder) {
883 TypedValue typedValue = new TypedValue();
884 mXmppConnectionService.getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
885 mBuilder.setColor(typedValue.data);
886 }
887
888 public void updateNotification() {
889 synchronized (notifications) {
890 updateNotification(false);
891 }
892 }
893
894 private void updateNotification(final boolean notify) {
895 updateNotification(notify, null, false);
896 }
897
898 private void updateNotification(final boolean notify, final List<String> conversations) {
899 updateNotification(notify, conversations, false);
900 }
901
902 private void updateNotification(
903 final boolean notify, final List<String> conversations, final boolean summaryOnly) {
904 final SharedPreferences preferences =
905 PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
906
907 final boolean quiteHours = isQuietHours();
908
909 final boolean notifyOnlyOneChild =
910 notify
911 && conversations != null
912 && conversations.size()
913 == 1; // if this check is changed to > 0 catchup messages will
914 // create one notification per conversation
915
916 if (notifications.size() == 0) {
917 cancel(NOTIFICATION_ID);
918 } else {
919 if (notify) {
920 this.markLastNotification();
921 }
922 final Builder mBuilder;
923 if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
924 mBuilder =
925 buildSingleConversations(
926 notifications.values().iterator().next(), notify, quiteHours);
927 modifyForSoundVibrationAndLight(mBuilder, notify, quiteHours, preferences);
928 notify(NOTIFICATION_ID, mBuilder.build());
929 } else {
930 mBuilder = buildMultipleConversation(notify, quiteHours);
931 if (notifyOnlyOneChild) {
932 mBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
933 }
934 modifyForSoundVibrationAndLight(mBuilder, notify, quiteHours, preferences);
935 if (!summaryOnly) {
936 for (Map.Entry<String, ArrayList<Message>> entry : notifications.entrySet()) {
937 String uuid = entry.getKey();
938 final boolean notifyThis =
939 notifyOnlyOneChild ? conversations.contains(uuid) : notify;
940 Builder singleBuilder =
941 buildSingleConversations(entry.getValue(), notifyThis, quiteHours);
942 if (!notifyOnlyOneChild) {
943 singleBuilder.setGroupAlertBehavior(
944 NotificationCompat.GROUP_ALERT_SUMMARY);
945 }
946 modifyForSoundVibrationAndLight(
947 singleBuilder, notifyThis, quiteHours, preferences);
948 singleBuilder.setGroup(MESSAGES_GROUP);
949 setNotificationColor(singleBuilder);
950 notify(entry.getKey(), NOTIFICATION_ID, singleBuilder.build());
951 }
952 }
953 notify(NOTIFICATION_ID, mBuilder.build());
954 }
955 }
956 }
957
958 private void updateMissedCallNotifications(final Set<Conversational> update) {
959 if (mMissedCalls.isEmpty()) {
960 cancel(MISSED_CALL_NOTIFICATION_ID);
961 return;
962 }
963 if (mMissedCalls.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
964 final Conversational conversation = mMissedCalls.keySet().iterator().next();
965 final MissedCallsInfo info = mMissedCalls.values().iterator().next();
966 final Notification notification = missedCall(conversation, info);
967 notify(MISSED_CALL_NOTIFICATION_ID, notification);
968 } else {
969 final Notification summary = missedCallsSummary();
970 notify(MISSED_CALL_NOTIFICATION_ID, summary);
971 if (update != null) {
972 for (final Conversational conversation : update) {
973 final MissedCallsInfo info = mMissedCalls.get(conversation);
974 if (info != null) {
975 final Notification notification = missedCall(conversation, info);
976 notify(conversation.getUuid(), MISSED_CALL_NOTIFICATION_ID, notification);
977 }
978 }
979 }
980 }
981 }
982
983 private void modifyForSoundVibrationAndLight(
984 Builder mBuilder, boolean notify, boolean quietHours, SharedPreferences preferences) {
985 final Resources resources = mXmppConnectionService.getResources();
986 final String ringtone =
987 preferences.getString(
988 "notification_ringtone",
989 resources.getString(R.string.notification_ringtone));
990 final boolean vibrate =
991 preferences.getBoolean(
992 "vibrate_on_notification",
993 resources.getBoolean(R.bool.vibrate_on_notification));
994 final boolean led = preferences.getBoolean("led", resources.getBoolean(R.bool.led));
995 final boolean headsup =
996 preferences.getBoolean(
997 "notification_headsup", resources.getBoolean(R.bool.headsup_notifications));
998 if (notify && !quietHours) {
999 if (vibrate) {
1000 final int dat = 70;
1001 final long[] pattern = {0, 3 * dat, dat, dat};
1002 mBuilder.setVibrate(pattern);
1003 } else {
1004 mBuilder.setVibrate(new long[] {0});
1005 }
1006 Uri uri = Uri.parse(ringtone);
1007 try {
1008 mBuilder.setSound(fixRingtoneUri(uri));
1009 } catch (SecurityException e) {
1010 Log.d(Config.LOGTAG, "unable to use custom notification sound " + uri.toString());
1011 }
1012 } else {
1013 mBuilder.setLocalOnly(true);
1014 }
1015 mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
1016 mBuilder.setPriority(
1017 notify
1018 ? (headsup
1019 ? NotificationCompat.PRIORITY_HIGH
1020 : NotificationCompat.PRIORITY_DEFAULT)
1021 : NotificationCompat.PRIORITY_LOW);
1022 setNotificationColor(mBuilder);
1023 mBuilder.setDefaults(0);
1024 if (led) {
1025 mBuilder.setLights(LED_COLOR, 2000, 3000);
1026 }
1027 }
1028
1029 private void modifyIncomingCall(final Builder mBuilder) {
1030 mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
1031 setNotificationColor(mBuilder);
1032 mBuilder.setLights(LED_COLOR, 2000, 3000);
1033 }
1034
1035 private Uri fixRingtoneUri(Uri uri) {
1036 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && "file".equals(uri.getScheme())) {
1037 return FileBackend.getUriForFile(mXmppConnectionService, new File(uri.getPath()));
1038 } else {
1039 return uri;
1040 }
1041 }
1042
1043 private Notification missedCallsSummary() {
1044 final Builder publicBuilder = buildMissedCallsSummary(true);
1045 final Builder builder = buildMissedCallsSummary(false);
1046 builder.setPublicVersion(publicBuilder.build());
1047 return builder.build();
1048 }
1049
1050 private Builder buildMissedCallsSummary(boolean publicVersion) {
1051 final Builder builder =
1052 new NotificationCompat.Builder(mXmppConnectionService, "missed_calls");
1053 int totalCalls = 0;
1054 final List<String> names = new ArrayList<>();
1055 long lastTime = 0;
1056 for (final Map.Entry<Conversational, MissedCallsInfo> entry : mMissedCalls.entrySet()) {
1057 final Conversational conversation = entry.getKey();
1058 final MissedCallsInfo missedCallsInfo = entry.getValue();
1059 names.add(conversation.getContact().getDisplayName());
1060 totalCalls += missedCallsInfo.getNumberOfCalls();
1061 lastTime = Math.max(lastTime, missedCallsInfo.getLastTime());
1062 }
1063 final String title =
1064 (totalCalls == 1)
1065 ? mXmppConnectionService.getString(R.string.missed_call)
1066 : (mMissedCalls.size() == 1)
1067 ? mXmppConnectionService
1068 .getResources()
1069 .getQuantityString(
1070 R.plurals.n_missed_calls, totalCalls, totalCalls)
1071 : mXmppConnectionService
1072 .getResources()
1073 .getQuantityString(
1074 R.plurals.n_missed_calls_from_m_contacts,
1075 mMissedCalls.size(),
1076 totalCalls,
1077 mMissedCalls.size());
1078 builder.setContentTitle(title);
1079 builder.setTicker(title);
1080 if (!publicVersion) {
1081 builder.setContentText(Joiner.on(", ").join(names));
1082 }
1083 builder.setSmallIcon(R.drawable.ic_call_missed_white_24db);
1084 builder.setGroupSummary(true);
1085 builder.setGroup(MISSED_CALLS_GROUP);
1086 builder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
1087 builder.setCategory(NotificationCompat.CATEGORY_CALL);
1088 builder.setWhen(lastTime);
1089 if (!mMissedCalls.isEmpty()) {
1090 final Conversational firstConversation = mMissedCalls.keySet().iterator().next();
1091 builder.setContentIntent(createContentIntent(firstConversation));
1092 }
1093 builder.setDeleteIntent(createMissedCallsDeleteIntent(null));
1094 modifyMissedCall(builder);
1095 return builder;
1096 }
1097
1098 private Notification missedCall(final Conversational conversation, final MissedCallsInfo info) {
1099 final Builder publicBuilder = buildMissedCall(conversation, info, true);
1100 final Builder builder = buildMissedCall(conversation, info, false);
1101 builder.setPublicVersion(publicBuilder.build());
1102 return builder.build();
1103 }
1104
1105 private Builder buildMissedCall(
1106 final Conversational conversation, final MissedCallsInfo info, boolean publicVersion) {
1107 final Builder builder =
1108 new NotificationCompat.Builder(mXmppConnectionService, "missed_calls");
1109 final String title =
1110 (info.getNumberOfCalls() == 1)
1111 ? mXmppConnectionService.getString(R.string.missed_call)
1112 : mXmppConnectionService
1113 .getResources()
1114 .getQuantityString(
1115 R.plurals.n_missed_calls,
1116 info.getNumberOfCalls(),
1117 info.getNumberOfCalls());
1118 builder.setContentTitle(title);
1119 if (mXmppConnectionService.getAccounts().size() > 1) {
1120 builder.setSubText(conversation.getAccount().getJid().asBareJid().toString());
1121 }
1122 final String name = conversation.getContact().getDisplayName();
1123 if (publicVersion) {
1124 builder.setTicker(title);
1125 } else {
1126 builder.setTicker(
1127 mXmppConnectionService
1128 .getResources()
1129 .getQuantityString(
1130 R.plurals.n_missed_calls_from_x,
1131 info.getNumberOfCalls(),
1132 info.getNumberOfCalls(),
1133 name));
1134 builder.setContentText(name);
1135 }
1136 builder.setSmallIcon(R.drawable.ic_call_missed_white_24db);
1137 builder.setGroup(MISSED_CALLS_GROUP);
1138 builder.setCategory(NotificationCompat.CATEGORY_CALL);
1139 builder.setWhen(info.getLastTime());
1140 builder.setContentIntent(createContentIntent(conversation));
1141 builder.setDeleteIntent(createMissedCallsDeleteIntent(conversation));
1142 if (!publicVersion && conversation instanceof Conversation) {
1143 builder.setLargeIcon(
1144 mXmppConnectionService
1145 .getAvatarService()
1146 .get(
1147 (Conversation) conversation,
1148 AvatarService.getSystemUiAvatarSize(mXmppConnectionService)));
1149 }
1150 modifyMissedCall(builder);
1151 return builder;
1152 }
1153
1154 private void modifyMissedCall(final Builder builder) {
1155 final SharedPreferences preferences =
1156 PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
1157 final Resources resources = mXmppConnectionService.getResources();
1158 final boolean led = preferences.getBoolean("led", resources.getBoolean(R.bool.led));
1159 if (led) {
1160 builder.setLights(LED_COLOR, 2000, 3000);
1161 }
1162 builder.setPriority(NotificationCompat.PRIORITY_HIGH);
1163 builder.setSound(null);
1164 setNotificationColor(builder);
1165 }
1166
1167 private Builder buildMultipleConversation(final boolean notify, final boolean quietHours) {
1168 final Builder mBuilder =
1169 new NotificationCompat.Builder(
1170 mXmppConnectionService,
1171 quietHours ? "quiet_hours" : (notify ? "messages" : "silent_messages"));
1172 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
1173 style.setBigContentTitle(
1174 mXmppConnectionService
1175 .getResources()
1176 .getQuantityString(
1177 R.plurals.x_unread_conversations,
1178 notifications.size(),
1179 notifications.size()));
1180 final List<String> names = new ArrayList<>();
1181 Conversation conversation = null;
1182 for (final ArrayList<Message> messages : notifications.values()) {
1183 if (messages.isEmpty()) {
1184 continue;
1185 }
1186 conversation = (Conversation) messages.get(0).getConversation();
1187 final String name = conversation.getName().toString();
1188 SpannableString styledString;
1189 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
1190 int count = messages.size();
1191 styledString =
1192 new SpannableString(
1193 name
1194 + ": "
1195 + mXmppConnectionService
1196 .getResources()
1197 .getQuantityString(
1198 R.plurals.x_messages, count, count));
1199 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
1200 style.addLine(styledString);
1201 } else {
1202 styledString =
1203 new SpannableString(
1204 name
1205 + ": "
1206 + UIHelper.getMessagePreview(
1207 mXmppConnectionService, messages.get(0))
1208 .first);
1209 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
1210 style.addLine(styledString);
1211 }
1212 names.add(name);
1213 }
1214 final String contentTitle =
1215 mXmppConnectionService
1216 .getResources()
1217 .getQuantityString(
1218 R.plurals.x_unread_conversations,
1219 notifications.size(),
1220 notifications.size());
1221 mBuilder.setContentTitle(contentTitle);
1222 mBuilder.setTicker(contentTitle);
1223 mBuilder.setContentText(Joiner.on(", ").join(names));
1224 mBuilder.setStyle(style);
1225 if (conversation != null) {
1226 mBuilder.setContentIntent(createContentIntent(conversation));
1227 }
1228 mBuilder.setGroupSummary(true);
1229 mBuilder.setGroup(MESSAGES_GROUP);
1230 mBuilder.setDeleteIntent(createDeleteIntent(null));
1231 mBuilder.setSmallIcon(R.drawable.ic_notification);
1232 return mBuilder;
1233 }
1234
1235 private Builder buildSingleConversations(
1236 final ArrayList<Message> messages, final boolean notify, final boolean quietHours) {
1237 final Builder mBuilder =
1238 new NotificationCompat.Builder(
1239 mXmppConnectionService,
1240 quietHours ? "quiet_hours" : (notify ? "messages" : "silent_messages"));
1241 if (messages.size() >= 1) {
1242 final Conversation conversation = (Conversation) messages.get(0).getConversation();
1243 mBuilder.setLargeIcon(
1244 mXmppConnectionService
1245 .getAvatarService()
1246 .get(
1247 conversation,
1248 AvatarService.getSystemUiAvatarSize(mXmppConnectionService)));
1249 mBuilder.setContentTitle(conversation.getName());
1250 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
1251 int count = messages.size();
1252 mBuilder.setContentText(
1253 mXmppConnectionService
1254 .getResources()
1255 .getQuantityString(R.plurals.x_messages, count, count));
1256 } else {
1257 Message message;
1258 // TODO starting with Android 9 we might want to put images in MessageStyle
1259 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P
1260 && (message = getImage(messages)) != null) {
1261 modifyForImage(mBuilder, message, messages);
1262 } else {
1263 modifyForTextOnly(mBuilder, messages);
1264 }
1265 RemoteInput remoteInput =
1266 new RemoteInput.Builder("text_reply")
1267 .setLabel(
1268 UIHelper.getMessageHint(
1269 mXmppConnectionService, conversation))
1270 .build();
1271 PendingIntent markAsReadPendingIntent = createReadPendingIntent(conversation);
1272 NotificationCompat.Action markReadAction =
1273 new NotificationCompat.Action.Builder(
1274 R.drawable.ic_drafts_white_24dp,
1275 mXmppConnectionService.getString(R.string.mark_as_read),
1276 markAsReadPendingIntent)
1277 .setSemanticAction(
1278 NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ)
1279 .setShowsUserInterface(false)
1280 .build();
1281 final String replyLabel = mXmppConnectionService.getString(R.string.reply);
1282 final String lastMessageUuid = Iterables.getLast(messages).getUuid();
1283 final NotificationCompat.Action replyAction =
1284 new NotificationCompat.Action.Builder(
1285 R.drawable.ic_send_text_offline,
1286 replyLabel,
1287 createReplyIntent(conversation, lastMessageUuid, false))
1288 .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY)
1289 .setShowsUserInterface(false)
1290 .addRemoteInput(remoteInput)
1291 .build();
1292 final NotificationCompat.Action wearReplyAction =
1293 new NotificationCompat.Action.Builder(
1294 R.drawable.ic_wear_reply,
1295 replyLabel,
1296 createReplyIntent(conversation, lastMessageUuid, true))
1297 .addRemoteInput(remoteInput)
1298 .build();
1299 mBuilder.extend(
1300 new NotificationCompat.WearableExtender().addAction(wearReplyAction));
1301 int addedActionsCount = 1;
1302 mBuilder.addAction(markReadAction);
1303 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1304 mBuilder.addAction(replyAction);
1305 ++addedActionsCount;
1306 }
1307
1308 if (displaySnoozeAction(messages)) {
1309 String label = mXmppConnectionService.getString(R.string.snooze);
1310 PendingIntent pendingSnoozeIntent = createSnoozeIntent(conversation);
1311 NotificationCompat.Action snoozeAction =
1312 new NotificationCompat.Action.Builder(
1313 R.drawable.ic_notifications_paused_white_24dp,
1314 label,
1315 pendingSnoozeIntent)
1316 .build();
1317 mBuilder.addAction(snoozeAction);
1318 ++addedActionsCount;
1319 }
1320 if (addedActionsCount < 3) {
1321 final Message firstLocationMessage = getFirstLocationMessage(messages);
1322 if (firstLocationMessage != null) {
1323 final PendingIntent pendingShowLocationIntent =
1324 createShowLocationIntent(firstLocationMessage);
1325 if (pendingShowLocationIntent != null) {
1326 final String label =
1327 mXmppConnectionService
1328 .getResources()
1329 .getString(R.string.show_location);
1330 NotificationCompat.Action locationAction =
1331 new NotificationCompat.Action.Builder(
1332 R.drawable.ic_room_white_24dp,
1333 label,
1334 pendingShowLocationIntent)
1335 .build();
1336 mBuilder.addAction(locationAction);
1337 ++addedActionsCount;
1338 }
1339 }
1340 }
1341 if (addedActionsCount < 3) {
1342 Message firstDownloadableMessage = getFirstDownloadableMessage(messages);
1343 if (firstDownloadableMessage != null) {
1344 String label =
1345 mXmppConnectionService
1346 .getResources()
1347 .getString(
1348 R.string.download_x_file,
1349 UIHelper.getFileDescriptionString(
1350 mXmppConnectionService,
1351 firstDownloadableMessage));
1352 PendingIntent pendingDownloadIntent =
1353 createDownloadIntent(firstDownloadableMessage);
1354 NotificationCompat.Action downloadAction =
1355 new NotificationCompat.Action.Builder(
1356 R.drawable.ic_file_download_white_24dp,
1357 label,
1358 pendingDownloadIntent)
1359 .build();
1360 mBuilder.addAction(downloadAction);
1361 ++addedActionsCount;
1362 }
1363 }
1364 }
1365 if (conversation.getMode() == Conversation.MODE_SINGLE) {
1366 Contact contact = conversation.getContact();
1367 Uri systemAccount = contact.getSystemAccount();
1368 if (systemAccount != null) {
1369 mBuilder.addPerson(systemAccount.toString());
1370 }
1371 }
1372 mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
1373 mBuilder.setSmallIcon(R.drawable.ic_notification);
1374 mBuilder.setDeleteIntent(createDeleteIntent(conversation));
1375 mBuilder.setContentIntent(createContentIntent(conversation));
1376 if (mXmppConnectionService.getAccounts().size() > 1) {
1377 mBuilder.setSubText(conversation.getAccount().getJid().asBareJid().toString());
1378 }
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}