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