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