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