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