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