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.Person;
26import android.support.v4.app.RemoteInput;
27import android.support.v4.content.ContextCompat;
28import android.support.v4.graphics.drawable.IconCompat;
29import android.text.SpannableString;
30import android.text.style.StyleSpan;
31import android.util.DisplayMetrics;
32import android.util.Log;
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.Set;
45import java.util.concurrent.atomic.AtomicInteger;
46import java.util.regex.Matcher;
47import java.util.regex.Pattern;
48
49import eu.siacs.conversations.Config;
50import eu.siacs.conversations.R;
51import eu.siacs.conversations.entities.Account;
52import eu.siacs.conversations.entities.Contact;
53import eu.siacs.conversations.entities.Conversation;
54import eu.siacs.conversations.entities.Conversational;
55import eu.siacs.conversations.entities.Message;
56import eu.siacs.conversations.persistance.FileBackend;
57import eu.siacs.conversations.ui.ConversationsActivity;
58import eu.siacs.conversations.ui.EditAccountActivity;
59import eu.siacs.conversations.ui.RtpSessionActivity;
60import eu.siacs.conversations.ui.TimePreference;
61import eu.siacs.conversations.utils.AccountUtils;
62import eu.siacs.conversations.utils.Compatibility;
63import eu.siacs.conversations.utils.GeoHelper;
64import eu.siacs.conversations.utils.UIHelper;
65import eu.siacs.conversations.xmpp.XmppConnection;
66import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
67import eu.siacs.conversations.xmpp.jingle.Media;
68
69public class NotificationService {
70
71 public static final Object CATCHUP_LOCK = new Object();
72
73 private static final int LED_COLOR = 0xff00ff00;
74
75 private static final int CALL_DAT = 120;
76 private static final long[] CALL_PATTERN = {0, 3 * CALL_DAT, CALL_DAT, CALL_DAT, 3 * CALL_DAT, CALL_DAT, CALL_DAT};
77
78 private static final String CONVERSATIONS_GROUP = "eu.siacs.conversations";
79 private static final int NOTIFICATION_ID_MULTIPLIER = 1024 * 1024;
80 static final int FOREGROUND_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 4;
81 private static final int NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 2;
82 private static final int ERROR_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 6;
83 private static final int INCOMING_CALL_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 8;
84 public static final int ONGOING_CALL_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 10;
85 private final XmppConnectionService mXmppConnectionService;
86 private final LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<>();
87 private final HashMap<Conversation, AtomicInteger> mBacklogMessageCounter = new HashMap<>();
88 private Conversation mOpenConversation;
89 private boolean mIsInForeground;
90 private long mLastNotification;
91
92 NotificationService(final XmppConnectionService service) {
93 this.mXmppConnectionService = service;
94 }
95
96 private static boolean displaySnoozeAction(List<Message> messages) {
97 int numberOfMessagesWithoutReply = 0;
98 for (Message message : messages) {
99 if (message.getStatus() == Message.STATUS_RECEIVED) {
100 ++numberOfMessagesWithoutReply;
101 } else {
102 return false;
103 }
104 }
105 return numberOfMessagesWithoutReply >= 3;
106 }
107
108 public static Pattern generateNickHighlightPattern(final String nick) {
109 return Pattern.compile("(?<=(^|\\s))" + Pattern.quote(nick) + "(?=\\s|$|\\p{Punct})");
110 }
111
112 private static boolean isImageMessage(Message message) {
113 return message.getType() != Message.TYPE_TEXT
114 && message.getTransferable() == null
115 && !message.isDeleted()
116 && message.getEncryption() != Message.ENCRYPTION_PGP
117 && message.getFileParams().height > 0;
118 }
119
120 @RequiresApi(api = Build.VERSION_CODES.O)
121 void initializeChannels() {
122 final Context c = mXmppConnectionService;
123 final NotificationManager notificationManager = c.getSystemService(NotificationManager.class);
124 if (notificationManager == null) {
125 return;
126 }
127
128 notificationManager.deleteNotificationChannel("export");
129
130 notificationManager.createNotificationChannelGroup(new NotificationChannelGroup("status", c.getString(R.string.notification_group_status_information)));
131 notificationManager.createNotificationChannelGroup(new NotificationChannelGroup("chats", c.getString(R.string.notification_group_messages)));
132 notificationManager.createNotificationChannelGroup(new NotificationChannelGroup("calls", c.getString(R.string.notification_group_calls)));
133 final NotificationChannel foregroundServiceChannel = new NotificationChannel("foreground",
134 c.getString(R.string.foreground_service_channel_name),
135 NotificationManager.IMPORTANCE_MIN);
136 foregroundServiceChannel.setDescription(c.getString(R.string.foreground_service_channel_description));
137 foregroundServiceChannel.setShowBadge(false);
138 foregroundServiceChannel.setGroup("status");
139 notificationManager.createNotificationChannel(foregroundServiceChannel);
140 final NotificationChannel errorChannel = new NotificationChannel("error",
141 c.getString(R.string.error_channel_name),
142 NotificationManager.IMPORTANCE_LOW);
143 errorChannel.setDescription(c.getString(R.string.error_channel_description));
144 errorChannel.setShowBadge(false);
145 errorChannel.setGroup("status");
146 notificationManager.createNotificationChannel(errorChannel);
147
148 final NotificationChannel videoCompressionChannel = new NotificationChannel("compression",
149 c.getString(R.string.video_compression_channel_name),
150 NotificationManager.IMPORTANCE_LOW);
151 videoCompressionChannel.setShowBadge(false);
152 videoCompressionChannel.setGroup("status");
153 notificationManager.createNotificationChannel(videoCompressionChannel);
154
155 final NotificationChannel exportChannel = new NotificationChannel("backup",
156 c.getString(R.string.backup_channel_name),
157 NotificationManager.IMPORTANCE_LOW);
158 exportChannel.setShowBadge(false);
159 exportChannel.setGroup("status");
160 notificationManager.createNotificationChannel(exportChannel);
161
162 final NotificationChannel incomingCallsChannel = new NotificationChannel("incoming_calls",
163 c.getString(R.string.incoming_calls_channel_name),
164 NotificationManager.IMPORTANCE_HIGH);
165 incomingCallsChannel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE), new AudioAttributes.Builder()
166 .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
167 .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
168 .build());
169 incomingCallsChannel.setShowBadge(false);
170 incomingCallsChannel.setLightColor(LED_COLOR);
171 incomingCallsChannel.enableLights(true);
172 incomingCallsChannel.setGroup("calls");
173 incomingCallsChannel.setBypassDnd(true);
174 incomingCallsChannel.enableVibration(true);
175 incomingCallsChannel.setVibrationPattern(CALL_PATTERN);
176 notificationManager.createNotificationChannel(incomingCallsChannel);
177
178 final NotificationChannel ongoingCallsChannel = new NotificationChannel("ongoing_calls",
179 c.getString(R.string.ongoing_calls_channel_name),
180 NotificationManager.IMPORTANCE_LOW);
181 ongoingCallsChannel.setShowBadge(false);
182 ongoingCallsChannel.setGroup("calls");
183 notificationManager.createNotificationChannel(ongoingCallsChannel);
184
185
186 final NotificationChannel messagesChannel = new NotificationChannel("messages",
187 c.getString(R.string.messages_channel_name),
188 NotificationManager.IMPORTANCE_HIGH);
189 messagesChannel.setShowBadge(true);
190 messagesChannel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), new AudioAttributes.Builder()
191 .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
192 .setUsage(AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT)
193 .build());
194 messagesChannel.setLightColor(LED_COLOR);
195 final int dat = 70;
196 final long[] pattern = {0, 3 * dat, dat, dat};
197 messagesChannel.setVibrationPattern(pattern);
198 messagesChannel.enableVibration(true);
199 messagesChannel.enableLights(true);
200 messagesChannel.setGroup("chats");
201 notificationManager.createNotificationChannel(messagesChannel);
202 final NotificationChannel silentMessagesChannel = new NotificationChannel("silent_messages",
203 c.getString(R.string.silent_messages_channel_name),
204 NotificationManager.IMPORTANCE_LOW);
205 silentMessagesChannel.setDescription(c.getString(R.string.silent_messages_channel_description));
206 silentMessagesChannel.setShowBadge(true);
207 silentMessagesChannel.setLightColor(LED_COLOR);
208 silentMessagesChannel.enableLights(true);
209 silentMessagesChannel.setGroup("chats");
210 notificationManager.createNotificationChannel(silentMessagesChannel);
211
212 final NotificationChannel quietHoursChannel = new NotificationChannel("quiet_hours",
213 c.getString(R.string.title_pref_quiet_hours),
214 NotificationManager.IMPORTANCE_LOW);
215 quietHoursChannel.setShowBadge(true);
216 quietHoursChannel.setLightColor(LED_COLOR);
217 quietHoursChannel.enableLights(true);
218 quietHoursChannel.setGroup("chats");
219 quietHoursChannel.enableVibration(false);
220 quietHoursChannel.setSound(null, null);
221
222 notificationManager.createNotificationChannel(quietHoursChannel);
223 }
224
225 public boolean notify(final Message message) {
226 final Conversation conversation = (Conversation) message.getConversation();
227 return message.getStatus() == Message.STATUS_RECEIVED
228 && !conversation.isMuted()
229 && (conversation.alwaysNotify() || wasHighlightedOrPrivate(message))
230 && (!conversation.isWithStranger() || notificationsFromStrangers());
231 }
232
233 public boolean notificationsFromStrangers() {
234 return mXmppConnectionService.getBooleanPreference("notifications_from_strangers", R.bool.notifications_from_strangers);
235 }
236
237 private boolean isQuietHours() {
238 if (!mXmppConnectionService.getBooleanPreference("enable_quiet_hours", R.bool.enable_quiet_hours)) {
239 return false;
240 }
241 final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
242 final long startTime = TimePreference.minutesToTimestamp(preferences.getLong("quiet_hours_start", TimePreference.DEFAULT_VALUE));
243 final long endTime = TimePreference.minutesToTimestamp(preferences.getLong("quiet_hours_end", TimePreference.DEFAULT_VALUE));
244 final long nowTime = Calendar.getInstance().getTimeInMillis();
245
246 if (endTime < startTime) {
247 return nowTime > startTime || nowTime < endTime;
248 } else {
249 return nowTime > startTime && nowTime < endTime;
250 }
251 }
252
253 public void pushFromBacklog(final Message message) {
254 if (notify(message)) {
255 synchronized (notifications) {
256 getBacklogMessageCounter((Conversation) message.getConversation()).incrementAndGet();
257 pushToStack(message);
258 }
259 }
260 }
261
262 private AtomicInteger getBacklogMessageCounter(Conversation conversation) {
263 synchronized (mBacklogMessageCounter) {
264 if (!mBacklogMessageCounter.containsKey(conversation)) {
265 mBacklogMessageCounter.put(conversation, new AtomicInteger(0));
266 }
267 return mBacklogMessageCounter.get(conversation);
268 }
269 }
270
271 void pushFromDirectReply(final Message message) {
272 synchronized (notifications) {
273 pushToStack(message);
274 updateNotification(false);
275 }
276 }
277
278 public void finishBacklog(boolean notify, Account account) {
279 synchronized (notifications) {
280 mXmppConnectionService.updateUnreadCountBadge();
281 if (account == null || !notify) {
282 updateNotification(notify);
283 } else {
284 final int count;
285 final List<String> conversations;
286 synchronized (this.mBacklogMessageCounter) {
287 conversations = getBacklogConversations(account);
288 count = getBacklogMessageCount(account);
289 }
290 updateNotification(count > 0, conversations);
291 }
292 }
293 }
294
295 private List<String> getBacklogConversations(Account account) {
296 final List<String> conversations = new ArrayList<>();
297 for (Map.Entry<Conversation, AtomicInteger> entry : mBacklogMessageCounter.entrySet()) {
298 if (entry.getKey().getAccount() == account) {
299 conversations.add(entry.getKey().getUuid());
300 }
301 }
302 return conversations;
303 }
304
305 private int getBacklogMessageCount(Account account) {
306 int count = 0;
307 for (Iterator<Map.Entry<Conversation, AtomicInteger>> it = mBacklogMessageCounter.entrySet().iterator(); it.hasNext(); ) {
308 Map.Entry<Conversation, AtomicInteger> entry = it.next();
309 if (entry.getKey().getAccount() == account) {
310 count += entry.getValue().get();
311 it.remove();
312 }
313 }
314 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": backlog message count=" + count);
315 return count;
316 }
317
318 void finishBacklog(boolean notify) {
319 finishBacklog(notify, null);
320 }
321
322 private void pushToStack(final Message message) {
323 final String conversationUuid = message.getConversationUuid();
324 if (notifications.containsKey(conversationUuid)) {
325 notifications.get(conversationUuid).add(message);
326 } else {
327 final ArrayList<Message> mList = new ArrayList<>();
328 mList.add(message);
329 notifications.put(conversationUuid, mList);
330 }
331 }
332
333 public void push(final Message message) {
334 synchronized (CATCHUP_LOCK) {
335 final XmppConnection connection = message.getConversation().getAccount().getXmppConnection();
336 if (connection != null && connection.isWaitingForSmCatchup()) {
337 connection.incrementSmCatchupMessageCounter();
338 pushFromBacklog(message);
339 } else {
340 pushNow(message);
341 }
342 }
343 }
344
345 public void showIncomingCallNotification(final AbstractJingleConnection.Id id, final Set<Media> media) {
346 final Intent fullScreenIntent = new Intent(mXmppConnectionService, RtpSessionActivity.class);
347 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, id.account.getJid().asBareJid().toEscapedString());
348 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_WITH, id.with.toEscapedString());
349 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.sessionId);
350 fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
351 fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
352 final NotificationCompat.Builder builder = new NotificationCompat.Builder(mXmppConnectionService, "incoming_calls");
353 if (media.contains(Media.VIDEO)) {
354 builder.setSmallIcon(R.drawable.ic_videocam_white_24dp);
355 builder.setContentTitle(mXmppConnectionService.getString(R.string.rtp_state_incoming_video_call));
356 } else {
357 builder.setSmallIcon(R.drawable.ic_call_white_24dp);
358 builder.setContentTitle(mXmppConnectionService.getString(R.string.rtp_state_incoming_call));
359 }
360 final Contact contact = id.getContact();
361 builder.setLargeIcon(mXmppConnectionService.getAvatarService().get(
362 contact,
363 AvatarService.getSystemUiAvatarSize(mXmppConnectionService))
364 );
365 final Uri systemAccount = contact.getSystemAccount();
366 if (systemAccount != null) {
367 builder.addPerson(systemAccount.toString());
368 }
369 builder.setContentText(id.account.getRoster().getContact(id.with).getDisplayName());
370 builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
371 builder.setPriority(NotificationCompat.PRIORITY_HIGH);
372 builder.setCategory(NotificationCompat.CATEGORY_CALL);
373 PendingIntent pendingIntent = createPendingRtpSession(id, Intent.ACTION_VIEW, 101);
374 builder.setFullScreenIntent(pendingIntent, true);
375 builder.setContentIntent(pendingIntent); //old androids need this?
376 builder.setOngoing(true);
377 builder.addAction(new NotificationCompat.Action.Builder(
378 R.drawable.ic_call_end_white_48dp,
379 mXmppConnectionService.getString(R.string.dismiss_call),
380 createCallAction(id.sessionId, XmppConnectionService.ACTION_DISMISS_CALL, 102))
381 .build());
382 builder.addAction(new NotificationCompat.Action.Builder(
383 R.drawable.ic_call_white_24dp,
384 mXmppConnectionService.getString(R.string.answer_call),
385 createPendingRtpSession(id, RtpSessionActivity.ACTION_ACCEPT_CALL, 103))
386 .build());
387 modifyIncomingCall(builder);
388 final Notification notification = builder.build();
389 notification.flags = notification.flags | Notification.FLAG_INSISTENT;
390 notify(INCOMING_CALL_NOTIFICATION_ID, notification);
391 }
392
393 public Notification getOngoingCallNotification(final AbstractJingleConnection.Id id, final Set<Media> media) {
394 final NotificationCompat.Builder builder = new NotificationCompat.Builder(mXmppConnectionService, "ongoing_calls");
395 if (media.contains(Media.VIDEO)) {
396 builder.setSmallIcon(R.drawable.ic_videocam_white_24dp);
397 builder.setContentTitle(mXmppConnectionService.getString(R.string.ongoing_video_call));
398 } else {
399 builder.setSmallIcon(R.drawable.ic_call_white_24dp);
400 builder.setContentTitle(mXmppConnectionService.getString(R.string.ongoing_call));
401 }
402 builder.setContentText(id.account.getRoster().getContact(id.with).getDisplayName());
403 builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
404 builder.setPriority(NotificationCompat.PRIORITY_HIGH);
405 builder.setCategory(NotificationCompat.CATEGORY_CALL);
406 builder.setContentIntent(createPendingRtpSession(id, Intent.ACTION_VIEW, 101));
407 builder.setOngoing(true);
408 builder.addAction(new NotificationCompat.Action.Builder(
409 R.drawable.ic_call_end_white_48dp,
410 mXmppConnectionService.getString(R.string.hang_up),
411 createCallAction(id.sessionId, XmppConnectionService.ACTION_END_CALL, 104))
412 .build());
413 return builder.build();
414 }
415
416 private PendingIntent createPendingRtpSession(final AbstractJingleConnection.Id id, final String action, final int requestCode) {
417 final Intent fullScreenIntent = new Intent(mXmppConnectionService, RtpSessionActivity.class);
418 fullScreenIntent.setAction(action);
419 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, id.account.getJid().asBareJid().toEscapedString());
420 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_WITH, id.with.toEscapedString());
421 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.sessionId);
422 return PendingIntent.getActivity(mXmppConnectionService, requestCode, fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);
423 }
424
425 public void cancelIncomingCallNotification() {
426 cancel(INCOMING_CALL_NOTIFICATION_ID);
427 }
428
429 private void pushNow(final Message message) {
430 mXmppConnectionService.updateUnreadCountBadge();
431 if (!notify(message)) {
432 Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because turned off");
433 return;
434 }
435 final boolean isScreenOn = mXmppConnectionService.isInteractive();
436 if (this.mIsInForeground && isScreenOn && this.mOpenConversation == message.getConversation()) {
437 Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because conversation is open");
438 return;
439 }
440 synchronized (notifications) {
441 pushToStack(message);
442 final Conversational conversation = message.getConversation();
443 final Account account = conversation.getAccount();
444 final boolean doNotify = (!(this.mIsInForeground && this.mOpenConversation == null) || !isScreenOn)
445 && !account.inGracePeriod()
446 && !this.inMiniGracePeriod(account);
447 updateNotification(doNotify, Collections.singletonList(conversation.getUuid()));
448 }
449 }
450
451 public void clear() {
452 synchronized (notifications) {
453 for (ArrayList<Message> messages : notifications.values()) {
454 markAsReadIfHasDirectReply(messages);
455 }
456 notifications.clear();
457 updateNotification(false);
458 }
459 }
460
461 public void clear(final Conversation conversation) {
462 synchronized (this.mBacklogMessageCounter) {
463 this.mBacklogMessageCounter.remove(conversation);
464 }
465 synchronized (notifications) {
466 markAsReadIfHasDirectReply(conversation);
467 if (notifications.remove(conversation.getUuid()) != null) {
468 cancel(conversation.getUuid(), NOTIFICATION_ID);
469 updateNotification(false, null, true);
470 }
471 }
472 }
473
474 private void markAsReadIfHasDirectReply(final Conversation conversation) {
475 markAsReadIfHasDirectReply(notifications.get(conversation.getUuid()));
476 }
477
478 private void markAsReadIfHasDirectReply(final ArrayList<Message> messages) {
479 if (messages != null && messages.size() > 0) {
480 Message last = messages.get(messages.size() - 1);
481 if (last.getStatus() != Message.STATUS_RECEIVED) {
482 if (mXmppConnectionService.markRead((Conversation) last.getConversation(), false)) {
483 mXmppConnectionService.updateConversationUi();
484 }
485 }
486 }
487 }
488
489 private void setNotificationColor(final Builder mBuilder) {
490 mBuilder.setColor(ContextCompat.getColor(mXmppConnectionService, R.color.green600));
491 }
492
493 public void updateNotification() {
494 synchronized (notifications) {
495 updateNotification(false);
496 }
497 }
498
499 private void updateNotification(final boolean notify) {
500 updateNotification(notify, null, false);
501 }
502
503 private void updateNotification(final boolean notify, final List<String> conversations) {
504 updateNotification(notify, conversations, false);
505 }
506
507 private void updateNotification(final boolean notify, final List<String> conversations, final boolean summaryOnly) {
508 final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
509
510 final boolean quiteHours = isQuietHours();
511
512 final boolean notifyOnlyOneChild = notify && conversations != null && conversations.size() == 1; //if this check is changed to > 0 catchup messages will create one notification per conversation
513
514
515 if (notifications.size() == 0) {
516 cancel(NOTIFICATION_ID);
517 } else {
518 if (notify) {
519 this.markLastNotification();
520 }
521 final Builder mBuilder;
522 if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
523 mBuilder = buildSingleConversations(notifications.values().iterator().next(), notify, quiteHours);
524 modifyForSoundVibrationAndLight(mBuilder, notify, quiteHours, preferences);
525 notify(NOTIFICATION_ID, mBuilder.build());
526 } else {
527 mBuilder = buildMultipleConversation(notify, quiteHours);
528 if (notifyOnlyOneChild) {
529 mBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
530 }
531 modifyForSoundVibrationAndLight(mBuilder, notify, quiteHours, preferences);
532 if (!summaryOnly) {
533 for (Map.Entry<String, ArrayList<Message>> entry : notifications.entrySet()) {
534 String uuid = entry.getKey();
535 final boolean notifyThis = notifyOnlyOneChild ? conversations.contains(uuid) : notify;
536 Builder singleBuilder = buildSingleConversations(entry.getValue(), notifyThis, quiteHours);
537 if (!notifyOnlyOneChild) {
538 singleBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY);
539 }
540 modifyForSoundVibrationAndLight(singleBuilder, notifyThis, quiteHours, preferences);
541 singleBuilder.setGroup(CONVERSATIONS_GROUP);
542 setNotificationColor(singleBuilder);
543 notify(entry.getKey(), NOTIFICATION_ID, singleBuilder.build());
544 }
545 }
546 notify(NOTIFICATION_ID, mBuilder.build());
547 }
548 }
549 }
550
551 private void modifyForSoundVibrationAndLight(Builder mBuilder, boolean notify, boolean quietHours, SharedPreferences preferences) {
552 final Resources resources = mXmppConnectionService.getResources();
553 final String ringtone = preferences.getString("notification_ringtone", resources.getString(R.string.notification_ringtone));
554 final boolean vibrate = preferences.getBoolean("vibrate_on_notification", resources.getBoolean(R.bool.vibrate_on_notification));
555 final boolean led = preferences.getBoolean("led", resources.getBoolean(R.bool.led));
556 final boolean headsup = preferences.getBoolean("notification_headsup", resources.getBoolean(R.bool.headsup_notifications));
557 if (notify && !quietHours) {
558 if (vibrate) {
559 final int dat = 70;
560 final long[] pattern = {0, 3 * dat, dat, dat};
561 mBuilder.setVibrate(pattern);
562 } else {
563 mBuilder.setVibrate(new long[]{0});
564 }
565 Uri uri = Uri.parse(ringtone);
566 try {
567 mBuilder.setSound(fixRingtoneUri(uri));
568 } catch (SecurityException e) {
569 Log.d(Config.LOGTAG, "unable to use custom notification sound " + uri.toString());
570 }
571 } else {
572 mBuilder.setLocalOnly(true);
573 }
574 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
575 mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
576 }
577 mBuilder.setPriority(notify ? (headsup ? NotificationCompat.PRIORITY_HIGH : NotificationCompat.PRIORITY_DEFAULT) : NotificationCompat.PRIORITY_LOW);
578 setNotificationColor(mBuilder);
579 mBuilder.setDefaults(0);
580 if (led) {
581 mBuilder.setLights(LED_COLOR, 2000, 3000);
582 }
583 }
584
585 private void modifyIncomingCall(Builder mBuilder) {
586 final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
587 final Resources resources = mXmppConnectionService.getResources();
588 final String ringtone = preferences.getString("call_ringtone", resources.getString(R.string.incoming_call_ringtone));
589 mBuilder.setVibrate(CALL_PATTERN);
590 final Uri uri = Uri.parse(ringtone);
591 try {
592 mBuilder.setSound(fixRingtoneUri(uri));
593 } catch (SecurityException e) {
594 Log.d(Config.LOGTAG, "unable to use custom notification sound " + uri.toString());
595 }
596 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
597 mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
598 }
599 mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
600 setNotificationColor(mBuilder);
601 mBuilder.setLights(LED_COLOR, 2000, 3000);
602 }
603
604 private Uri fixRingtoneUri(Uri uri) {
605 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && "file".equals(uri.getScheme())) {
606 return FileBackend.getUriForFile(mXmppConnectionService, new File(uri.getPath()));
607 } else {
608 return uri;
609 }
610 }
611
612 private Builder buildMultipleConversation(final boolean notify, final boolean quietHours) {
613 final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService, quietHours ? "quiet_hours" : (notify ? "messages" : "silent_messages"));
614 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
615 style.setBigContentTitle(mXmppConnectionService.getString(R.string.x_unread_conversations, notifications.size()));
616 final StringBuilder names = new StringBuilder();
617 Conversation conversation = null;
618 for (final ArrayList<Message> messages : notifications.values()) {
619 if (messages.size() > 0) {
620 conversation = (Conversation) messages.get(0).getConversation();
621 final String name = conversation.getName().toString();
622 SpannableString styledString;
623 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
624 int count = messages.size();
625 styledString = new SpannableString(name + ": " + mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
626 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
627 style.addLine(styledString);
628 } else {
629 styledString = new SpannableString(name + ": " + UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
630 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
631 style.addLine(styledString);
632 }
633 names.append(name);
634 names.append(", ");
635 }
636 }
637 if (names.length() >= 2) {
638 names.delete(names.length() - 2, names.length());
639 }
640 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.x_unread_conversations, notifications.size()));
641 mBuilder.setTicker(mXmppConnectionService.getString(R.string.x_unread_conversations, notifications.size()));
642 mBuilder.setContentText(names.toString());
643 mBuilder.setStyle(style);
644 if (conversation != null) {
645 mBuilder.setContentIntent(createContentIntent(conversation));
646 }
647 mBuilder.setGroupSummary(true);
648 mBuilder.setGroup(CONVERSATIONS_GROUP);
649 mBuilder.setDeleteIntent(createDeleteIntent(null));
650 mBuilder.setSmallIcon(R.drawable.ic_notification);
651 return mBuilder;
652 }
653
654 private Builder buildSingleConversations(final ArrayList<Message> messages, final boolean notify, final boolean quietHours) {
655 final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService, quietHours ? "quiet_hours" : (notify ? "messages" : "silent_messages"));
656 if (messages.size() >= 1) {
657 final Conversation conversation = (Conversation) messages.get(0).getConversation();
658 mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
659 .get(conversation, AvatarService.getSystemUiAvatarSize(mXmppConnectionService)));
660 mBuilder.setContentTitle(conversation.getName());
661 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
662 int count = messages.size();
663 mBuilder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
664 } else {
665 Message message;
666 //TODO starting with Android 9 we might want to put images in MessageStyle
667 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P && (message = getImage(messages)) != null) {
668 modifyForImage(mBuilder, message, messages);
669 } else {
670 modifyForTextOnly(mBuilder, messages);
671 }
672 RemoteInput remoteInput = new RemoteInput.Builder("text_reply").setLabel(UIHelper.getMessageHint(mXmppConnectionService, conversation)).build();
673 PendingIntent markAsReadPendingIntent = createReadPendingIntent(conversation);
674 NotificationCompat.Action markReadAction = new NotificationCompat.Action.Builder(
675 R.drawable.ic_drafts_white_24dp,
676 mXmppConnectionService.getString(R.string.mark_as_read),
677 markAsReadPendingIntent)
678 .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ)
679 .setShowsUserInterface(false)
680 .build();
681 String replyLabel = mXmppConnectionService.getString(R.string.reply);
682 NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
683 R.drawable.ic_send_text_offline,
684 replyLabel,
685 createReplyIntent(conversation, false))
686 .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY)
687 .setShowsUserInterface(false)
688 .addRemoteInput(remoteInput).build();
689 NotificationCompat.Action wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_wear_reply,
690 replyLabel,
691 createReplyIntent(conversation, true)).addRemoteInput(remoteInput).build();
692 mBuilder.extend(new NotificationCompat.WearableExtender().addAction(wearReplyAction));
693 int addedActionsCount = 1;
694 mBuilder.addAction(markReadAction);
695 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
696 mBuilder.addAction(replyAction);
697 ++addedActionsCount;
698 }
699
700 if (displaySnoozeAction(messages)) {
701 String label = mXmppConnectionService.getString(R.string.snooze);
702 PendingIntent pendingSnoozeIntent = createSnoozeIntent(conversation);
703 NotificationCompat.Action snoozeAction = new NotificationCompat.Action.Builder(
704 R.drawable.ic_notifications_paused_white_24dp,
705 label,
706 pendingSnoozeIntent).build();
707 mBuilder.addAction(snoozeAction);
708 ++addedActionsCount;
709 }
710 if (addedActionsCount < 3) {
711 final Message firstLocationMessage = getFirstLocationMessage(messages);
712 if (firstLocationMessage != null) {
713 final PendingIntent pendingShowLocationIntent = createShowLocationIntent(firstLocationMessage);
714 if (pendingShowLocationIntent != null) {
715 final String label = mXmppConnectionService.getResources().getString(R.string.show_location);
716 NotificationCompat.Action locationAction = new NotificationCompat.Action.Builder(
717 R.drawable.ic_room_white_24dp,
718 label,
719 pendingShowLocationIntent).build();
720 mBuilder.addAction(locationAction);
721 ++addedActionsCount;
722 }
723 }
724 }
725 if (addedActionsCount < 3) {
726 Message firstDownloadableMessage = getFirstDownloadableMessage(messages);
727 if (firstDownloadableMessage != null) {
728 String label = mXmppConnectionService.getResources().getString(R.string.download_x_file, UIHelper.getFileDescriptionString(mXmppConnectionService, firstDownloadableMessage));
729 PendingIntent pendingDownloadIntent = createDownloadIntent(firstDownloadableMessage);
730 NotificationCompat.Action downloadAction = new NotificationCompat.Action.Builder(
731 R.drawable.ic_file_download_white_24dp,
732 label,
733 pendingDownloadIntent).build();
734 mBuilder.addAction(downloadAction);
735 ++addedActionsCount;
736 }
737 }
738 }
739 if (conversation.getMode() == Conversation.MODE_SINGLE) {
740 Contact contact = conversation.getContact();
741 Uri systemAccount = contact.getSystemAccount();
742 if (systemAccount != null) {
743 mBuilder.addPerson(systemAccount.toString());
744 }
745 }
746 mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
747 mBuilder.setSmallIcon(R.drawable.ic_notification);
748 mBuilder.setDeleteIntent(createDeleteIntent(conversation));
749 mBuilder.setContentIntent(createContentIntent(conversation));
750 }
751 return mBuilder;
752 }
753
754 private void modifyForImage(final Builder builder, final Message message, final ArrayList<Message> messages) {
755 try {
756 final Bitmap bitmap = mXmppConnectionService.getFileBackend().getThumbnail(message, getPixel(288), false);
757 final ArrayList<Message> tmp = new ArrayList<>();
758 for (final Message msg : messages) {
759 if (msg.getType() == Message.TYPE_TEXT
760 && msg.getTransferable() == null) {
761 tmp.add(msg);
762 }
763 }
764 final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
765 bigPictureStyle.bigPicture(bitmap);
766 if (tmp.size() > 0) {
767 CharSequence text = getMergedBodies(tmp);
768 bigPictureStyle.setSummaryText(text);
769 builder.setContentText(text);
770 builder.setTicker(text);
771 } else {
772 final String description = UIHelper.getFileDescriptionString(mXmppConnectionService, message);
773 builder.setContentText(description);
774 builder.setTicker(description);
775 }
776 builder.setStyle(bigPictureStyle);
777 } catch (final IOException e) {
778 modifyForTextOnly(builder, messages);
779 }
780 }
781
782 private Person getPerson(Message message) {
783 final Contact contact = message.getContact();
784 final Person.Builder builder = new Person.Builder();
785 if (contact != null) {
786 builder.setName(contact.getDisplayName());
787 final Uri uri = contact.getSystemAccount();
788 if (uri != null) {
789 builder.setUri(uri.toString());
790 }
791 } else {
792 builder.setName(UIHelper.getMessageDisplayName(message));
793 }
794 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
795 builder.setIcon(IconCompat.createWithBitmap(mXmppConnectionService.getAvatarService().get(message, AvatarService.getSystemUiAvatarSize(mXmppConnectionService), false)));
796 }
797 return builder.build();
798 }
799
800 private void modifyForTextOnly(final Builder builder, final ArrayList<Message> messages) {
801 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
802 final Conversation conversation = (Conversation) messages.get(0).getConversation();
803 final Person.Builder meBuilder = new Person.Builder().setName(mXmppConnectionService.getString(R.string.me));
804 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
805 meBuilder.setIcon(IconCompat.createWithBitmap(mXmppConnectionService.getAvatarService().get(conversation.getAccount(), AvatarService.getSystemUiAvatarSize(mXmppConnectionService))));
806 }
807 final Person me = meBuilder.build();
808 NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(me);
809 final boolean multiple = conversation.getMode() == Conversation.MODE_MULTI;
810 if (multiple) {
811 messagingStyle.setConversationTitle(conversation.getName());
812 }
813 for (Message message : messages) {
814 final Person sender = message.getStatus() == Message.STATUS_RECEIVED ? getPerson(message) : null;
815 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && isImageMessage(message)) {
816 final Uri dataUri = FileBackend.getMediaUri(mXmppConnectionService, mXmppConnectionService.getFileBackend().getFile(message));
817 NotificationCompat.MessagingStyle.Message imageMessage = new NotificationCompat.MessagingStyle.Message(UIHelper.getMessagePreview(mXmppConnectionService, message).first, message.getTimeSent(), sender);
818 if (dataUri != null) {
819 imageMessage.setData(message.getMimeType(), dataUri);
820 }
821 messagingStyle.addMessage(imageMessage);
822 } else {
823 messagingStyle.addMessage(UIHelper.getMessagePreview(mXmppConnectionService, message).first, message.getTimeSent(), sender);
824 }
825 }
826 messagingStyle.setGroupConversation(multiple);
827 builder.setStyle(messagingStyle);
828 } else {
829 if (messages.get(0).getConversation().getMode() == Conversation.MODE_SINGLE) {
830 builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
831 final CharSequence preview = UIHelper.getMessagePreview(mXmppConnectionService, messages.get(messages.size() - 1)).first;
832 builder.setContentText(preview);
833 builder.setTicker(preview);
834 builder.setNumber(messages.size());
835 } else {
836 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
837 SpannableString styledString;
838 for (Message message : messages) {
839 final String name = UIHelper.getMessageDisplayName(message);
840 styledString = new SpannableString(name + ": " + message.getBody());
841 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
842 style.addLine(styledString);
843 }
844 builder.setStyle(style);
845 int count = messages.size();
846 if (count == 1) {
847 final String name = UIHelper.getMessageDisplayName(messages.get(0));
848 styledString = new SpannableString(name + ": " + messages.get(0).getBody());
849 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
850 builder.setContentText(styledString);
851 builder.setTicker(styledString);
852 } else {
853 final String text = mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count);
854 builder.setContentText(text);
855 builder.setTicker(text);
856 }
857 }
858 }
859 }
860
861 private Message getImage(final Iterable<Message> messages) {
862 Message image = null;
863 for (final Message message : messages) {
864 if (message.getStatus() != Message.STATUS_RECEIVED) {
865 return null;
866 }
867 if (isImageMessage(message)) {
868 image = message;
869 }
870 }
871 return image;
872 }
873
874 private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
875 for (final Message message : messages) {
876 if (message.getTransferable() != null || (message.getType() == Message.TYPE_TEXT && message.treatAsDownloadable())) {
877 return message;
878 }
879 }
880 return null;
881 }
882
883 private Message getFirstLocationMessage(final Iterable<Message> messages) {
884 for (final Message message : messages) {
885 if (message.isGeoUri()) {
886 return message;
887 }
888 }
889 return null;
890 }
891
892 private CharSequence getMergedBodies(final ArrayList<Message> messages) {
893 final StringBuilder text = new StringBuilder();
894 for (Message message : messages) {
895 if (text.length() != 0) {
896 text.append("\n");
897 }
898 text.append(UIHelper.getMessagePreview(mXmppConnectionService, message).first);
899 }
900 return text.toString();
901 }
902
903 private PendingIntent createShowLocationIntent(final Message message) {
904 Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(mXmppConnectionService, message);
905 for (Intent intent : intents) {
906 if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
907 return PendingIntent.getActivity(mXmppConnectionService, generateRequestCode(message.getConversation(), 18), intent, PendingIntent.FLAG_UPDATE_CURRENT);
908 }
909 }
910 return null;
911 }
912
913 private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
914 final Intent viewConversationIntent = new Intent(mXmppConnectionService, ConversationsActivity.class);
915 viewConversationIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
916 viewConversationIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversationUuid);
917 if (downloadMessageUuid != null) {
918 viewConversationIntent.putExtra(ConversationsActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
919 return PendingIntent.getActivity(mXmppConnectionService,
920 generateRequestCode(conversationUuid, 8),
921 viewConversationIntent,
922 PendingIntent.FLAG_UPDATE_CURRENT);
923 } else {
924 return PendingIntent.getActivity(mXmppConnectionService,
925 generateRequestCode(conversationUuid, 10),
926 viewConversationIntent,
927 PendingIntent.FLAG_UPDATE_CURRENT);
928 }
929 }
930
931 private int generateRequestCode(String uuid, int actionId) {
932 return (actionId * NOTIFICATION_ID_MULTIPLIER) + (uuid.hashCode() % NOTIFICATION_ID_MULTIPLIER);
933 }
934
935 private int generateRequestCode(Conversational conversation, int actionId) {
936 return generateRequestCode(conversation.getUuid(), actionId);
937 }
938
939 private PendingIntent createDownloadIntent(final Message message) {
940 return createContentIntent(message.getConversationUuid(), message.getUuid());
941 }
942
943 private PendingIntent createContentIntent(final Conversational conversation) {
944 return createContentIntent(conversation.getUuid(), null);
945 }
946
947 private PendingIntent createDeleteIntent(Conversation conversation) {
948 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
949 intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
950 if (conversation != null) {
951 intent.putExtra("uuid", conversation.getUuid());
952 return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 20), intent, 0);
953 }
954 return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
955 }
956
957 private PendingIntent createReplyIntent(Conversation conversation, boolean dismissAfterReply) {
958 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
959 intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
960 intent.putExtra("uuid", conversation.getUuid());
961 intent.putExtra("dismiss_notification", dismissAfterReply);
962 final int id = generateRequestCode(conversation, dismissAfterReply ? 12 : 14);
963 return PendingIntent.getService(mXmppConnectionService, id, intent, 0);
964 }
965
966 private PendingIntent createReadPendingIntent(Conversation conversation) {
967 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
968 intent.setAction(XmppConnectionService.ACTION_MARK_AS_READ);
969 intent.putExtra("uuid", conversation.getUuid());
970 intent.setPackage(mXmppConnectionService.getPackageName());
971 return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 16), intent, PendingIntent.FLAG_UPDATE_CURRENT);
972 }
973
974 private PendingIntent createCallAction(String sessionId, final String action, int requestCode) {
975 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
976 intent.setAction(action);
977 intent.setPackage(mXmppConnectionService.getPackageName());
978 intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, sessionId);
979 return PendingIntent.getService(mXmppConnectionService, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
980 }
981
982 private PendingIntent createSnoozeIntent(Conversation conversation) {
983 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
984 intent.setAction(XmppConnectionService.ACTION_SNOOZE);
985 intent.putExtra("uuid", conversation.getUuid());
986 intent.setPackage(mXmppConnectionService.getPackageName());
987 return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 22), intent, PendingIntent.FLAG_UPDATE_CURRENT);
988 }
989
990 private PendingIntent createTryAgainIntent() {
991 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
992 intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
993 return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
994 }
995
996 private PendingIntent createDismissErrorIntent() {
997 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
998 intent.setAction(XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS);
999 return PendingIntent.getService(mXmppConnectionService, 69, intent, 0);
1000 }
1001
1002 private boolean wasHighlightedOrPrivate(final Message message) {
1003 if (message.getConversation() instanceof Conversation) {
1004 Conversation conversation = (Conversation) message.getConversation();
1005 final String nick = conversation.getMucOptions().getActualNick();
1006 final Pattern highlight = generateNickHighlightPattern(nick);
1007 if (message.getBody() == null || nick == null) {
1008 return false;
1009 }
1010 final Matcher m = highlight.matcher(message.getBody());
1011 return (m.find() || message.isPrivateMessage());
1012 } else {
1013 return false;
1014 }
1015 }
1016
1017 public void setOpenConversation(final Conversation conversation) {
1018 this.mOpenConversation = conversation;
1019 }
1020
1021 public void setIsInForeground(final boolean foreground) {
1022 this.mIsInForeground = foreground;
1023 }
1024
1025 private int getPixel(final int dp) {
1026 final DisplayMetrics metrics = mXmppConnectionService.getResources()
1027 .getDisplayMetrics();
1028 return ((int) (dp * metrics.density));
1029 }
1030
1031 private void markLastNotification() {
1032 this.mLastNotification = SystemClock.elapsedRealtime();
1033 }
1034
1035 private boolean inMiniGracePeriod(final Account account) {
1036 final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
1037 : Config.MINI_GRACE_PERIOD * 2;
1038 return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
1039 }
1040
1041 Notification createForegroundNotification() {
1042 final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1043 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.app_name));
1044 final List<Account> accounts = mXmppConnectionService.getAccounts();
1045 int enabled = 0;
1046 int connected = 0;
1047 if (accounts != null) {
1048 for (Account account : accounts) {
1049 if (account.isOnlineAndConnected()) {
1050 connected++;
1051 enabled++;
1052 } else if (account.isEnabled()) {
1053 enabled++;
1054 }
1055 }
1056 }
1057 mBuilder.setContentText(mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
1058 final PendingIntent openIntent = createOpenConversationsIntent();
1059 if (openIntent != null) {
1060 mBuilder.setContentIntent(openIntent);
1061 }
1062 mBuilder.setWhen(0);
1063 mBuilder.setPriority(Notification.PRIORITY_MIN);
1064 mBuilder.setSmallIcon(connected > 0 ? R.drawable.ic_link_white_24dp : R.drawable.ic_link_off_white_24dp);
1065
1066 if (Compatibility.runsTwentySix()) {
1067 mBuilder.setChannelId("foreground");
1068 }
1069
1070
1071 return mBuilder.build();
1072 }
1073
1074 private PendingIntent createOpenConversationsIntent() {
1075 try {
1076 return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService, ConversationsActivity.class), 0);
1077 } catch (RuntimeException e) {
1078 return null;
1079 }
1080 }
1081
1082 void updateErrorNotification() {
1083 if (Config.SUPPRESS_ERROR_NOTIFICATION) {
1084 cancel(ERROR_NOTIFICATION_ID);
1085 return;
1086 }
1087 final boolean showAllErrors = QuickConversationsService.isConversations();
1088 final List<Account> errors = new ArrayList<>();
1089 for (final Account account : mXmppConnectionService.getAccounts()) {
1090 if (account.hasErrorStatus() && account.showErrorNotification() && (showAllErrors || account.getLastErrorStatus() == Account.State.UNAUTHORIZED)) {
1091 errors.add(account);
1092 }
1093 }
1094 if (mXmppConnectionService.foregroundNotificationNeedsUpdatingWhenErrorStateChanges()) {
1095 notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
1096 }
1097 final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1098 if (errors.size() == 0) {
1099 cancel(ERROR_NOTIFICATION_ID);
1100 return;
1101 } else if (errors.size() == 1) {
1102 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
1103 mBuilder.setContentText(errors.get(0).getJid().asBareJid().toString());
1104 } else {
1105 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
1106 mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
1107 }
1108 mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
1109 mXmppConnectionService.getString(R.string.try_again),
1110 createTryAgainIntent());
1111 mBuilder.setDeleteIntent(createDismissErrorIntent());
1112 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
1113 mBuilder.setVisibility(Notification.VISIBILITY_PRIVATE);
1114 mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
1115 } else {
1116 mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
1117 }
1118 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
1119 mBuilder.setLocalOnly(true);
1120 }
1121 mBuilder.setPriority(Notification.PRIORITY_LOW);
1122 final Intent intent;
1123 if (AccountUtils.MANAGE_ACCOUNT_ACTIVITY != null) {
1124 intent = new Intent(mXmppConnectionService, AccountUtils.MANAGE_ACCOUNT_ACTIVITY);
1125 } else {
1126 intent = new Intent(mXmppConnectionService, EditAccountActivity.class);
1127 intent.putExtra("jid", errors.get(0).getJid().asBareJid().toEscapedString());
1128 intent.putExtra(EditAccountActivity.EXTRA_OPENED_FROM_NOTIFICATION, true);
1129 }
1130 mBuilder.setContentIntent(PendingIntent.getActivity(mXmppConnectionService, 145, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1131 if (Compatibility.runsTwentySix()) {
1132 mBuilder.setChannelId("error");
1133 }
1134 notify(ERROR_NOTIFICATION_ID, mBuilder.build());
1135 }
1136
1137 void updateFileAddingNotification(int current, Message message) {
1138 Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1139 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.transcoding_video));
1140 mBuilder.setProgress(100, current, false);
1141 mBuilder.setSmallIcon(R.drawable.ic_hourglass_empty_white_24dp);
1142 mBuilder.setContentIntent(createContentIntent(message.getConversation()));
1143 mBuilder.setOngoing(true);
1144 if (Compatibility.runsTwentySix()) {
1145 mBuilder.setChannelId("compression");
1146 }
1147 Notification notification = mBuilder.build();
1148 notify(FOREGROUND_NOTIFICATION_ID, notification);
1149 }
1150
1151 private void notify(String tag, int id, Notification notification) {
1152 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1153 try {
1154 notificationManager.notify(tag, id, notification);
1155 } catch (RuntimeException e) {
1156 Log.d(Config.LOGTAG, "unable to make notification", e);
1157 }
1158 }
1159
1160 public void notify(int id, Notification notification) {
1161 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1162 try {
1163 notificationManager.notify(id, notification);
1164 } catch (RuntimeException e) {
1165 Log.d(Config.LOGTAG, "unable to make notification", e);
1166 }
1167 }
1168
1169 public void cancel(int id) {
1170 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1171 try {
1172 notificationManager.cancel(id);
1173 } catch (RuntimeException e) {
1174 Log.d(Config.LOGTAG, "unable to cancel notification", e);
1175 }
1176 }
1177
1178 private void cancel(String tag, int id) {
1179 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1180 try {
1181 notificationManager.cancel(tag, id);
1182 } catch (RuntimeException e) {
1183 Log.d(Config.LOGTAG, "unable to cancel notification", e);
1184 }
1185 }
1186}