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