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