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