1package eu.siacs.conversations.services;
2
3import android.app.Notification;
4import android.app.PendingIntent;
5import android.content.Intent;
6import android.content.SharedPreferences;
7import android.graphics.Bitmap;
8import android.net.Uri;
9import android.os.Build;
10import android.os.SystemClock;
11import android.support.v4.app.NotificationCompat;
12import android.support.v4.app.NotificationCompat.BigPictureStyle;
13import android.support.v4.app.NotificationCompat.Builder;
14import android.support.v4.app.NotificationManagerCompat;
15import android.support.v4.app.RemoteInput;
16import android.text.Html;
17import android.util.DisplayMetrics;
18import android.util.Log;
19
20import java.io.FileNotFoundException;
21import java.util.ArrayList;
22import java.util.Calendar;
23import java.util.LinkedHashMap;
24import java.util.List;
25import java.util.Map;
26import java.util.regex.Matcher;
27import java.util.regex.Pattern;
28
29import eu.siacs.conversations.Config;
30import eu.siacs.conversations.R;
31import eu.siacs.conversations.entities.Account;
32import eu.siacs.conversations.entities.Contact;
33import eu.siacs.conversations.entities.Conversation;
34import eu.siacs.conversations.entities.Message;
35import eu.siacs.conversations.ui.ConversationActivity;
36import eu.siacs.conversations.ui.ManageAccountActivity;
37import eu.siacs.conversations.ui.SettingsActivity;
38import eu.siacs.conversations.ui.TimePreference;
39import eu.siacs.conversations.utils.GeoHelper;
40import eu.siacs.conversations.utils.UIHelper;
41
42public class NotificationService {
43
44 private static final String CONVERSATIONS_GROUP = "eu.siacs.conversations";
45 private final XmppConnectionService mXmppConnectionService;
46
47 private final LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<>();
48
49 public static final int NOTIFICATION_ID = 0x2342;
50 public static final int FOREGROUND_NOTIFICATION_ID = 0x8899;
51 public static final int ERROR_NOTIFICATION_ID = 0x5678;
52
53 private Conversation mOpenConversation;
54 private boolean mIsInForeground;
55 private long mLastNotification;
56
57 public NotificationService(final XmppConnectionService service) {
58 this.mXmppConnectionService = service;
59 }
60
61 public boolean notify(final Message message) {
62 return message.getStatus() == Message.STATUS_RECEIVED
63 && notificationsEnabled()
64 && !message.getConversation().isMuted()
65 && (message.getConversation().alwaysNotify() || wasHighlightedOrPrivate(message))
66 && (!message.getConversation().isWithStranger() || notificationsFromStrangers())
67 ;
68 }
69
70 public boolean notificationsEnabled() {
71 return mXmppConnectionService.getPreferences().getBoolean("show_notification", true);
72 }
73
74 private boolean notificationsFromStrangers() {
75 return mXmppConnectionService.getPreferences().getBoolean("notifications_from_strangers",
76 mXmppConnectionService.getResources().getBoolean(R.bool.notifications_from_strangers));
77 }
78
79 public boolean isQuietHours() {
80 if (!mXmppConnectionService.getPreferences().getBoolean("enable_quiet_hours", false)) {
81 return false;
82 }
83 final long startTime = mXmppConnectionService.getPreferences().getLong("quiet_hours_start", TimePreference.DEFAULT_VALUE) % Config.MILLISECONDS_IN_DAY;
84 final long endTime = mXmppConnectionService.getPreferences().getLong("quiet_hours_end", TimePreference.DEFAULT_VALUE) % Config.MILLISECONDS_IN_DAY;
85 final long nowTime = Calendar.getInstance().getTimeInMillis() % Config.MILLISECONDS_IN_DAY;
86
87 if (endTime < startTime) {
88 return nowTime > startTime || nowTime < endTime;
89 } else {
90 return nowTime > startTime && nowTime < endTime;
91 }
92 }
93
94 public void pushFromBacklog(final Message message) {
95 if (notify(message)) {
96 synchronized (notifications) {
97 pushToStack(message);
98 }
99 }
100 }
101
102 public void pushFromDirectReply(final Message message) {
103 synchronized (notifications) {
104 pushToStack(message);
105 updateNotification(false);
106 }
107 }
108
109 public void finishBacklog(boolean notify, Account account) {
110 synchronized (notifications) {
111 mXmppConnectionService.updateUnreadCountBadge();
112 if (account == null || !notify) {
113 updateNotification(notify);
114 } else {
115 boolean hasPendingMessages = false;
116 for(ArrayList<Message> messages : notifications.values()) {
117 if (messages.size() > 0 && messages.get(0).getConversation().getAccount() == account) {
118 hasPendingMessages = true;
119 break;
120 }
121 }
122 updateNotification(hasPendingMessages);
123 }
124 }
125 }
126
127 public void finishBacklog(boolean notify) {
128 finishBacklog(notify,null);
129 }
130
131 private void pushToStack(final Message message) {
132 final String conversationUuid = message.getConversationUuid();
133 if (notifications.containsKey(conversationUuid)) {
134 notifications.get(conversationUuid).add(message);
135 } else {
136 final ArrayList<Message> mList = new ArrayList<>();
137 mList.add(message);
138 notifications.put(conversationUuid, mList);
139 }
140 }
141
142 public void push(final Message message) {
143 mXmppConnectionService.updateUnreadCountBadge();
144 if (!notify(message)) {
145 Log.d(Config.LOGTAG,message.getConversation().getAccount().getJid().toBareJid()+": suppressing notification because turned off");
146 return;
147 }
148 final boolean isScreenOn = mXmppConnectionService.isInteractive();
149 if (this.mIsInForeground && isScreenOn && this.mOpenConversation == message.getConversation()) {
150 Log.d(Config.LOGTAG,message.getConversation().getAccount().getJid().toBareJid()+": suppressing notification because conversation is open");
151 return;
152 }
153 synchronized (notifications) {
154 pushToStack(message);
155 final Account account = message.getConversation().getAccount();
156 final boolean doNotify = (!(this.mIsInForeground && this.mOpenConversation == null) || !isScreenOn)
157 && !account.inGracePeriod()
158 && !this.inMiniGracePeriod(account);
159 updateNotification(doNotify);
160 }
161 }
162
163 public void clear() {
164 synchronized (notifications) {
165 for(ArrayList<Message> messages : notifications.values()) {
166 markAsReadIfHasDirectReply(messages);
167 }
168 notifications.clear();
169 updateNotification(false);
170 }
171 }
172
173 public void clear(final Conversation conversation) {
174 synchronized (notifications) {
175 markAsReadIfHasDirectReply(conversation);
176 notifications.remove(conversation.getUuid());
177 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
178 notificationManager.cancel(conversation.getUuid(), NOTIFICATION_ID);
179 updateNotification(false);
180 }
181 }
182
183 private void markAsReadIfHasDirectReply(final Conversation conversation) {
184 markAsReadIfHasDirectReply(notifications.get(conversation.getUuid()));
185 }
186
187 private void markAsReadIfHasDirectReply(final ArrayList<Message> messages) {
188 if (messages != null && messages.size() > 0) {
189 Message last = messages.get(messages.size() - 1);
190 if (last.getStatus() != Message.STATUS_RECEIVED) {
191 mXmppConnectionService.markRead(last.getConversation(), false);
192 }
193 }
194 }
195
196 private void setNotificationColor(final Builder mBuilder) {
197 mBuilder.setColor(mXmppConnectionService.getResources().getColor(R.color.primary500));
198 }
199
200 public void updateNotification(final boolean notify) {
201 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
202 final SharedPreferences preferences = mXmppConnectionService.getPreferences();
203
204 if (notifications.size() == 0) {
205 notificationManager.cancel(NOTIFICATION_ID);
206 } else {
207 if (notify) {
208 this.markLastNotification();
209 }
210 final Builder mBuilder;
211 if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
212 mBuilder = buildSingleConversations(notifications.values().iterator().next());
213 modifyForSoundVibrationAndLight(mBuilder, notify, preferences);
214 notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
215 } else {
216 mBuilder = buildMultipleConversation();
217 modifyForSoundVibrationAndLight(mBuilder, notify, preferences);
218 notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
219 for(Map.Entry<String,ArrayList<Message>> entry : notifications.entrySet()) {
220 Builder singleBuilder = buildSingleConversations(entry.getValue());
221 singleBuilder.setGroup(CONVERSATIONS_GROUP);
222 modifyForSoundVibrationAndLight(singleBuilder,notify,preferences);
223 notificationManager.notify(entry.getKey(), NOTIFICATION_ID ,singleBuilder.build());
224 }
225 }
226 }
227 }
228
229
230 private void modifyForSoundVibrationAndLight(Builder mBuilder, boolean notify, SharedPreferences preferences) {
231 final String ringtone = preferences.getString("notification_ringtone", null);
232 final boolean vibrate = preferences.getBoolean("vibrate_on_notification", true);
233 final boolean led = preferences.getBoolean("led", true);
234 if (notify && !isQuietHours()) {
235 if (vibrate) {
236 final int dat = 70;
237 final long[] pattern = {0, 3 * dat, dat, dat};
238 mBuilder.setVibrate(pattern);
239 } else {
240 mBuilder.setVibrate(new long[]{0});
241 }
242 if (ringtone != null) {
243 mBuilder.setSound(Uri.parse(ringtone));
244 }
245 }
246 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
247 mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
248 }
249 mBuilder.setPriority(notify ? NotificationCompat.PRIORITY_DEFAULT : NotificationCompat.PRIORITY_LOW);
250 setNotificationColor(mBuilder);
251 mBuilder.setDefaults(0);
252 if (led) {
253 mBuilder.setLights(0xff00FF00, 2000, 3000);
254 }
255 }
256
257 private Builder buildMultipleConversation() {
258 final Builder mBuilder = new NotificationCompat.Builder(
259 mXmppConnectionService);
260 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
261 style.setBigContentTitle(notifications.size()
262 + " "
263 + mXmppConnectionService
264 .getString(R.string.unread_conversations));
265 final StringBuilder names = new StringBuilder();
266 Conversation conversation = null;
267 for (final ArrayList<Message> messages : notifications.values()) {
268 if (messages.size() > 0) {
269 conversation = messages.get(0).getConversation();
270 final String name = conversation.getName();
271 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
272 int count = messages.size();
273 style.addLine(Html.fromHtml("<b>"+name+"</b>: "+mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages,count,count)));
274 } else {
275 style.addLine(Html.fromHtml("<b>" + name + "</b>: "
276 + UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first));
277 }
278 names.append(name);
279 names.append(", ");
280 }
281 }
282 if (names.length() >= 2) {
283 names.delete(names.length() - 2, names.length());
284 }
285 mBuilder.setContentTitle(notifications.size()
286 + " "
287 + mXmppConnectionService
288 .getString(R.string.unread_conversations));
289 mBuilder.setContentText(names.toString());
290 mBuilder.setStyle(style);
291 if (conversation != null) {
292 mBuilder.setContentIntent(createContentIntent(conversation));
293 }
294 mBuilder.setGroupSummary(true);
295 mBuilder.setGroup(CONVERSATIONS_GROUP);
296 mBuilder.setDeleteIntent(createDeleteIntent(null));
297 mBuilder.setSmallIcon(R.drawable.ic_notification);
298 return mBuilder;
299 }
300
301 private Builder buildSingleConversations(final ArrayList<Message> messages) {
302 final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
303 if (messages.size() >= 1) {
304 final Conversation conversation = messages.get(0).getConversation();
305 mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
306 .get(conversation, getPixel(64)));
307 mBuilder.setContentTitle(conversation.getName());
308 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
309 int count = messages.size();
310 mBuilder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages,count,count));
311 } else {
312 Message message;
313 if ((message = getImage(messages)) != null) {
314 modifyForImage(mBuilder, message, messages);
315 } else {
316 modifyForTextOnly(mBuilder, messages);
317 }
318 RemoteInput remoteInput = new RemoteInput.Builder("text_reply").setLabel(UIHelper.getMessageHint(mXmppConnectionService, conversation)).build();
319 NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(R.drawable.ic_send_text_offline, "Reply", createReplyIntent(conversation, false)).addRemoteInput(remoteInput).build();
320 NotificationCompat.Action wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_send_text_offline, "Reply", createReplyIntent(conversation, true)).addRemoteInput(remoteInput).build();
321 mBuilder.extend(new NotificationCompat.WearableExtender().addAction(wearReplyAction));
322 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
323 mBuilder.addAction(replyAction);
324 }
325 if ((message = getFirstDownloadableMessage(messages)) != null) {
326 mBuilder.addAction(
327 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ?
328 R.drawable.ic_file_download_white_24dp : R.drawable.ic_action_download,
329 mXmppConnectionService.getResources().getString(R.string.download_x_file,
330 UIHelper.getFileDescriptionString(mXmppConnectionService, message)),
331 createDownloadIntent(message)
332 );
333 }
334 if ((message = getFirstLocationMessage(messages)) != null) {
335 mBuilder.addAction(R.drawable.ic_room_white_24dp,
336 mXmppConnectionService.getString(R.string.show_location),
337 createShowLocationIntent(message));
338 }
339 }
340 if (conversation.getMode() == Conversation.MODE_SINGLE) {
341 Contact contact = conversation.getContact();
342 Uri systemAccount = contact.getSystemAccount();
343 if (systemAccount != null) {
344 mBuilder.addPerson(systemAccount.toString());
345 }
346 }
347 mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
348 mBuilder.setSmallIcon(R.drawable.ic_notification);
349 mBuilder.setDeleteIntent(createDeleteIntent(conversation));
350 mBuilder.setContentIntent(createContentIntent(conversation));
351 }
352 return mBuilder;
353 }
354
355 private void modifyForImage(final Builder builder, final Message message,
356 final ArrayList<Message> messages) {
357 try {
358 final Bitmap bitmap = mXmppConnectionService.getFileBackend()
359 .getThumbnail(message, getPixel(288), false);
360 final ArrayList<Message> tmp = new ArrayList<>();
361 for (final Message msg : messages) {
362 if (msg.getType() == Message.TYPE_TEXT
363 && msg.getTransferable() == null) {
364 tmp.add(msg);
365 }
366 }
367 final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
368 bigPictureStyle.bigPicture(bitmap);
369 if (tmp.size() > 0) {
370 CharSequence text = getMergedBodies(tmp);
371 bigPictureStyle.setSummaryText(text);
372 builder.setContentText(text);
373 } else {
374 builder.setContentText(mXmppConnectionService.getString(
375 R.string.received_x_file,
376 UIHelper.getFileDescriptionString(mXmppConnectionService, message)));
377 }
378 builder.setStyle(bigPictureStyle);
379 } catch (final FileNotFoundException e) {
380 modifyForTextOnly(builder, messages);
381 }
382 }
383
384 private void modifyForTextOnly(final Builder builder, final ArrayList<Message> messages) {
385 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
386 NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(mXmppConnectionService.getString(R.string.me));
387 Conversation conversation = messages.get(0).getConversation();
388 if (conversation.getMode() == Conversation.MODE_MULTI) {
389 messagingStyle.setConversationTitle(conversation.getName());
390 }
391 for (Message message : messages) {
392 String sender = message.getStatus() == Message.STATUS_RECEIVED ? UIHelper.getMessageDisplayName(message) : null;
393 messagingStyle.addMessage(UIHelper.getMessagePreview(mXmppConnectionService,message).first, message.getTimeSent(), sender);
394 }
395 builder.setStyle(messagingStyle);
396 } else {
397 builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
398 builder.setContentText(UIHelper.getMessagePreview(mXmppConnectionService, messages.get((messages.size()-1))).first);
399 }
400 }
401
402 private Message getImage(final Iterable<Message> messages) {
403 Message image = null;
404 for (final Message message : messages) {
405 if (message.getStatus() != Message.STATUS_RECEIVED) {
406 return null;
407 }
408 if (message.getType() != Message.TYPE_TEXT
409 && message.getTransferable() == null
410 && message.getEncryption() != Message.ENCRYPTION_PGP
411 && message.getFileParams().height > 0) {
412 image = message;
413 }
414 }
415 return image;
416 }
417
418 private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
419 for (final Message message : messages) {
420 if (message.getTransferable() != null
421 && (message.getType() == Message.TYPE_FILE
422 || message.getType() == Message.TYPE_IMAGE
423 || message.treatAsDownloadable() != Message.Decision.NEVER)) {
424 return message;
425 }
426 }
427 return null;
428 }
429
430 private Message getFirstLocationMessage(final Iterable<Message> messages) {
431 for (final Message message : messages) {
432 if (GeoHelper.isGeoUri(message.getBody())) {
433 return message;
434 }
435 }
436 return null;
437 }
438
439 private CharSequence getMergedBodies(final ArrayList<Message> messages) {
440 final StringBuilder text = new StringBuilder();
441 for (int i = 0; i < messages.size(); ++i) {
442 text.append(UIHelper.getMessagePreview(mXmppConnectionService, messages.get(i)).first);
443 if (i != messages.size() - 1) {
444 text.append("\n");
445 }
446 }
447 return text.toString();
448 }
449
450 private PendingIntent createShowLocationIntent(final Message message) {
451 Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(message);
452 for (Intent intent : intents) {
453 if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
454 return PendingIntent.getActivity(mXmppConnectionService, 18, intent, PendingIntent.FLAG_UPDATE_CURRENT);
455 }
456 }
457 return createOpenConversationsIntent();
458 }
459
460 private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
461 final Intent viewConversationIntent = new Intent(mXmppConnectionService,ConversationActivity.class);
462 viewConversationIntent.setAction(ConversationActivity.ACTION_VIEW_CONVERSATION);
463 viewConversationIntent.putExtra(ConversationActivity.CONVERSATION, conversationUuid);
464 if (downloadMessageUuid != null) {
465 viewConversationIntent.putExtra(ConversationActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
466 return PendingIntent.getActivity(mXmppConnectionService,
467 conversationUuid.hashCode() % 389782,
468 viewConversationIntent,
469 PendingIntent.FLAG_UPDATE_CURRENT);
470 } else {
471 return PendingIntent.getActivity(mXmppConnectionService,
472 conversationUuid.hashCode() % 936236,
473 viewConversationIntent,
474 PendingIntent.FLAG_UPDATE_CURRENT);
475 }
476 }
477
478 private PendingIntent createDownloadIntent(final Message message) {
479 return createContentIntent(message.getConversationUuid(), message.getUuid());
480 }
481
482 private PendingIntent createContentIntent(final Conversation conversation) {
483 return createContentIntent(conversation.getUuid(), null);
484 }
485
486 private PendingIntent createDeleteIntent(Conversation conversation) {
487 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
488 intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
489 if (conversation != null) {
490 intent.putExtra("uuid", conversation.getUuid());
491 return PendingIntent.getService(mXmppConnectionService, conversation.getUuid().hashCode() % 247527, intent, 0);
492 }
493 return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
494 }
495
496 private PendingIntent createReplyIntent(Conversation conversation, boolean dismissAfterReply) {
497 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
498 intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
499 intent.putExtra("uuid",conversation.getUuid());
500 intent.putExtra("dismiss_notification",dismissAfterReply);
501 int id = conversation.getUuid().hashCode() % (dismissAfterReply ? 402359 : 426583);
502 return PendingIntent.getService(mXmppConnectionService, id, intent, 0);
503 }
504
505 private PendingIntent createDisableForeground() {
506 final Intent intent = new Intent(mXmppConnectionService,
507 XmppConnectionService.class);
508 intent.setAction(XmppConnectionService.ACTION_DISABLE_FOREGROUND);
509 return PendingIntent.getService(mXmppConnectionService, 34, intent, 0);
510 }
511
512 private PendingIntent createTryAgainIntent() {
513 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
514 intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
515 return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
516 }
517
518 private PendingIntent createDismissErrorIntent() {
519 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
520 intent.setAction(XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS);
521 return PendingIntent.getService(mXmppConnectionService, 69, intent, 0);
522 }
523
524 private boolean wasHighlightedOrPrivate(final Message message) {
525 final String nick = message.getConversation().getMucOptions().getActualNick();
526 final Pattern highlight = generateNickHighlightPattern(nick);
527 if (message.getBody() == null || nick == null) {
528 return false;
529 }
530 final Matcher m = highlight.matcher(message.getBody());
531 return (m.find() || message.getType() == Message.TYPE_PRIVATE);
532 }
533
534 public static Pattern generateNickHighlightPattern(final String nick) {
535 // We expect a word boundary, i.e. space or start of string, followed by
536 // the
537 // nick (matched in case-insensitive manner), followed by optional
538 // punctuation (for example "bob: i disagree" or "how are you alice?"),
539 // followed by another word boundary.
540 return Pattern.compile("\\b" + Pattern.quote(nick) + "\\p{Punct}?\\b",
541 Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
542 }
543
544 public void setOpenConversation(final Conversation conversation) {
545 this.mOpenConversation = conversation;
546 }
547
548 public void setIsInForeground(final boolean foreground) {
549 this.mIsInForeground = foreground;
550 }
551
552 private int getPixel(final int dp) {
553 final DisplayMetrics metrics = mXmppConnectionService.getResources()
554 .getDisplayMetrics();
555 return ((int) (dp * metrics.density));
556 }
557
558 private void markLastNotification() {
559 this.mLastNotification = SystemClock.elapsedRealtime();
560 }
561
562 private boolean inMiniGracePeriod(final Account account) {
563 final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
564 : Config.MINI_GRACE_PERIOD * 2;
565 return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
566 }
567
568 public Notification createForegroundNotification() {
569 final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
570
571 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.conversations_foreground_service));
572 if (Config.SHOW_CONNECTED_ACCOUNTS) {
573 List<Account> accounts = mXmppConnectionService.getAccounts();
574 int enabled = 0;
575 int connected = 0;
576 for (Account account : accounts) {
577 if (account.isOnlineAndConnected()) {
578 connected++;
579 enabled++;
580 } else if (!account.isOptionSet(Account.OPTION_DISABLED)) {
581 enabled++;
582 }
583 }
584 mBuilder.setContentText(mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
585 } else {
586 mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_open_conversations));
587 }
588 mBuilder.setContentIntent(createOpenConversationsIntent());
589 mBuilder.setWhen(0);
590 mBuilder.setPriority(Config.SHOW_CONNECTED_ACCOUNTS ? NotificationCompat.PRIORITY_DEFAULT : NotificationCompat.PRIORITY_MIN);
591 mBuilder.setSmallIcon(R.drawable.ic_link_white_24dp);
592 if (Config.SHOW_DISABLE_FOREGROUND) {
593 final int cancelIcon;
594 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
595 mBuilder.setCategory(Notification.CATEGORY_SERVICE);
596 cancelIcon = R.drawable.ic_cancel_white_24dp;
597 } else {
598 cancelIcon = R.drawable.ic_action_cancel;
599 }
600 mBuilder.addAction(cancelIcon,
601 mXmppConnectionService.getString(R.string.disable_foreground_service),
602 createDisableForeground());
603 }
604 return mBuilder.build();
605 }
606
607 private PendingIntent createOpenConversationsIntent() {
608 return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService, ConversationActivity.class), 0);
609 }
610
611 public void updateErrorNotification() {
612 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
613 final List<Account> errors = new ArrayList<>();
614 for (final Account account : mXmppConnectionService.getAccounts()) {
615 if (account.hasErrorStatus() && account.showErrorNotification()) {
616 errors.add(account);
617 }
618 }
619 if (mXmppConnectionService.getPreferences().getBoolean(SettingsActivity.KEEP_FOREGROUND_SERVICE, false)) {
620 notificationManager.notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
621 }
622 final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
623 if (errors.size() == 0) {
624 notificationManager.cancel(ERROR_NOTIFICATION_ID);
625 return;
626 } else if (errors.size() == 1) {
627 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
628 mBuilder.setContentText(errors.get(0).getJid().toBareJid().toString());
629 } else {
630 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
631 mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
632 }
633 mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
634 mXmppConnectionService.getString(R.string.try_again),
635 createTryAgainIntent());
636 mBuilder.setDeleteIntent(createDismissErrorIntent());
637 mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
638 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
639 mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
640 } else {
641 mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
642 }
643 mBuilder.setContentIntent(PendingIntent.getActivity(mXmppConnectionService,
644 145,
645 new Intent(mXmppConnectionService,ManageAccountActivity.class),
646 PendingIntent.FLAG_UPDATE_CURRENT));
647 notificationManager.notify(ERROR_NOTIFICATION_ID, mBuilder.build());
648 }
649}