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