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