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