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