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