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