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 if (mXmppConnectionService.markRead(last.getConversation(), false)) {
221 mXmppConnectionService.updateConversationUi();
222 }
223 }
224 }
225 }
226
227 private void setNotificationColor(final Builder mBuilder) {
228 mBuilder.setColor(ContextCompat.getColor(mXmppConnectionService, R.color.primary500));
229 }
230
231 public void updateNotification(final boolean notify) {
232 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
233 final SharedPreferences preferences = mXmppConnectionService.getPreferences();
234
235 if (notifications.size() == 0) {
236 notificationManager.cancel(NOTIFICATION_ID);
237 } else {
238 if (notify) {
239 this.markLastNotification();
240 }
241 final Builder mBuilder;
242 if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
243 mBuilder = buildSingleConversations(notifications.values().iterator().next());
244 modifyForSoundVibrationAndLight(mBuilder, notify, preferences);
245 notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
246 } else {
247 mBuilder = buildMultipleConversation();
248 modifyForSoundVibrationAndLight(mBuilder, notify, preferences);
249 notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
250 for(Map.Entry<String,ArrayList<Message>> entry : notifications.entrySet()) {
251 Builder singleBuilder = buildSingleConversations(entry.getValue());
252 singleBuilder.setGroup(CONVERSATIONS_GROUP);
253 modifyForSoundVibrationAndLight(singleBuilder,notify,preferences);
254 notificationManager.notify(entry.getKey(), NOTIFICATION_ID ,singleBuilder.build());
255 }
256 }
257 }
258 }
259
260
261 private void modifyForSoundVibrationAndLight(Builder mBuilder, boolean notify, SharedPreferences preferences) {
262 final String ringtone = preferences.getString("notification_ringtone", null);
263 final boolean vibrate = preferences.getBoolean("vibrate_on_notification", true);
264 final boolean led = preferences.getBoolean("led", true);
265 if (notify && !isQuietHours()) {
266 if (vibrate) {
267 final int dat = 70;
268 final long[] pattern = {0, 3 * dat, dat, dat};
269 mBuilder.setVibrate(pattern);
270 } else {
271 mBuilder.setVibrate(new long[]{0});
272 }
273 if (ringtone != null) {
274 mBuilder.setSound(Uri.parse(ringtone));
275 }
276 }
277 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
278 mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
279 }
280 mBuilder.setPriority(notify ? NotificationCompat.PRIORITY_DEFAULT : NotificationCompat.PRIORITY_LOW);
281 setNotificationColor(mBuilder);
282 mBuilder.setDefaults(0);
283 if (led) {
284 mBuilder.setLights(0xff00FF00, 2000, 3000);
285 }
286 }
287
288 private Builder buildMultipleConversation() {
289 final Builder mBuilder = new NotificationCompat.Builder(
290 mXmppConnectionService);
291 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
292 style.setBigContentTitle(notifications.size()
293 + " "
294 + mXmppConnectionService
295 .getString(R.string.unread_conversations));
296 final StringBuilder names = new StringBuilder();
297 Conversation conversation = null;
298 for (final ArrayList<Message> messages : notifications.values()) {
299 if (messages.size() > 0) {
300 conversation = messages.get(0).getConversation();
301 final String name = conversation.getName();
302 SpannableString styledString;
303 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
304 int count = messages.size();
305 styledString = new SpannableString(name + ": " + mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages,count,count));
306 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
307 style.addLine(styledString);
308 } else {
309 styledString = new SpannableString(name + ": " + UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
310 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
311 style.addLine(styledString);
312 }
313 names.append(name);
314 names.append(", ");
315 }
316 }
317 if (names.length() >= 2) {
318 names.delete(names.length() - 2, names.length());
319 }
320 mBuilder.setContentTitle(notifications.size()
321 + " "
322 + mXmppConnectionService
323 .getString(R.string.unread_conversations));
324 mBuilder.setContentText(names.toString());
325 mBuilder.setStyle(style);
326 if (conversation != null) {
327 mBuilder.setContentIntent(createContentIntent(conversation));
328 }
329 mBuilder.setGroupSummary(true);
330 mBuilder.setGroup(CONVERSATIONS_GROUP);
331 mBuilder.setDeleteIntent(createDeleteIntent(null));
332 mBuilder.setSmallIcon(R.drawable.ic_notification);
333 return mBuilder;
334 }
335
336 private Builder buildSingleConversations(final ArrayList<Message> messages) {
337 final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
338 if (messages.size() >= 1) {
339 final Conversation conversation = messages.get(0).getConversation();
340 mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
341 .get(conversation, getPixel(64)));
342 mBuilder.setContentTitle(conversation.getName());
343 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
344 int count = messages.size();
345 mBuilder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages,count,count));
346 } else {
347 Message message;
348 if ((message = getImage(messages)) != null) {
349 modifyForImage(mBuilder, message, messages);
350 } else {
351 modifyForTextOnly(mBuilder, messages);
352 }
353 RemoteInput remoteInput = new RemoteInput.Builder("text_reply").setLabel(UIHelper.getMessageHint(mXmppConnectionService, conversation)).build();
354 NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(R.drawable.ic_send_text_offline, "Reply", createReplyIntent(conversation, false)).addRemoteInput(remoteInput).build();
355 NotificationCompat.Action wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_wear_reply, "Reply", createReplyIntent(conversation, true)).addRemoteInput(remoteInput).build();
356 mBuilder.extend(new NotificationCompat.WearableExtender().addAction(wearReplyAction));
357 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
358 mBuilder.addAction(replyAction);
359 }
360 if ((message = getFirstDownloadableMessage(messages)) != null) {
361 mBuilder.addAction(
362 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ?
363 R.drawable.ic_file_download_white_24dp : R.drawable.ic_action_download,
364 mXmppConnectionService.getResources().getString(R.string.download_x_file,
365 UIHelper.getFileDescriptionString(mXmppConnectionService, message)),
366 createDownloadIntent(message)
367 );
368 }
369 if ((message = getFirstLocationMessage(messages)) != null) {
370 mBuilder.addAction(R.drawable.ic_room_white_24dp,
371 mXmppConnectionService.getString(R.string.show_location),
372 createShowLocationIntent(message));
373 }
374 }
375 if (conversation.getMode() == Conversation.MODE_SINGLE) {
376 Contact contact = conversation.getContact();
377 Uri systemAccount = contact.getSystemAccount();
378 if (systemAccount != null) {
379 mBuilder.addPerson(systemAccount.toString());
380 }
381 }
382 mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
383 mBuilder.setSmallIcon(R.drawable.ic_notification);
384 mBuilder.setDeleteIntent(createDeleteIntent(conversation));
385 mBuilder.setContentIntent(createContentIntent(conversation));
386 }
387 return mBuilder;
388 }
389
390 private void modifyForImage(final Builder builder, final Message message,
391 final ArrayList<Message> messages) {
392 try {
393 final Bitmap bitmap = mXmppConnectionService.getFileBackend()
394 .getThumbnail(message, getPixel(288), false);
395 final ArrayList<Message> tmp = new ArrayList<>();
396 for (final Message msg : messages) {
397 if (msg.getType() == Message.TYPE_TEXT
398 && msg.getTransferable() == null) {
399 tmp.add(msg);
400 }
401 }
402 final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
403 bigPictureStyle.bigPicture(bitmap);
404 if (tmp.size() > 0) {
405 CharSequence text = getMergedBodies(tmp);
406 bigPictureStyle.setSummaryText(text);
407 builder.setContentText(text);
408 } else {
409 builder.setContentText(mXmppConnectionService.getString(
410 R.string.received_x_file,
411 UIHelper.getFileDescriptionString(mXmppConnectionService, message)));
412 }
413 builder.setStyle(bigPictureStyle);
414 } catch (final FileNotFoundException e) {
415 modifyForTextOnly(builder, messages);
416 }
417 }
418
419 private void modifyForTextOnly(final Builder builder, final ArrayList<Message> messages) {
420 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
421 NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(mXmppConnectionService.getString(R.string.me));
422 Conversation conversation = messages.get(0).getConversation();
423 if (conversation.getMode() == Conversation.MODE_MULTI) {
424 messagingStyle.setConversationTitle(conversation.getName());
425 }
426 for (Message message : messages) {
427 String sender = message.getStatus() == Message.STATUS_RECEIVED ? UIHelper.getMessageDisplayName(message) : null;
428 messagingStyle.addMessage(UIHelper.getMessagePreview(mXmppConnectionService,message).first, message.getTimeSent(), sender);
429 }
430 builder.setStyle(messagingStyle);
431 } else {
432 if(messages.get(0).getConversation().getMode() == Conversation.MODE_SINGLE) {
433 builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
434 builder.setContentText(UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
435 } else {
436 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
437 SpannableString styledString;
438 for (Message message : messages) {
439 final String name = UIHelper.getMessageDisplayName(message);
440 styledString = new SpannableString(name + ": " + message.getBody());
441 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
442 style.addLine(styledString);
443 }
444 builder.setStyle(style);
445 int count = messages.size();
446 if(count == 1) {
447 final String name = UIHelper.getMessageDisplayName(messages.get(0));
448 styledString = new SpannableString(name + ": " + messages.get(0).getBody());
449 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
450 builder.setContentText(styledString);
451 } else {
452 builder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages,count,count));
453 }
454 }
455 }
456 }
457
458 private Message getImage(final Iterable<Message> messages) {
459 Message image = null;
460 for (final Message message : messages) {
461 if (message.getStatus() != Message.STATUS_RECEIVED) {
462 return null;
463 }
464 if (message.getType() != Message.TYPE_TEXT
465 && message.getTransferable() == null
466 && message.getEncryption() != Message.ENCRYPTION_PGP
467 && message.getFileParams().height > 0) {
468 image = message;
469 }
470 }
471 return image;
472 }
473
474 private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
475 for (final Message message : messages) {
476 if (message.getTransferable() != null || (message.getType() == Message.TYPE_TEXT && message.treatAsDownloadable())) {
477 return message;
478 }
479 }
480 return null;
481 }
482
483 private Message getFirstLocationMessage(final Iterable<Message> messages) {
484 for (final Message message : messages) {
485 if (GeoHelper.isGeoUri(message.getBody())) {
486 return message;
487 }
488 }
489 return null;
490 }
491
492 private CharSequence getMergedBodies(final ArrayList<Message> messages) {
493 final StringBuilder text = new StringBuilder();
494 for(Message message : messages) {
495 if (text.length() != 0) {
496 text.append("\n");
497 }
498 text.append(UIHelper.getMessagePreview(mXmppConnectionService, message).first);
499 }
500 return text.toString();
501 }
502
503 private PendingIntent createShowLocationIntent(final Message message) {
504 Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(message);
505 for (Intent intent : intents) {
506 if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
507 return PendingIntent.getActivity(mXmppConnectionService, 18, intent, PendingIntent.FLAG_UPDATE_CURRENT);
508 }
509 }
510 return createOpenConversationsIntent();
511 }
512
513 private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
514 final Intent viewConversationIntent = new Intent(mXmppConnectionService,ConversationActivity.class);
515 viewConversationIntent.setAction(ConversationActivity.ACTION_VIEW_CONVERSATION);
516 viewConversationIntent.putExtra(ConversationActivity.CONVERSATION, conversationUuid);
517 if (downloadMessageUuid != null) {
518 viewConversationIntent.putExtra(ConversationActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
519 return PendingIntent.getActivity(mXmppConnectionService,
520 conversationUuid.hashCode() % 389782,
521 viewConversationIntent,
522 PendingIntent.FLAG_UPDATE_CURRENT);
523 } else {
524 return PendingIntent.getActivity(mXmppConnectionService,
525 conversationUuid.hashCode() % 936236,
526 viewConversationIntent,
527 PendingIntent.FLAG_UPDATE_CURRENT);
528 }
529 }
530
531 private PendingIntent createDownloadIntent(final Message message) {
532 return createContentIntent(message.getConversationUuid(), message.getUuid());
533 }
534
535 private PendingIntent createContentIntent(final Conversation conversation) {
536 return createContentIntent(conversation.getUuid(), null);
537 }
538
539 private PendingIntent createDeleteIntent(Conversation conversation) {
540 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
541 intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
542 if (conversation != null) {
543 intent.putExtra("uuid", conversation.getUuid());
544 return PendingIntent.getService(mXmppConnectionService, conversation.getUuid().hashCode() % 247527, intent, 0);
545 }
546 return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
547 }
548
549 private PendingIntent createReplyIntent(Conversation conversation, boolean dismissAfterReply) {
550 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
551 intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
552 intent.putExtra("uuid",conversation.getUuid());
553 intent.putExtra("dismiss_notification",dismissAfterReply);
554 int id = conversation.getUuid().hashCode() % (dismissAfterReply ? 402359 : 426583);
555 return PendingIntent.getService(mXmppConnectionService, id, intent, 0);
556 }
557
558 private PendingIntent createDisableForeground() {
559 final Intent intent = new Intent(mXmppConnectionService,
560 XmppConnectionService.class);
561 intent.setAction(XmppConnectionService.ACTION_DISABLE_FOREGROUND);
562 return PendingIntent.getService(mXmppConnectionService, 34, intent, 0);
563 }
564
565 private PendingIntent createTryAgainIntent() {
566 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
567 intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
568 return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
569 }
570
571 private PendingIntent createDismissErrorIntent() {
572 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
573 intent.setAction(XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS);
574 return PendingIntent.getService(mXmppConnectionService, 69, intent, 0);
575 }
576
577 private boolean wasHighlightedOrPrivate(final Message message) {
578 final String nick = message.getConversation().getMucOptions().getActualNick();
579 final Pattern highlight = generateNickHighlightPattern(nick);
580 if (message.getBody() == null || nick == null) {
581 return false;
582 }
583 final Matcher m = highlight.matcher(message.getBody());
584 return (m.find() || message.getType() == Message.TYPE_PRIVATE);
585 }
586
587 public static Pattern generateNickHighlightPattern(final String nick) {
588 // We expect a word boundary, i.e. space or start of string, followed by
589 // the
590 // nick (matched in case-insensitive manner), followed by optional
591 // punctuation (for example "bob: i disagree" or "how are you alice?"),
592 // followed by another word boundary.
593 return Pattern.compile("\\b" + Pattern.quote(nick) + "\\p{Punct}?\\b",
594 Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
595 }
596
597 public void setOpenConversation(final Conversation conversation) {
598 this.mOpenConversation = conversation;
599 }
600
601 public void setIsInForeground(final boolean foreground) {
602 this.mIsInForeground = foreground;
603 }
604
605 private int getPixel(final int dp) {
606 final DisplayMetrics metrics = mXmppConnectionService.getResources()
607 .getDisplayMetrics();
608 return ((int) (dp * metrics.density));
609 }
610
611 private void markLastNotification() {
612 this.mLastNotification = SystemClock.elapsedRealtime();
613 }
614
615 private boolean inMiniGracePeriod(final Account account) {
616 final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
617 : Config.MINI_GRACE_PERIOD * 2;
618 return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
619 }
620
621 public Notification createForegroundNotification() {
622 final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
623
624 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.conversations_foreground_service));
625 if (Config.SHOW_CONNECTED_ACCOUNTS) {
626 List<Account> accounts = mXmppConnectionService.getAccounts();
627 int enabled = 0;
628 int connected = 0;
629 for (Account account : accounts) {
630 if (account.isOnlineAndConnected()) {
631 connected++;
632 enabled++;
633 } else if (!account.isOptionSet(Account.OPTION_DISABLED)) {
634 enabled++;
635 }
636 }
637 mBuilder.setContentText(mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
638 } else {
639 mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_open_conversations));
640 }
641 mBuilder.setContentIntent(createOpenConversationsIntent());
642 mBuilder.setWhen(0);
643 mBuilder.setPriority(Config.SHOW_CONNECTED_ACCOUNTS ? NotificationCompat.PRIORITY_DEFAULT : NotificationCompat.PRIORITY_MIN);
644 mBuilder.setSmallIcon(R.drawable.ic_link_white_24dp);
645 if (Config.SHOW_DISABLE_FOREGROUND) {
646 final int cancelIcon;
647 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
648 mBuilder.setCategory(Notification.CATEGORY_SERVICE);
649 cancelIcon = R.drawable.ic_cancel_white_24dp;
650 } else {
651 cancelIcon = R.drawable.ic_action_cancel;
652 }
653 mBuilder.addAction(cancelIcon,
654 mXmppConnectionService.getString(R.string.disable_foreground_service),
655 createDisableForeground());
656 }
657 return mBuilder.build();
658 }
659
660 private PendingIntent createOpenConversationsIntent() {
661 return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService, ConversationActivity.class), 0);
662 }
663
664 public void updateErrorNotification() {
665 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
666 final List<Account> errors = new ArrayList<>();
667 for (final Account account : mXmppConnectionService.getAccounts()) {
668 if (account.hasErrorStatus() && account.showErrorNotification()) {
669 errors.add(account);
670 }
671 }
672 if (mXmppConnectionService.getPreferences().getBoolean(SettingsActivity.KEEP_FOREGROUND_SERVICE, false)) {
673 notificationManager.notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
674 }
675 final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
676 if (errors.size() == 0) {
677 notificationManager.cancel(ERROR_NOTIFICATION_ID);
678 return;
679 } else if (errors.size() == 1) {
680 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
681 mBuilder.setContentText(errors.get(0).getJid().toBareJid().toString());
682 } else {
683 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
684 mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
685 }
686 mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
687 mXmppConnectionService.getString(R.string.try_again),
688 createTryAgainIntent());
689 mBuilder.setDeleteIntent(createDismissErrorIntent());
690 mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
691 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
692 mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
693 } else {
694 mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
695 }
696 mBuilder.setContentIntent(PendingIntent.getActivity(mXmppConnectionService,
697 145,
698 new Intent(mXmppConnectionService,ManageAccountActivity.class),
699 PendingIntent.FLAG_UPDATE_CURRENT));
700 notificationManager.notify(ERROR_NOTIFICATION_ID, mBuilder.build());
701 }
702}