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