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 static void cancelIncomingCallNotification(final Context context) {
430 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
431 try {
432 notificationManager.cancel(INCOMING_CALL_NOTIFICATION_ID);
433 } catch (RuntimeException e) {
434 Log.d(Config.LOGTAG, "unable to cancel incoming call notification after crash", e);
435 }
436 }
437
438 private void pushNow(final Message message) {
439 mXmppConnectionService.updateUnreadCountBadge();
440 if (!notify(message)) {
441 Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because turned off");
442 return;
443 }
444 final boolean isScreenOn = mXmppConnectionService.isInteractive();
445 if (this.mIsInForeground && isScreenOn && this.mOpenConversation == message.getConversation()) {
446 Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because conversation is open");
447 return;
448 }
449 synchronized (notifications) {
450 pushToStack(message);
451 final Conversational conversation = message.getConversation();
452 final Account account = conversation.getAccount();
453 final boolean doNotify = (!(this.mIsInForeground && this.mOpenConversation == null) || !isScreenOn)
454 && !account.inGracePeriod()
455 && !this.inMiniGracePeriod(account);
456 updateNotification(doNotify, Collections.singletonList(conversation.getUuid()));
457 }
458 }
459
460 public void clear() {
461 synchronized (notifications) {
462 for (ArrayList<Message> messages : notifications.values()) {
463 markAsReadIfHasDirectReply(messages);
464 }
465 notifications.clear();
466 updateNotification(false);
467 }
468 }
469
470 public void clear(final Conversation conversation) {
471 synchronized (this.mBacklogMessageCounter) {
472 this.mBacklogMessageCounter.remove(conversation);
473 }
474 synchronized (notifications) {
475 markAsReadIfHasDirectReply(conversation);
476 if (notifications.remove(conversation.getUuid()) != null) {
477 cancel(conversation.getUuid(), NOTIFICATION_ID);
478 updateNotification(false, null, true);
479 }
480 }
481 }
482
483 private void markAsReadIfHasDirectReply(final Conversation conversation) {
484 markAsReadIfHasDirectReply(notifications.get(conversation.getUuid()));
485 }
486
487 private void markAsReadIfHasDirectReply(final ArrayList<Message> messages) {
488 if (messages != null && messages.size() > 0) {
489 Message last = messages.get(messages.size() - 1);
490 if (last.getStatus() != Message.STATUS_RECEIVED) {
491 if (mXmppConnectionService.markRead((Conversation) last.getConversation(), false)) {
492 mXmppConnectionService.updateConversationUi();
493 }
494 }
495 }
496 }
497
498 private void setNotificationColor(final Builder mBuilder) {
499 mBuilder.setColor(ContextCompat.getColor(mXmppConnectionService, R.color.green600));
500 }
501
502 public void updateNotification() {
503 synchronized (notifications) {
504 updateNotification(false);
505 }
506 }
507
508 private void updateNotification(final boolean notify) {
509 updateNotification(notify, null, false);
510 }
511
512 private void updateNotification(final boolean notify, final List<String> conversations) {
513 updateNotification(notify, conversations, false);
514 }
515
516 private void updateNotification(final boolean notify, final List<String> conversations, final boolean summaryOnly) {
517 final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
518
519 final boolean quiteHours = isQuietHours();
520
521 final boolean notifyOnlyOneChild = notify && conversations != null && conversations.size() == 1; //if this check is changed to > 0 catchup messages will create one notification per conversation
522
523
524 if (notifications.size() == 0) {
525 cancel(NOTIFICATION_ID);
526 } else {
527 if (notify) {
528 this.markLastNotification();
529 }
530 final Builder mBuilder;
531 if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
532 mBuilder = buildSingleConversations(notifications.values().iterator().next(), notify, quiteHours);
533 modifyForSoundVibrationAndLight(mBuilder, notify, quiteHours, preferences);
534 notify(NOTIFICATION_ID, mBuilder.build());
535 } else {
536 mBuilder = buildMultipleConversation(notify, quiteHours);
537 if (notifyOnlyOneChild) {
538 mBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
539 }
540 modifyForSoundVibrationAndLight(mBuilder, notify, quiteHours, preferences);
541 if (!summaryOnly) {
542 for (Map.Entry<String, ArrayList<Message>> entry : notifications.entrySet()) {
543 String uuid = entry.getKey();
544 final boolean notifyThis = notifyOnlyOneChild ? conversations.contains(uuid) : notify;
545 Builder singleBuilder = buildSingleConversations(entry.getValue(), notifyThis, quiteHours);
546 if (!notifyOnlyOneChild) {
547 singleBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY);
548 }
549 modifyForSoundVibrationAndLight(singleBuilder, notifyThis, quiteHours, preferences);
550 singleBuilder.setGroup(CONVERSATIONS_GROUP);
551 setNotificationColor(singleBuilder);
552 notify(entry.getKey(), NOTIFICATION_ID, singleBuilder.build());
553 }
554 }
555 notify(NOTIFICATION_ID, mBuilder.build());
556 }
557 }
558 }
559
560 private void modifyForSoundVibrationAndLight(Builder mBuilder, boolean notify, boolean quietHours, SharedPreferences preferences) {
561 final Resources resources = mXmppConnectionService.getResources();
562 final String ringtone = preferences.getString("notification_ringtone", resources.getString(R.string.notification_ringtone));
563 final boolean vibrate = preferences.getBoolean("vibrate_on_notification", resources.getBoolean(R.bool.vibrate_on_notification));
564 final boolean led = preferences.getBoolean("led", resources.getBoolean(R.bool.led));
565 final boolean headsup = preferences.getBoolean("notification_headsup", resources.getBoolean(R.bool.headsup_notifications));
566 if (notify && !quietHours) {
567 if (vibrate) {
568 final int dat = 70;
569 final long[] pattern = {0, 3 * dat, dat, dat};
570 mBuilder.setVibrate(pattern);
571 } else {
572 mBuilder.setVibrate(new long[]{0});
573 }
574 Uri uri = Uri.parse(ringtone);
575 try {
576 mBuilder.setSound(fixRingtoneUri(uri));
577 } catch (SecurityException e) {
578 Log.d(Config.LOGTAG, "unable to use custom notification sound " + uri.toString());
579 }
580 } else {
581 mBuilder.setLocalOnly(true);
582 }
583 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
584 mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
585 }
586 mBuilder.setPriority(notify ? (headsup ? NotificationCompat.PRIORITY_HIGH : NotificationCompat.PRIORITY_DEFAULT) : NotificationCompat.PRIORITY_LOW);
587 setNotificationColor(mBuilder);
588 mBuilder.setDefaults(0);
589 if (led) {
590 mBuilder.setLights(LED_COLOR, 2000, 3000);
591 }
592 }
593
594 private void modifyIncomingCall(Builder mBuilder) {
595 final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
596 final Resources resources = mXmppConnectionService.getResources();
597 final String ringtone = preferences.getString("call_ringtone", resources.getString(R.string.incoming_call_ringtone));
598 mBuilder.setVibrate(CALL_PATTERN);
599 final Uri uri = Uri.parse(ringtone);
600 try {
601 mBuilder.setSound(fixRingtoneUri(uri));
602 } catch (SecurityException e) {
603 Log.d(Config.LOGTAG, "unable to use custom notification sound " + uri.toString());
604 }
605 mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
606 setNotificationColor(mBuilder);
607 mBuilder.setLights(LED_COLOR, 2000, 3000);
608 }
609
610 private Uri fixRingtoneUri(Uri uri) {
611 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && "file".equals(uri.getScheme())) {
612 return FileBackend.getUriForFile(mXmppConnectionService, new File(uri.getPath()));
613 } else {
614 return uri;
615 }
616 }
617
618 private Builder buildMultipleConversation(final boolean notify, final boolean quietHours) {
619 final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService, quietHours ? "quiet_hours" : (notify ? "messages" : "silent_messages"));
620 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
621 style.setBigContentTitle(mXmppConnectionService.getString(R.string.x_unread_conversations, notifications.size()));
622 final StringBuilder names = new StringBuilder();
623 Conversation conversation = null;
624 for (final ArrayList<Message> messages : notifications.values()) {
625 if (messages.size() > 0) {
626 conversation = (Conversation) messages.get(0).getConversation();
627 final String name = conversation.getName().toString();
628 SpannableString styledString;
629 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
630 int count = messages.size();
631 styledString = new SpannableString(name + ": " + mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
632 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
633 style.addLine(styledString);
634 } else {
635 styledString = new SpannableString(name + ": " + UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
636 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
637 style.addLine(styledString);
638 }
639 names.append(name);
640 names.append(", ");
641 }
642 }
643 if (names.length() >= 2) {
644 names.delete(names.length() - 2, names.length());
645 }
646 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.x_unread_conversations, notifications.size()));
647 mBuilder.setTicker(mXmppConnectionService.getString(R.string.x_unread_conversations, notifications.size()));
648 mBuilder.setContentText(names.toString());
649 mBuilder.setStyle(style);
650 if (conversation != null) {
651 mBuilder.setContentIntent(createContentIntent(conversation));
652 }
653 mBuilder.setGroupSummary(true);
654 mBuilder.setGroup(CONVERSATIONS_GROUP);
655 mBuilder.setDeleteIntent(createDeleteIntent(null));
656 mBuilder.setSmallIcon(R.drawable.ic_notification);
657 return mBuilder;
658 }
659
660 private Builder buildSingleConversations(final ArrayList<Message> messages, final boolean notify, final boolean quietHours) {
661 final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService, quietHours ? "quiet_hours" : (notify ? "messages" : "silent_messages"));
662 if (messages.size() >= 1) {
663 final Conversation conversation = (Conversation) messages.get(0).getConversation();
664 mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
665 .get(conversation, AvatarService.getSystemUiAvatarSize(mXmppConnectionService)));
666 mBuilder.setContentTitle(conversation.getName());
667 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
668 int count = messages.size();
669 mBuilder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
670 } else {
671 Message message;
672 //TODO starting with Android 9 we might want to put images in MessageStyle
673 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P && (message = getImage(messages)) != null) {
674 modifyForImage(mBuilder, message, messages);
675 } else {
676 modifyForTextOnly(mBuilder, messages);
677 }
678 RemoteInput remoteInput = new RemoteInput.Builder("text_reply").setLabel(UIHelper.getMessageHint(mXmppConnectionService, conversation)).build();
679 PendingIntent markAsReadPendingIntent = createReadPendingIntent(conversation);
680 NotificationCompat.Action markReadAction = new NotificationCompat.Action.Builder(
681 R.drawable.ic_drafts_white_24dp,
682 mXmppConnectionService.getString(R.string.mark_as_read),
683 markAsReadPendingIntent)
684 .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ)
685 .setShowsUserInterface(false)
686 .build();
687 String replyLabel = mXmppConnectionService.getString(R.string.reply);
688 NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
689 R.drawable.ic_send_text_offline,
690 replyLabel,
691 createReplyIntent(conversation, false))
692 .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY)
693 .setShowsUserInterface(false)
694 .addRemoteInput(remoteInput).build();
695 NotificationCompat.Action wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_wear_reply,
696 replyLabel,
697 createReplyIntent(conversation, true)).addRemoteInput(remoteInput).build();
698 mBuilder.extend(new NotificationCompat.WearableExtender().addAction(wearReplyAction));
699 int addedActionsCount = 1;
700 mBuilder.addAction(markReadAction);
701 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
702 mBuilder.addAction(replyAction);
703 ++addedActionsCount;
704 }
705
706 if (displaySnoozeAction(messages)) {
707 String label = mXmppConnectionService.getString(R.string.snooze);
708 PendingIntent pendingSnoozeIntent = createSnoozeIntent(conversation);
709 NotificationCompat.Action snoozeAction = new NotificationCompat.Action.Builder(
710 R.drawable.ic_notifications_paused_white_24dp,
711 label,
712 pendingSnoozeIntent).build();
713 mBuilder.addAction(snoozeAction);
714 ++addedActionsCount;
715 }
716 if (addedActionsCount < 3) {
717 final Message firstLocationMessage = getFirstLocationMessage(messages);
718 if (firstLocationMessage != null) {
719 final PendingIntent pendingShowLocationIntent = createShowLocationIntent(firstLocationMessage);
720 if (pendingShowLocationIntent != null) {
721 final String label = mXmppConnectionService.getResources().getString(R.string.show_location);
722 NotificationCompat.Action locationAction = new NotificationCompat.Action.Builder(
723 R.drawable.ic_room_white_24dp,
724 label,
725 pendingShowLocationIntent).build();
726 mBuilder.addAction(locationAction);
727 ++addedActionsCount;
728 }
729 }
730 }
731 if (addedActionsCount < 3) {
732 Message firstDownloadableMessage = getFirstDownloadableMessage(messages);
733 if (firstDownloadableMessage != null) {
734 String label = mXmppConnectionService.getResources().getString(R.string.download_x_file, UIHelper.getFileDescriptionString(mXmppConnectionService, firstDownloadableMessage));
735 PendingIntent pendingDownloadIntent = createDownloadIntent(firstDownloadableMessage);
736 NotificationCompat.Action downloadAction = new NotificationCompat.Action.Builder(
737 R.drawable.ic_file_download_white_24dp,
738 label,
739 pendingDownloadIntent).build();
740 mBuilder.addAction(downloadAction);
741 ++addedActionsCount;
742 }
743 }
744 }
745 if (conversation.getMode() == Conversation.MODE_SINGLE) {
746 Contact contact = conversation.getContact();
747 Uri systemAccount = contact.getSystemAccount();
748 if (systemAccount != null) {
749 mBuilder.addPerson(systemAccount.toString());
750 }
751 }
752 mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
753 mBuilder.setSmallIcon(R.drawable.ic_notification);
754 mBuilder.setDeleteIntent(createDeleteIntent(conversation));
755 mBuilder.setContentIntent(createContentIntent(conversation));
756 }
757 return mBuilder;
758 }
759
760 private void modifyForImage(final Builder builder, final Message message, final ArrayList<Message> messages) {
761 try {
762 final Bitmap bitmap = mXmppConnectionService.getFileBackend().getThumbnail(message, getPixel(288), false);
763 final ArrayList<Message> tmp = new ArrayList<>();
764 for (final Message msg : messages) {
765 if (msg.getType() == Message.TYPE_TEXT
766 && msg.getTransferable() == null) {
767 tmp.add(msg);
768 }
769 }
770 final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
771 bigPictureStyle.bigPicture(bitmap);
772 if (tmp.size() > 0) {
773 CharSequence text = getMergedBodies(tmp);
774 bigPictureStyle.setSummaryText(text);
775 builder.setContentText(text);
776 builder.setTicker(text);
777 } else {
778 final String description = UIHelper.getFileDescriptionString(mXmppConnectionService, message);
779 builder.setContentText(description);
780 builder.setTicker(description);
781 }
782 builder.setStyle(bigPictureStyle);
783 } catch (final IOException e) {
784 modifyForTextOnly(builder, messages);
785 }
786 }
787
788 private Person getPerson(Message message) {
789 final Contact contact = message.getContact();
790 final Person.Builder builder = new Person.Builder();
791 if (contact != null) {
792 builder.setName(contact.getDisplayName());
793 final Uri uri = contact.getSystemAccount();
794 if (uri != null) {
795 builder.setUri(uri.toString());
796 }
797 } else {
798 builder.setName(UIHelper.getMessageDisplayName(message));
799 }
800 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
801 builder.setIcon(IconCompat.createWithBitmap(mXmppConnectionService.getAvatarService().get(message, AvatarService.getSystemUiAvatarSize(mXmppConnectionService), false)));
802 }
803 return builder.build();
804 }
805
806 private void modifyForTextOnly(final Builder builder, final ArrayList<Message> messages) {
807 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
808 final Conversation conversation = (Conversation) messages.get(0).getConversation();
809 final Person.Builder meBuilder = new Person.Builder().setName(mXmppConnectionService.getString(R.string.me));
810 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
811 meBuilder.setIcon(IconCompat.createWithBitmap(mXmppConnectionService.getAvatarService().get(conversation.getAccount(), AvatarService.getSystemUiAvatarSize(mXmppConnectionService))));
812 }
813 final Person me = meBuilder.build();
814 NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(me);
815 final boolean multiple = conversation.getMode() == Conversation.MODE_MULTI;
816 if (multiple) {
817 messagingStyle.setConversationTitle(conversation.getName());
818 }
819 for (Message message : messages) {
820 final Person sender = message.getStatus() == Message.STATUS_RECEIVED ? getPerson(message) : null;
821 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && isImageMessage(message)) {
822 final Uri dataUri = FileBackend.getMediaUri(mXmppConnectionService, mXmppConnectionService.getFileBackend().getFile(message));
823 NotificationCompat.MessagingStyle.Message imageMessage = new NotificationCompat.MessagingStyle.Message(UIHelper.getMessagePreview(mXmppConnectionService, message).first, message.getTimeSent(), sender);
824 if (dataUri != null) {
825 imageMessage.setData(message.getMimeType(), dataUri);
826 }
827 messagingStyle.addMessage(imageMessage);
828 } else {
829 messagingStyle.addMessage(UIHelper.getMessagePreview(mXmppConnectionService, message).first, message.getTimeSent(), sender);
830 }
831 }
832 messagingStyle.setGroupConversation(multiple);
833 builder.setStyle(messagingStyle);
834 } else {
835 if (messages.get(0).getConversation().getMode() == Conversation.MODE_SINGLE) {
836 builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
837 final CharSequence preview = UIHelper.getMessagePreview(mXmppConnectionService, messages.get(messages.size() - 1)).first;
838 builder.setContentText(preview);
839 builder.setTicker(preview);
840 builder.setNumber(messages.size());
841 } else {
842 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
843 SpannableString styledString;
844 for (Message message : messages) {
845 final String name = UIHelper.getMessageDisplayName(message);
846 styledString = new SpannableString(name + ": " + message.getBody());
847 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
848 style.addLine(styledString);
849 }
850 builder.setStyle(style);
851 int count = messages.size();
852 if (count == 1) {
853 final String name = UIHelper.getMessageDisplayName(messages.get(0));
854 styledString = new SpannableString(name + ": " + messages.get(0).getBody());
855 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
856 builder.setContentText(styledString);
857 builder.setTicker(styledString);
858 } else {
859 final String text = mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count);
860 builder.setContentText(text);
861 builder.setTicker(text);
862 }
863 }
864 }
865 }
866
867 private Message getImage(final Iterable<Message> messages) {
868 Message image = null;
869 for (final Message message : messages) {
870 if (message.getStatus() != Message.STATUS_RECEIVED) {
871 return null;
872 }
873 if (isImageMessage(message)) {
874 image = message;
875 }
876 }
877 return image;
878 }
879
880 private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
881 for (final Message message : messages) {
882 if (message.getTransferable() != null || (message.getType() == Message.TYPE_TEXT && message.treatAsDownloadable())) {
883 return message;
884 }
885 }
886 return null;
887 }
888
889 private Message getFirstLocationMessage(final Iterable<Message> messages) {
890 for (final Message message : messages) {
891 if (message.isGeoUri()) {
892 return message;
893 }
894 }
895 return null;
896 }
897
898 private CharSequence getMergedBodies(final ArrayList<Message> messages) {
899 final StringBuilder text = new StringBuilder();
900 for (Message message : messages) {
901 if (text.length() != 0) {
902 text.append("\n");
903 }
904 text.append(UIHelper.getMessagePreview(mXmppConnectionService, message).first);
905 }
906 return text.toString();
907 }
908
909 private PendingIntent createShowLocationIntent(final Message message) {
910 Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(mXmppConnectionService, message);
911 for (Intent intent : intents) {
912 if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
913 return PendingIntent.getActivity(mXmppConnectionService, generateRequestCode(message.getConversation(), 18), intent, PendingIntent.FLAG_UPDATE_CURRENT);
914 }
915 }
916 return null;
917 }
918
919 private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
920 final Intent viewConversationIntent = new Intent(mXmppConnectionService, ConversationsActivity.class);
921 viewConversationIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
922 viewConversationIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversationUuid);
923 if (downloadMessageUuid != null) {
924 viewConversationIntent.putExtra(ConversationsActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
925 return PendingIntent.getActivity(mXmppConnectionService,
926 generateRequestCode(conversationUuid, 8),
927 viewConversationIntent,
928 PendingIntent.FLAG_UPDATE_CURRENT);
929 } else {
930 return PendingIntent.getActivity(mXmppConnectionService,
931 generateRequestCode(conversationUuid, 10),
932 viewConversationIntent,
933 PendingIntent.FLAG_UPDATE_CURRENT);
934 }
935 }
936
937 private int generateRequestCode(String uuid, int actionId) {
938 return (actionId * NOTIFICATION_ID_MULTIPLIER) + (uuid.hashCode() % NOTIFICATION_ID_MULTIPLIER);
939 }
940
941 private int generateRequestCode(Conversational conversation, int actionId) {
942 return generateRequestCode(conversation.getUuid(), actionId);
943 }
944
945 private PendingIntent createDownloadIntent(final Message message) {
946 return createContentIntent(message.getConversationUuid(), message.getUuid());
947 }
948
949 private PendingIntent createContentIntent(final Conversational conversation) {
950 return createContentIntent(conversation.getUuid(), null);
951 }
952
953 private PendingIntent createDeleteIntent(Conversation conversation) {
954 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
955 intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
956 if (conversation != null) {
957 intent.putExtra("uuid", conversation.getUuid());
958 return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 20), intent, 0);
959 }
960 return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
961 }
962
963 private PendingIntent createReplyIntent(Conversation conversation, boolean dismissAfterReply) {
964 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
965 intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
966 intent.putExtra("uuid", conversation.getUuid());
967 intent.putExtra("dismiss_notification", dismissAfterReply);
968 final int id = generateRequestCode(conversation, dismissAfterReply ? 12 : 14);
969 return PendingIntent.getService(mXmppConnectionService, id, intent, 0);
970 }
971
972 private PendingIntent createReadPendingIntent(Conversation conversation) {
973 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
974 intent.setAction(XmppConnectionService.ACTION_MARK_AS_READ);
975 intent.putExtra("uuid", conversation.getUuid());
976 intent.setPackage(mXmppConnectionService.getPackageName());
977 return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 16), intent, PendingIntent.FLAG_UPDATE_CURRENT);
978 }
979
980 private PendingIntent createCallAction(String sessionId, final String action, int requestCode) {
981 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
982 intent.setAction(action);
983 intent.setPackage(mXmppConnectionService.getPackageName());
984 intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, sessionId);
985 return PendingIntent.getService(mXmppConnectionService, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
986 }
987
988 private PendingIntent createSnoozeIntent(Conversation conversation) {
989 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
990 intent.setAction(XmppConnectionService.ACTION_SNOOZE);
991 intent.putExtra("uuid", conversation.getUuid());
992 intent.setPackage(mXmppConnectionService.getPackageName());
993 return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 22), intent, PendingIntent.FLAG_UPDATE_CURRENT);
994 }
995
996 private PendingIntent createTryAgainIntent() {
997 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
998 intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
999 return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
1000 }
1001
1002 private PendingIntent createDismissErrorIntent() {
1003 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1004 intent.setAction(XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS);
1005 return PendingIntent.getService(mXmppConnectionService, 69, intent, 0);
1006 }
1007
1008 private boolean wasHighlightedOrPrivate(final Message message) {
1009 if (message.getConversation() instanceof Conversation) {
1010 Conversation conversation = (Conversation) message.getConversation();
1011 final String nick = conversation.getMucOptions().getActualNick();
1012 final Pattern highlight = generateNickHighlightPattern(nick);
1013 if (message.getBody() == null || nick == null) {
1014 return false;
1015 }
1016 final Matcher m = highlight.matcher(message.getBody());
1017 return (m.find() || message.isPrivateMessage());
1018 } else {
1019 return false;
1020 }
1021 }
1022
1023 public void setOpenConversation(final Conversation conversation) {
1024 this.mOpenConversation = conversation;
1025 }
1026
1027 public void setIsInForeground(final boolean foreground) {
1028 this.mIsInForeground = foreground;
1029 }
1030
1031 private int getPixel(final int dp) {
1032 final DisplayMetrics metrics = mXmppConnectionService.getResources()
1033 .getDisplayMetrics();
1034 return ((int) (dp * metrics.density));
1035 }
1036
1037 private void markLastNotification() {
1038 this.mLastNotification = SystemClock.elapsedRealtime();
1039 }
1040
1041 private boolean inMiniGracePeriod(final Account account) {
1042 final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
1043 : Config.MINI_GRACE_PERIOD * 2;
1044 return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
1045 }
1046
1047 Notification createForegroundNotification() {
1048 final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1049 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.app_name));
1050 final List<Account> accounts = mXmppConnectionService.getAccounts();
1051 int enabled = 0;
1052 int connected = 0;
1053 if (accounts != null) {
1054 for (Account account : accounts) {
1055 if (account.isOnlineAndConnected()) {
1056 connected++;
1057 enabled++;
1058 } else if (account.isEnabled()) {
1059 enabled++;
1060 }
1061 }
1062 }
1063 mBuilder.setContentText(mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
1064 final PendingIntent openIntent = createOpenConversationsIntent();
1065 if (openIntent != null) {
1066 mBuilder.setContentIntent(openIntent);
1067 }
1068 mBuilder.setWhen(0);
1069 mBuilder.setPriority(Notification.PRIORITY_MIN);
1070 mBuilder.setSmallIcon(connected > 0 ? R.drawable.ic_link_white_24dp : R.drawable.ic_link_off_white_24dp);
1071
1072 if (Compatibility.runsTwentySix()) {
1073 mBuilder.setChannelId("foreground");
1074 }
1075
1076
1077 return mBuilder.build();
1078 }
1079
1080 private PendingIntent createOpenConversationsIntent() {
1081 try {
1082 return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService, ConversationsActivity.class), 0);
1083 } catch (RuntimeException e) {
1084 return null;
1085 }
1086 }
1087
1088 void updateErrorNotification() {
1089 if (Config.SUPPRESS_ERROR_NOTIFICATION) {
1090 cancel(ERROR_NOTIFICATION_ID);
1091 return;
1092 }
1093 final boolean showAllErrors = QuickConversationsService.isConversations();
1094 final List<Account> errors = new ArrayList<>();
1095 for (final Account account : mXmppConnectionService.getAccounts()) {
1096 if (account.hasErrorStatus() && account.showErrorNotification() && (showAllErrors || account.getLastErrorStatus() == Account.State.UNAUTHORIZED)) {
1097 errors.add(account);
1098 }
1099 }
1100 if (mXmppConnectionService.foregroundNotificationNeedsUpdatingWhenErrorStateChanges()) {
1101 notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
1102 }
1103 final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1104 if (errors.size() == 0) {
1105 cancel(ERROR_NOTIFICATION_ID);
1106 return;
1107 } else if (errors.size() == 1) {
1108 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
1109 mBuilder.setContentText(errors.get(0).getJid().asBareJid().toEscapedString());
1110 } else {
1111 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
1112 mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
1113 }
1114 mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
1115 mXmppConnectionService.getString(R.string.try_again),
1116 createTryAgainIntent());
1117 mBuilder.setDeleteIntent(createDismissErrorIntent());
1118 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
1119 mBuilder.setVisibility(Notification.VISIBILITY_PRIVATE);
1120 mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
1121 } else {
1122 mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
1123 }
1124 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
1125 mBuilder.setLocalOnly(true);
1126 }
1127 mBuilder.setPriority(Notification.PRIORITY_LOW);
1128 final Intent intent;
1129 if (AccountUtils.MANAGE_ACCOUNT_ACTIVITY != null) {
1130 intent = new Intent(mXmppConnectionService, AccountUtils.MANAGE_ACCOUNT_ACTIVITY);
1131 } else {
1132 intent = new Intent(mXmppConnectionService, EditAccountActivity.class);
1133 intent.putExtra("jid", errors.get(0).getJid().asBareJid().toEscapedString());
1134 intent.putExtra(EditAccountActivity.EXTRA_OPENED_FROM_NOTIFICATION, true);
1135 }
1136 mBuilder.setContentIntent(PendingIntent.getActivity(mXmppConnectionService, 145, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1137 if (Compatibility.runsTwentySix()) {
1138 mBuilder.setChannelId("error");
1139 }
1140 notify(ERROR_NOTIFICATION_ID, mBuilder.build());
1141 }
1142
1143 void updateFileAddingNotification(int current, Message message) {
1144 Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1145 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.transcoding_video));
1146 mBuilder.setProgress(100, current, false);
1147 mBuilder.setSmallIcon(R.drawable.ic_hourglass_empty_white_24dp);
1148 mBuilder.setContentIntent(createContentIntent(message.getConversation()));
1149 mBuilder.setOngoing(true);
1150 if (Compatibility.runsTwentySix()) {
1151 mBuilder.setChannelId("compression");
1152 }
1153 Notification notification = mBuilder.build();
1154 notify(FOREGROUND_NOTIFICATION_ID, notification);
1155 }
1156
1157 private void notify(String tag, int id, Notification notification) {
1158 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1159 try {
1160 notificationManager.notify(tag, id, notification);
1161 } catch (RuntimeException e) {
1162 Log.d(Config.LOGTAG, "unable to make notification", e);
1163 }
1164 }
1165
1166 public void notify(int id, Notification notification) {
1167 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1168 try {
1169 notificationManager.notify(id, notification);
1170 } catch (RuntimeException e) {
1171 Log.d(Config.LOGTAG, "unable to make notification", e);
1172 }
1173 }
1174
1175 public void cancel(int id) {
1176 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1177 try {
1178 notificationManager.cancel(id);
1179 } catch (RuntimeException e) {
1180 Log.d(Config.LOGTAG, "unable to cancel notification", e);
1181 }
1182 }
1183
1184 private void cancel(String tag, int id) {
1185 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1186 try {
1187 notificationManager.cancel(tag, id);
1188 } catch (RuntimeException e) {
1189 Log.d(Config.LOGTAG, "unable to cancel notification", e);
1190 }
1191 }
1192}