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