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