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