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