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				cancel(conversation.getUuid(), NOTIFICATION_ID);
229				updateNotification(false, true);
230			}
231		}
232	}
233
234	private void markAsReadIfHasDirectReply(final Conversation conversation) {
235		markAsReadIfHasDirectReply(notifications.get(conversation.getUuid()));
236	}
237
238	private void markAsReadIfHasDirectReply(final ArrayList<Message> messages) {
239		if (messages != null && messages.size() > 0) {
240			Message last = messages.get(messages.size() - 1);
241			if (last.getStatus() != Message.STATUS_RECEIVED) {
242				if (mXmppConnectionService.markRead(last.getConversation(), false)) {
243					mXmppConnectionService.updateConversationUi();
244				}
245			}
246		}
247	}
248
249	private void setNotificationColor(final Builder mBuilder) {
250		mBuilder.setColor(ContextCompat.getColor(mXmppConnectionService, R.color.primary500));
251	}
252
253	public void updateNotification(final boolean notify) {
254		updateNotification(notify, false);
255	}
256
257	public void updateNotification(final boolean notify, boolean summaryOnly) {
258		final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
259
260		if (notifications.size() == 0) {
261			cancel(NOTIFICATION_ID);
262		} else {
263			if (notify) {
264				this.markLastNotification();
265			}
266			final Builder mBuilder;
267			if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
268				mBuilder = buildSingleConversations(notifications.values().iterator().next());
269				modifyForSoundVibrationAndLight(mBuilder, notify, preferences);
270				notify(NOTIFICATION_ID, mBuilder.build());
271			} else {
272				mBuilder = buildMultipleConversation();
273				modifyForSoundVibrationAndLight(mBuilder, notify, preferences);
274				if (!summaryOnly) {
275					for (Map.Entry<String, ArrayList<Message>> entry : notifications.entrySet()) {
276						Builder singleBuilder = buildSingleConversations(entry.getValue());
277						singleBuilder.setGroup(CONVERSATIONS_GROUP);
278						setNotificationColor(singleBuilder);
279						notify(entry.getKey(), NOTIFICATION_ID, singleBuilder.build());
280					}
281				}
282				notify(NOTIFICATION_ID, mBuilder.build());
283			}
284		}
285	}
286
287
288	private void modifyForSoundVibrationAndLight(Builder mBuilder, boolean notify, SharedPreferences preferences) {
289		final Resources resources = mXmppConnectionService.getResources();
290		final String ringtone = preferences.getString("notification_ringtone", resources.getString(R.string.notification_ringtone));
291		final boolean vibrate = preferences.getBoolean("vibrate_on_notification", resources.getBoolean(R.bool.vibrate_on_notification));
292		final boolean led = preferences.getBoolean("led", resources.getBoolean(R.bool.led));
293		final boolean headsup = preferences.getBoolean("notification_headsup", resources.getBoolean(R.bool.headsup_notifications));
294		if (notify && !isQuietHours()) {
295			if (vibrate) {
296				final int dat = 70;
297				final long[] pattern = {0, 3 * dat, dat, dat};
298				mBuilder.setVibrate(pattern);
299			} else {
300				mBuilder.setVibrate(new long[]{0});
301			}
302			Uri uri = Uri.parse(ringtone);
303			try {
304				mBuilder.setSound(fixRingtoneUri(uri));
305			} catch (SecurityException e) {
306				Log.d(Config.LOGTAG, "unable to use custom notification sound " + uri.toString());
307			}
308		}
309		if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
310			mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
311		}
312		mBuilder.setPriority(notify ? (headsup ? NotificationCompat.PRIORITY_HIGH : NotificationCompat.PRIORITY_DEFAULT) : NotificationCompat.PRIORITY_LOW);
313		setNotificationColor(mBuilder);
314		mBuilder.setDefaults(0);
315		if (led) {
316			mBuilder.setLights(0xff00FF00, 2000, 3000);
317		}
318	}
319
320	private Uri fixRingtoneUri(Uri uri) {
321		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && "file".equals(uri.getScheme())) {
322			return FileBackend.getUriForFile(mXmppConnectionService, new File(uri.getPath()));
323		} else {
324			return uri;
325		}
326	}
327
328	private Builder buildMultipleConversation() {
329		final Builder mBuilder = new NotificationCompat.Builder(
330				mXmppConnectionService);
331		final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
332		style.setBigContentTitle(notifications.size()
333				+ " "
334				+ mXmppConnectionService
335				.getString(R.string.unread_conversations));
336		final StringBuilder names = new StringBuilder();
337		Conversation conversation = null;
338		for (final ArrayList<Message> messages : notifications.values()) {
339			if (messages.size() > 0) {
340				conversation = messages.get(0).getConversation();
341				final String name = conversation.getName().toString();
342				SpannableString styledString;
343				if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
344					int count = messages.size();
345					styledString = new SpannableString(name + ": " + mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
346					styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
347					style.addLine(styledString);
348				} else {
349					styledString = new SpannableString(name + ": " + UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
350					styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
351					style.addLine(styledString);
352				}
353				names.append(name);
354				names.append(", ");
355			}
356		}
357		if (names.length() >= 2) {
358			names.delete(names.length() - 2, names.length());
359		}
360		mBuilder.setContentTitle(notifications.size()
361				+ " "
362				+ mXmppConnectionService
363				.getString(R.string.unread_conversations));
364		mBuilder.setContentText(names.toString());
365		mBuilder.setStyle(style);
366		if (conversation != null) {
367			mBuilder.setContentIntent(createContentIntent(conversation));
368		}
369		mBuilder.setGroupSummary(true);
370		mBuilder.setGroup(CONVERSATIONS_GROUP);
371		mBuilder.setDeleteIntent(createDeleteIntent(null));
372		mBuilder.setSmallIcon(R.drawable.ic_notification);
373		return mBuilder;
374	}
375
376	private Builder buildSingleConversations(final ArrayList<Message> messages) {
377		final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
378		if (messages.size() >= 1) {
379			final Conversation conversation = messages.get(0).getConversation();
380			final UnreadConversation.Builder mUnreadBuilder = new UnreadConversation.Builder(conversation.getName().toString());
381			mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
382					.get(conversation, getPixel(64)));
383			mBuilder.setContentTitle(conversation.getName());
384			if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
385				int count = messages.size();
386				mBuilder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
387			} else {
388				Message message;
389				if ((message = getImage(messages)) != null) {
390					modifyForImage(mBuilder, mUnreadBuilder, message, messages);
391				} else {
392					modifyForTextOnly(mBuilder, mUnreadBuilder, messages);
393				}
394				RemoteInput remoteInput = new RemoteInput.Builder("text_reply").setLabel(UIHelper.getMessageHint(mXmppConnectionService, conversation)).build();
395				PendingIntent markAsReadPendingIntent = createReadPendingIntent(conversation);
396				NotificationCompat.Action markReadAction = new NotificationCompat.Action.Builder(
397						R.drawable.ic_drafts_white_24dp,
398						mXmppConnectionService.getString(R.string.mark_as_read),
399						markAsReadPendingIntent).build();
400				String replyLabel = mXmppConnectionService.getString(R.string.reply);
401				NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
402						R.drawable.ic_send_text_offline,
403						replyLabel,
404						createReplyIntent(conversation, false)).addRemoteInput(remoteInput).build();
405				NotificationCompat.Action wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_wear_reply,
406						replyLabel,
407						createReplyIntent(conversation, true)).addRemoteInput(remoteInput).build();
408				mBuilder.extend(new NotificationCompat.WearableExtender().addAction(wearReplyAction));
409				mUnreadBuilder.setReplyAction(createReplyIntent(conversation, true), remoteInput);
410				mUnreadBuilder.setReadPendingIntent(markAsReadPendingIntent);
411				mBuilder.extend(new NotificationCompat.CarExtender().setUnreadConversation(mUnreadBuilder.build()));
412				int addedActionsCount = 1;
413				mBuilder.addAction(markReadAction);
414				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
415					mBuilder.addAction(replyAction);
416					++addedActionsCount;
417				}
418
419				if (displaySnoozeAction(messages)) {
420					String label = mXmppConnectionService.getString(R.string.snooze);
421					PendingIntent pendingSnoozeIntent = createSnoozeIntent(conversation);
422					NotificationCompat.Action snoozeAction = new NotificationCompat.Action.Builder(
423							R.drawable.ic_notifications_paused_white_24dp,
424							label,
425							pendingSnoozeIntent).build();
426					mBuilder.addAction(snoozeAction);
427					++addedActionsCount;
428				}
429				if (addedActionsCount < 3) {
430					final Message firstLocationMessage = getFirstLocationMessage(messages);
431					if (firstLocationMessage != null) {
432						String label = mXmppConnectionService.getResources().getString(R.string.show_location);
433						PendingIntent pendingShowLocationIntent = createShowLocationIntent(firstLocationMessage);
434						NotificationCompat.Action locationAction = new NotificationCompat.Action.Builder(
435								R.drawable.ic_room_white_24dp,
436								label,
437								pendingShowLocationIntent).build();
438						mBuilder.addAction(locationAction);
439						++addedActionsCount;
440					}
441				}
442				if (addedActionsCount < 3) {
443					Message firstDownloadableMessage = getFirstDownloadableMessage(messages);
444					if (firstDownloadableMessage != null) {
445						String label = mXmppConnectionService.getResources().getString(R.string.download_x_file, UIHelper.getFileDescriptionString(mXmppConnectionService, firstDownloadableMessage));
446						PendingIntent pendingDownloadIntent = createDownloadIntent(firstDownloadableMessage);
447						NotificationCompat.Action downloadAction = new NotificationCompat.Action.Builder(
448								R.drawable.ic_file_download_white_24dp,
449								label,
450								pendingDownloadIntent).build();
451						mBuilder.addAction(downloadAction);
452						++addedActionsCount;
453					}
454				}
455			}
456			if (conversation.getMode() == Conversation.MODE_SINGLE) {
457				Contact contact = conversation.getContact();
458				Uri systemAccount = contact.getSystemAccount();
459				if (systemAccount != null) {
460					mBuilder.addPerson(systemAccount.toString());
461				}
462			}
463			mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
464			mBuilder.setSmallIcon(R.drawable.ic_notification);
465			mBuilder.setDeleteIntent(createDeleteIntent(conversation));
466			mBuilder.setContentIntent(createContentIntent(conversation));
467		}
468		return mBuilder;
469	}
470
471	private static boolean displaySnoozeAction(List<Message> messages) {
472		int numberOfMessagesWithoutReply = 0;
473		for (Message message : messages) {
474			if (message.getStatus() == Message.STATUS_RECEIVED) {
475				++numberOfMessagesWithoutReply;
476			} else {
477				return false;
478			}
479		}
480		return numberOfMessagesWithoutReply >= 3;
481	}
482
483	private void modifyForImage(final Builder builder, final UnreadConversation.Builder uBuilder,
484	                            final Message message, final ArrayList<Message> messages) {
485		try {
486			final Bitmap bitmap = mXmppConnectionService.getFileBackend()
487					.getThumbnail(message, getPixel(288), false);
488			final ArrayList<Message> tmp = new ArrayList<>();
489			for (final Message msg : messages) {
490				if (msg.getType() == Message.TYPE_TEXT
491						&& msg.getTransferable() == null) {
492					tmp.add(msg);
493				}
494			}
495			final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
496			bigPictureStyle.bigPicture(bitmap);
497			if (tmp.size() > 0) {
498				CharSequence text = getMergedBodies(tmp);
499				bigPictureStyle.setSummaryText(text);
500				builder.setContentText(text);
501			} else {
502				builder.setContentText(mXmppConnectionService.getString(
503						R.string.received_x_file,
504						UIHelper.getFileDescriptionString(mXmppConnectionService, message)));
505			}
506			builder.setStyle(bigPictureStyle);
507		} catch (final FileNotFoundException e) {
508			modifyForTextOnly(builder, uBuilder, messages);
509		}
510	}
511
512	private void modifyForTextOnly(final Builder builder, final UnreadConversation.Builder uBuilder, final ArrayList<Message> messages) {
513		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
514			NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(mXmppConnectionService.getString(R.string.me));
515			Conversation conversation = messages.get(0).getConversation();
516			if (conversation.getMode() == Conversation.MODE_MULTI) {
517				messagingStyle.setConversationTitle(conversation.getName());
518			}
519			for (Message message : messages) {
520				String sender = message.getStatus() == Message.STATUS_RECEIVED ? UIHelper.getMessageDisplayName(message) : null;
521				messagingStyle.addMessage(UIHelper.getMessagePreview(mXmppConnectionService, message).first, message.getTimeSent(), sender);
522			}
523			builder.setStyle(messagingStyle);
524		} else {
525			if (messages.get(0).getConversation().getMode() == Conversation.MODE_SINGLE) {
526				builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
527				builder.setContentText(UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
528			} else {
529				final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
530				SpannableString styledString;
531				for (Message message : messages) {
532					final String name = UIHelper.getMessageDisplayName(message);
533					styledString = new SpannableString(name + ": " + message.getBody());
534					styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
535					style.addLine(styledString);
536				}
537				builder.setStyle(style);
538				int count = messages.size();
539				if (count == 1) {
540					final String name = UIHelper.getMessageDisplayName(messages.get(0));
541					styledString = new SpannableString(name + ": " + messages.get(0).getBody());
542					styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
543					builder.setContentText(styledString);
544				} else {
545					builder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
546				}
547			}
548		}
549		/** message preview for Android Auto **/
550		for (Message message : messages) {
551			Pair<String, Boolean> preview = UIHelper.getMessagePreview(mXmppConnectionService, message);
552			// only show user written text
553			if (!preview.second) {
554				uBuilder.addMessage(preview.first);
555				uBuilder.setLatestTimestamp(message.getTimeSent());
556			}
557		}
558	}
559
560	private Message getImage(final Iterable<Message> messages) {
561		Message image = null;
562		for (final Message message : messages) {
563			if (message.getStatus() != Message.STATUS_RECEIVED) {
564				return null;
565			}
566			if (message.getType() != Message.TYPE_TEXT
567					&& message.getTransferable() == null
568					&& message.getEncryption() != Message.ENCRYPTION_PGP
569					&& message.getFileParams().height > 0) {
570				image = message;
571			}
572		}
573		return image;
574	}
575
576	private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
577		for (final Message message : messages) {
578			if (message.getTransferable() != null || (message.getType() == Message.TYPE_TEXT && message.treatAsDownloadable())) {
579				return message;
580			}
581		}
582		return null;
583	}
584
585	private Message getFirstLocationMessage(final Iterable<Message> messages) {
586		for (final Message message : messages) {
587			if (message.isGeoUri()) {
588				return message;
589			}
590		}
591		return null;
592	}
593
594	private CharSequence getMergedBodies(final ArrayList<Message> messages) {
595		final StringBuilder text = new StringBuilder();
596		for (Message message : messages) {
597			if (text.length() != 0) {
598				text.append("\n");
599			}
600			text.append(UIHelper.getMessagePreview(mXmppConnectionService, message).first);
601		}
602		return text.toString();
603	}
604
605	private PendingIntent createShowLocationIntent(final Message message) {
606		Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(message);
607		for (Intent intent : intents) {
608			if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
609				return PendingIntent.getActivity(mXmppConnectionService, generateRequestCode(message.getConversation(), 18), intent, PendingIntent.FLAG_UPDATE_CURRENT);
610			}
611		}
612		return createOpenConversationsIntent();
613	}
614
615	private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
616		final Intent viewConversationIntent = new Intent(mXmppConnectionService, ConversationsActivity.class);
617		viewConversationIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
618		viewConversationIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversationUuid);
619		if (downloadMessageUuid != null) {
620			viewConversationIntent.putExtra(ConversationsActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
621			return PendingIntent.getActivity(mXmppConnectionService,
622					generateRequestCode(conversationUuid, 8),
623					viewConversationIntent,
624					PendingIntent.FLAG_UPDATE_CURRENT);
625		} else {
626			return PendingIntent.getActivity(mXmppConnectionService,
627					generateRequestCode(conversationUuid, 10),
628					viewConversationIntent,
629					PendingIntent.FLAG_UPDATE_CURRENT);
630		}
631	}
632
633	private int generateRequestCode(String uuid, int actionId) {
634		return (actionId * NOTIFICATION_ID_MULTIPLIER) + (uuid.hashCode() % NOTIFICATION_ID_MULTIPLIER);
635	}
636
637	private int generateRequestCode(Conversation conversation, int actionId) {
638		return generateRequestCode(conversation.getUuid(), actionId);
639	}
640
641	private PendingIntent createDownloadIntent(final Message message) {
642		return createContentIntent(message.getConversationUuid(), message.getUuid());
643	}
644
645	private PendingIntent createContentIntent(final Conversation conversation) {
646		return createContentIntent(conversation.getUuid(), null);
647	}
648
649	private PendingIntent createDeleteIntent(Conversation conversation) {
650		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
651		intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
652		if (conversation != null) {
653			intent.putExtra("uuid", conversation.getUuid());
654			return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 20), intent, 0);
655		}
656		return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
657	}
658
659	private PendingIntent createReplyIntent(Conversation conversation, boolean dismissAfterReply) {
660		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
661		intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
662		intent.putExtra("uuid", conversation.getUuid());
663		intent.putExtra("dismiss_notification", dismissAfterReply);
664		final int id = generateRequestCode(conversation, dismissAfterReply ? 12 : 14);
665		return PendingIntent.getService(mXmppConnectionService, id, intent, 0);
666	}
667
668	private PendingIntent createReadPendingIntent(Conversation conversation) {
669		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
670		intent.setAction(XmppConnectionService.ACTION_MARK_AS_READ);
671		intent.putExtra("uuid", conversation.getUuid());
672		intent.setPackage(mXmppConnectionService.getPackageName());
673		return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 16), intent, PendingIntent.FLAG_UPDATE_CURRENT);
674	}
675
676	public PendingIntent createSnoozeIntent(Conversation conversation) {
677		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
678		intent.setAction(XmppConnectionService.ACTION_SNOOZE);
679		intent.putExtra("uuid", conversation.getUuid());
680		intent.setPackage(mXmppConnectionService.getPackageName());
681		return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 22), intent, PendingIntent.FLAG_UPDATE_CURRENT);
682	}
683
684	private PendingIntent createTryAgainIntent() {
685		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
686		intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
687		return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
688	}
689
690	private PendingIntent createDismissErrorIntent() {
691		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
692		intent.setAction(XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS);
693		return PendingIntent.getService(mXmppConnectionService, 69, intent, 0);
694	}
695
696	private boolean wasHighlightedOrPrivate(final Message message) {
697		final String nick = message.getConversation().getMucOptions().getActualNick();
698		final Pattern highlight = generateNickHighlightPattern(nick);
699		if (message.getBody() == null || nick == null) {
700			return false;
701		}
702		final Matcher m = highlight.matcher(message.getBody());
703		return (m.find() || message.getType() == Message.TYPE_PRIVATE);
704	}
705
706	public static Pattern generateNickHighlightPattern(final String nick) {
707		// We expect a word boundary, i.e. space or start of string, followed by
708		// the
709		// nick (matched in case-insensitive manner), followed by optional
710		// punctuation (for example "bob: i disagree" or "how are you alice?"),
711		// followed by another word boundary.
712		return Pattern.compile("\\b" + Pattern.quote(nick) + "\\p{Punct}?\\b",
713				Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
714	}
715
716	public void setOpenConversation(final Conversation conversation) {
717		this.mOpenConversation = conversation;
718	}
719
720	public void setIsInForeground(final boolean foreground) {
721		this.mIsInForeground = foreground;
722	}
723
724	private int getPixel(final int dp) {
725		final DisplayMetrics metrics = mXmppConnectionService.getResources()
726				.getDisplayMetrics();
727		return ((int) (dp * metrics.density));
728	}
729
730	private void markLastNotification() {
731		this.mLastNotification = SystemClock.elapsedRealtime();
732	}
733
734	private boolean inMiniGracePeriod(final Account account) {
735		final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
736				: Config.MINI_GRACE_PERIOD * 2;
737		return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
738	}
739
740	public Notification createForegroundNotification() {
741		final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
742
743		mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.conversations_foreground_service));
744		if (Config.SHOW_CONNECTED_ACCOUNTS) {
745			List<Account> accounts = mXmppConnectionService.getAccounts();
746			int enabled = 0;
747			int connected = 0;
748			for (Account account : accounts) {
749				if (account.isOnlineAndConnected()) {
750					connected++;
751					enabled++;
752				} else if (account.isEnabled()) {
753					enabled++;
754				}
755			}
756			mBuilder.setContentText(mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
757		} else {
758			mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_open_conversations));
759		}
760		mBuilder.setContentIntent(createOpenConversationsIntent());
761		mBuilder.setWhen(0);
762		mBuilder.setPriority(Config.SHOW_CONNECTED_ACCOUNTS ? NotificationCompat.PRIORITY_DEFAULT : NotificationCompat.PRIORITY_MIN);
763		mBuilder.setSmallIcon(R.drawable.ic_link_white_24dp);
764		return mBuilder.build();
765	}
766
767	private PendingIntent createOpenConversationsIntent() {
768		return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService, ConversationsActivity.class), 0);
769	}
770
771	public void updateErrorNotification() {
772		final List<Account> errors = new ArrayList<>();
773		for (final Account account : mXmppConnectionService.getAccounts()) {
774			if (account.hasErrorStatus() && account.showErrorNotification()) {
775				errors.add(account);
776			}
777		}
778		if (mXmppConnectionService.keepForegroundService()) {
779			notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
780		}
781		final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
782		if (errors.size() == 0) {
783			cancel(ERROR_NOTIFICATION_ID);
784			return;
785		} else if (errors.size() == 1) {
786			mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
787			mBuilder.setContentText(errors.get(0).getJid().asBareJid().toString());
788		} else {
789			mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
790			mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
791		}
792		mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
793				mXmppConnectionService.getString(R.string.try_again),
794				createTryAgainIntent());
795		mBuilder.setDeleteIntent(createDismissErrorIntent());
796		mBuilder.setVisibility(NotificationCompat.VISIBILITY_PRIVATE);
797		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
798			mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
799		} else {
800			mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
801		}
802		mBuilder.setLocalOnly(true);
803		mBuilder.setPriority(NotificationCompat.PRIORITY_LOW);
804		mBuilder.setContentIntent(PendingIntent.getActivity(mXmppConnectionService,
805				145,
806				new Intent(mXmppConnectionService, ManageAccountActivity.class),
807				PendingIntent.FLAG_UPDATE_CURRENT));
808		notify(ERROR_NOTIFICATION_ID, mBuilder.build());
809	}
810
811	public Notification updateFileAddingNotification(int current, Message message) {
812		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
813		mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.transcoding_video));
814		mBuilder.setProgress(100, current, false);
815		mBuilder.setSmallIcon(R.drawable.ic_hourglass_empty_white_24dp);
816		mBuilder.setContentIntent(createContentIntent(message.getConversation()));
817		Notification notification = mBuilder.build();
818		notify(FOREGROUND_NOTIFICATION_ID, notification);
819		return notification;
820	}
821
822	private void notify(String tag, int id, Notification notification) {
823		final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
824		try {
825			notificationManager.notify(tag, id, notification);
826		} catch (RuntimeException e) {
827			Log.d(Config.LOGTAG, "unable to make notification", e);
828		}
829	}
830
831	private void notify(int id, Notification notification) {
832		final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
833		try {
834			notificationManager.notify(id, notification);
835		} catch (RuntimeException e) {
836			Log.d(Config.LOGTAG, "unable to make notification", e);
837		}
838	}
839
840	private void cancel(int id) {
841		final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
842		try {
843			notificationManager.cancel(id);
844		} catch (RuntimeException e) {
845			Log.d(Config.LOGTAG, "unable to cancel notification", e);
846		}
847	}
848
849	private void cancel(String tag, int id) {
850		final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
851		try {
852			notificationManager.cancel(tag, id);
853		} catch (RuntimeException e) {
854			Log.d(Config.LOGTAG, "unable to cancel notification", e);
855		}
856	}
857}