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