NotificationService.java

  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			} else {
408				final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
409				SpannableString styledString;
410				for (Message message : messages) {
411					final String name = UIHelper.getMessageDisplayName(message);
412					styledString = new SpannableString(name + ": " + message.getBody());
413					styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
414					style.addLine(styledString);
415				}
416				builder.setStyle(style);
417				int count = messages.size();
418				if(count == 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				} else {
424					builder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages,count,count));
425				}
426			}
427		}
428	}
429
430	private Message getImage(final Iterable<Message> messages) {
431		Message image = null;
432		for (final Message message : messages) {
433			if (message.getStatus() != Message.STATUS_RECEIVED) {
434				return null;
435			}
436			if (message.getType() != Message.TYPE_TEXT
437					&& message.getTransferable() == null
438					&& message.getEncryption() != Message.ENCRYPTION_PGP
439					&& message.getFileParams().height > 0) {
440				image = message;
441			}
442		}
443		return image;
444	}
445
446	private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
447		for (final Message message : messages) {
448			if (message.getTransferable() != null
449					&& (message.getType() == Message.TYPE_FILE
450							|| message.getType() == Message.TYPE_IMAGE
451							|| message.treatAsDownloadable() != Message.Decision.NEVER)) {
452				return message;
453			}
454		}
455		return null;
456	}
457
458	private Message getFirstLocationMessage(final Iterable<Message> messages) {
459		for (final Message message : messages) {
460			if (GeoHelper.isGeoUri(message.getBody())) {
461				return message;
462			}
463		}
464		return null;
465	}
466
467	private CharSequence getMergedBodies(final ArrayList<Message> messages) {
468		final StringBuilder text = new StringBuilder();
469		for (int i = 0; i < messages.size(); ++i) {
470			text.append(UIHelper.getMessagePreview(mXmppConnectionService, messages.get(i)).first);
471			if (i != messages.size() - 1) {
472				text.append("\n");
473			}
474		}
475		return text.toString();
476	}
477
478	private PendingIntent createShowLocationIntent(final Message message) {
479		Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(message);
480		for (Intent intent : intents) {
481			if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
482				return PendingIntent.getActivity(mXmppConnectionService, 18, intent, PendingIntent.FLAG_UPDATE_CURRENT);
483			}
484		}
485		return createOpenConversationsIntent();
486	}
487
488	private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
489		final Intent viewConversationIntent = new Intent(mXmppConnectionService,ConversationActivity.class);
490		viewConversationIntent.setAction(ConversationActivity.ACTION_VIEW_CONVERSATION);
491		viewConversationIntent.putExtra(ConversationActivity.CONVERSATION, conversationUuid);
492		if (downloadMessageUuid != null) {
493			viewConversationIntent.putExtra(ConversationActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
494			return PendingIntent.getActivity(mXmppConnectionService,
495					conversationUuid.hashCode() % 389782,
496					viewConversationIntent,
497					PendingIntent.FLAG_UPDATE_CURRENT);
498		} else {
499			return PendingIntent.getActivity(mXmppConnectionService,
500					conversationUuid.hashCode() % 936236,
501					viewConversationIntent,
502					PendingIntent.FLAG_UPDATE_CURRENT);
503		}
504	}
505
506	private PendingIntent createDownloadIntent(final Message message) {
507		return createContentIntent(message.getConversationUuid(), message.getUuid());
508	}
509
510	private PendingIntent createContentIntent(final Conversation conversation) {
511		return createContentIntent(conversation.getUuid(), null);
512	}
513
514	private PendingIntent createDeleteIntent(Conversation conversation) {
515		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
516		intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
517		if (conversation != null) {
518			intent.putExtra("uuid", conversation.getUuid());
519			return PendingIntent.getService(mXmppConnectionService, conversation.getUuid().hashCode() % 247527, intent, 0);
520		}
521		return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
522	}
523
524	private PendingIntent createReplyIntent(Conversation conversation, boolean dismissAfterReply) {
525		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
526		intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
527		intent.putExtra("uuid",conversation.getUuid());
528		intent.putExtra("dismiss_notification",dismissAfterReply);
529		int id =  conversation.getUuid().hashCode() % (dismissAfterReply ? 402359 : 426583);
530		return PendingIntent.getService(mXmppConnectionService, id, intent, 0);
531	}
532
533	private PendingIntent createDisableForeground() {
534		final Intent intent = new Intent(mXmppConnectionService,
535				XmppConnectionService.class);
536		intent.setAction(XmppConnectionService.ACTION_DISABLE_FOREGROUND);
537		return PendingIntent.getService(mXmppConnectionService, 34, intent, 0);
538	}
539
540	private PendingIntent createTryAgainIntent() {
541		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
542		intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
543		return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
544	}
545
546	private PendingIntent createDismissErrorIntent() {
547		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
548		intent.setAction(XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS);
549		return PendingIntent.getService(mXmppConnectionService, 69, intent, 0);
550	}
551
552	private boolean wasHighlightedOrPrivate(final Message message) {
553		final String nick = message.getConversation().getMucOptions().getActualNick();
554		final Pattern highlight = generateNickHighlightPattern(nick);
555		if (message.getBody() == null || nick == null) {
556			return false;
557		}
558		final Matcher m = highlight.matcher(message.getBody());
559		return (m.find() || message.getType() == Message.TYPE_PRIVATE);
560	}
561
562	public static Pattern generateNickHighlightPattern(final String nick) {
563		// We expect a word boundary, i.e. space or start of string, followed by
564		// the
565		// nick (matched in case-insensitive manner), followed by optional
566		// punctuation (for example "bob: i disagree" or "how are you alice?"),
567		// followed by another word boundary.
568		return Pattern.compile("\\b" + Pattern.quote(nick) + "\\p{Punct}?\\b",
569				Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
570	}
571
572	public void setOpenConversation(final Conversation conversation) {
573		this.mOpenConversation = conversation;
574	}
575
576	public void setIsInForeground(final boolean foreground) {
577		this.mIsInForeground = foreground;
578	}
579
580	private int getPixel(final int dp) {
581		final DisplayMetrics metrics = mXmppConnectionService.getResources()
582				.getDisplayMetrics();
583		return ((int) (dp * metrics.density));
584	}
585
586	private void markLastNotification() {
587		this.mLastNotification = SystemClock.elapsedRealtime();
588	}
589
590	private boolean inMiniGracePeriod(final Account account) {
591		final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
592				: Config.MINI_GRACE_PERIOD * 2;
593		return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
594	}
595
596	public Notification createForegroundNotification() {
597		final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
598
599		mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.conversations_foreground_service));
600		if (Config.SHOW_CONNECTED_ACCOUNTS) {
601			List<Account> accounts = mXmppConnectionService.getAccounts();
602			int enabled = 0;
603			int connected = 0;
604			for (Account account : accounts) {
605				if (account.isOnlineAndConnected()) {
606					connected++;
607					enabled++;
608				} else if (!account.isOptionSet(Account.OPTION_DISABLED)) {
609					enabled++;
610				}
611			}
612			mBuilder.setContentText(mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
613		} else {
614			mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_open_conversations));
615		}
616		mBuilder.setContentIntent(createOpenConversationsIntent());
617		mBuilder.setWhen(0);
618		mBuilder.setPriority(Config.SHOW_CONNECTED_ACCOUNTS ? NotificationCompat.PRIORITY_DEFAULT : NotificationCompat.PRIORITY_MIN);
619		mBuilder.setSmallIcon(R.drawable.ic_link_white_24dp);
620		if (Config.SHOW_DISABLE_FOREGROUND) {
621			final int cancelIcon;
622			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
623				mBuilder.setCategory(Notification.CATEGORY_SERVICE);
624				cancelIcon = R.drawable.ic_cancel_white_24dp;
625			} else {
626				cancelIcon = R.drawable.ic_action_cancel;
627			}
628			mBuilder.addAction(cancelIcon,
629					mXmppConnectionService.getString(R.string.disable_foreground_service),
630					createDisableForeground());
631		}
632		return mBuilder.build();
633	}
634
635	private PendingIntent createOpenConversationsIntent() {
636		return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService, ConversationActivity.class), 0);
637	}
638
639	public void updateErrorNotification() {
640		final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
641		final List<Account> errors = new ArrayList<>();
642		for (final Account account : mXmppConnectionService.getAccounts()) {
643			if (account.hasErrorStatus() && account.showErrorNotification()) {
644				errors.add(account);
645			}
646		}
647		if (mXmppConnectionService.getPreferences().getBoolean(SettingsActivity.KEEP_FOREGROUND_SERVICE, false)) {
648			notificationManager.notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
649		}
650		final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
651		if (errors.size() == 0) {
652			notificationManager.cancel(ERROR_NOTIFICATION_ID);
653			return;
654		} else if (errors.size() == 1) {
655			mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
656			mBuilder.setContentText(errors.get(0).getJid().toBareJid().toString());
657		} else {
658			mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
659			mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
660		}
661		mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
662				mXmppConnectionService.getString(R.string.try_again),
663				createTryAgainIntent());
664		mBuilder.setDeleteIntent(createDismissErrorIntent());
665		mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
666		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
667			mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
668		} else {
669			mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
670		}
671		mBuilder.setContentIntent(PendingIntent.getActivity(mXmppConnectionService,
672				145,
673				new Intent(mXmppConnectionService,ManageAccountActivity.class),
674				PendingIntent.FLAG_UPDATE_CURRENT));
675		notificationManager.notify(ERROR_NOTIFICATION_ID, mBuilder.build());
676	}
677}