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