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