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