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(UIHelper.getFileDescriptionString(mXmppConnectionService, message));
503			}
504			builder.setStyle(bigPictureStyle);
505		} catch (final FileNotFoundException e) {
506			modifyForTextOnly(builder, uBuilder, messages);
507		}
508	}
509
510	private void modifyForTextOnly(final Builder builder, final UnreadConversation.Builder uBuilder, final ArrayList<Message> messages) {
511		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
512			NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(mXmppConnectionService.getString(R.string.me));
513			Conversation conversation = messages.get(0).getConversation();
514			if (conversation.getMode() == Conversation.MODE_MULTI) {
515				messagingStyle.setConversationTitle(conversation.getName());
516			}
517			for (Message message : messages) {
518				String sender = message.getStatus() == Message.STATUS_RECEIVED ? UIHelper.getMessageDisplayName(message) : null;
519				messagingStyle.addMessage(UIHelper.getMessagePreview(mXmppConnectionService, message).first, message.getTimeSent(), sender);
520			}
521			builder.setStyle(messagingStyle);
522		} else {
523			if (messages.get(0).getConversation().getMode() == Conversation.MODE_SINGLE) {
524				builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
525				builder.setContentText(UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
526			} else {
527				final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
528				SpannableString styledString;
529				for (Message message : messages) {
530					final String name = UIHelper.getMessageDisplayName(message);
531					styledString = new SpannableString(name + ": " + message.getBody());
532					styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
533					style.addLine(styledString);
534				}
535				builder.setStyle(style);
536				int count = messages.size();
537				if (count == 1) {
538					final String name = UIHelper.getMessageDisplayName(messages.get(0));
539					styledString = new SpannableString(name + ": " + messages.get(0).getBody());
540					styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
541					builder.setContentText(styledString);
542				} else {
543					builder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
544				}
545			}
546		}
547		/** message preview for Android Auto **/
548		for (Message message : messages) {
549			Pair<String, Boolean> preview = UIHelper.getMessagePreview(mXmppConnectionService, message);
550			// only show user written text
551			if (!preview.second) {
552				uBuilder.addMessage(preview.first);
553				uBuilder.setLatestTimestamp(message.getTimeSent());
554			}
555		}
556	}
557
558	private Message getImage(final Iterable<Message> messages) {
559		Message image = null;
560		for (final Message message : messages) {
561			if (message.getStatus() != Message.STATUS_RECEIVED) {
562				return null;
563			}
564			if (message.getType() != Message.TYPE_TEXT
565					&& message.getTransferable() == null
566					&& message.getEncryption() != Message.ENCRYPTION_PGP
567					&& message.getFileParams().height > 0) {
568				image = message;
569			}
570		}
571		return image;
572	}
573
574	private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
575		for (final Message message : messages) {
576			if (message.getTransferable() != null || (message.getType() == Message.TYPE_TEXT && message.treatAsDownloadable())) {
577				return message;
578			}
579		}
580		return null;
581	}
582
583	private Message getFirstLocationMessage(final Iterable<Message> messages) {
584		for (final Message message : messages) {
585			if (message.isGeoUri()) {
586				return message;
587			}
588		}
589		return null;
590	}
591
592	private CharSequence getMergedBodies(final ArrayList<Message> messages) {
593		final StringBuilder text = new StringBuilder();
594		for (Message message : messages) {
595			if (text.length() != 0) {
596				text.append("\n");
597			}
598			text.append(UIHelper.getMessagePreview(mXmppConnectionService, message).first);
599		}
600		return text.toString();
601	}
602
603	private PendingIntent createShowLocationIntent(final Message message) {
604		Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(message);
605		for (Intent intent : intents) {
606			if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
607				return PendingIntent.getActivity(mXmppConnectionService, generateRequestCode(message.getConversation(), 18), intent, PendingIntent.FLAG_UPDATE_CURRENT);
608			}
609		}
610		return createOpenConversationsIntent();
611	}
612
613	private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
614		final Intent viewConversationIntent = new Intent(mXmppConnectionService, ConversationsActivity.class);
615		viewConversationIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
616		viewConversationIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversationUuid);
617		if (downloadMessageUuid != null) {
618			viewConversationIntent.putExtra(ConversationsActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
619			return PendingIntent.getActivity(mXmppConnectionService,
620					generateRequestCode(conversationUuid, 8),
621					viewConversationIntent,
622					PendingIntent.FLAG_UPDATE_CURRENT);
623		} else {
624			return PendingIntent.getActivity(mXmppConnectionService,
625					generateRequestCode(conversationUuid, 10),
626					viewConversationIntent,
627					PendingIntent.FLAG_UPDATE_CURRENT);
628		}
629	}
630
631	private int generateRequestCode(String uuid, int actionId) {
632		return (actionId * NOTIFICATION_ID_MULTIPLIER) + (uuid.hashCode() % NOTIFICATION_ID_MULTIPLIER);
633	}
634
635	private int generateRequestCode(Conversation conversation, int actionId) {
636		return generateRequestCode(conversation.getUuid(), actionId);
637	}
638
639	private PendingIntent createDownloadIntent(final Message message) {
640		return createContentIntent(message.getConversationUuid(), message.getUuid());
641	}
642
643	private PendingIntent createContentIntent(final Conversation conversation) {
644		return createContentIntent(conversation.getUuid(), null);
645	}
646
647	private PendingIntent createDeleteIntent(Conversation conversation) {
648		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
649		intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
650		if (conversation != null) {
651			intent.putExtra("uuid", conversation.getUuid());
652			return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 20), intent, 0);
653		}
654		return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
655	}
656
657	private PendingIntent createReplyIntent(Conversation conversation, boolean dismissAfterReply) {
658		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
659		intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
660		intent.putExtra("uuid", conversation.getUuid());
661		intent.putExtra("dismiss_notification", dismissAfterReply);
662		final int id = generateRequestCode(conversation, dismissAfterReply ? 12 : 14);
663		return PendingIntent.getService(mXmppConnectionService, id, intent, 0);
664	}
665
666	private PendingIntent createReadPendingIntent(Conversation conversation) {
667		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
668		intent.setAction(XmppConnectionService.ACTION_MARK_AS_READ);
669		intent.putExtra("uuid", conversation.getUuid());
670		intent.setPackage(mXmppConnectionService.getPackageName());
671		return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 16), intent, PendingIntent.FLAG_UPDATE_CURRENT);
672	}
673
674	public PendingIntent createSnoozeIntent(Conversation conversation) {
675		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
676		intent.setAction(XmppConnectionService.ACTION_SNOOZE);
677		intent.putExtra("uuid", conversation.getUuid());
678		intent.setPackage(mXmppConnectionService.getPackageName());
679		return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 22), intent, PendingIntent.FLAG_UPDATE_CURRENT);
680	}
681
682	private PendingIntent createTryAgainIntent() {
683		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
684		intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
685		return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
686	}
687
688	private PendingIntent createDismissErrorIntent() {
689		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
690		intent.setAction(XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS);
691		return PendingIntent.getService(mXmppConnectionService, 69, intent, 0);
692	}
693
694	private boolean wasHighlightedOrPrivate(final Message message) {
695		final String nick = message.getConversation().getMucOptions().getActualNick();
696		final Pattern highlight = generateNickHighlightPattern(nick);
697		if (message.getBody() == null || nick == null) {
698			return false;
699		}
700		final Matcher m = highlight.matcher(message.getBody());
701		return (m.find() || message.getType() == Message.TYPE_PRIVATE);
702	}
703
704	public static Pattern generateNickHighlightPattern(final String nick) {
705		// We expect a word boundary, i.e. space or start of string, followed by
706		// the
707		// nick (matched in case-insensitive manner), followed by optional
708		// punctuation (for example "bob: i disagree" or "how are you alice?"),
709		// followed by another word boundary.
710		return Pattern.compile("\\b" + Pattern.quote(nick) + "\\p{Punct}?\\b",
711				Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
712	}
713
714	public void setOpenConversation(final Conversation conversation) {
715		this.mOpenConversation = conversation;
716	}
717
718	public void setIsInForeground(final boolean foreground) {
719		this.mIsInForeground = foreground;
720	}
721
722	private int getPixel(final int dp) {
723		final DisplayMetrics metrics = mXmppConnectionService.getResources()
724				.getDisplayMetrics();
725		return ((int) (dp * metrics.density));
726	}
727
728	private void markLastNotification() {
729		this.mLastNotification = SystemClock.elapsedRealtime();
730	}
731
732	private boolean inMiniGracePeriod(final Account account) {
733		final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
734				: Config.MINI_GRACE_PERIOD * 2;
735		return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
736	}
737
738	public Notification createForegroundNotification() {
739		final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
740
741		mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.conversations_foreground_service));
742		if (Config.SHOW_CONNECTED_ACCOUNTS) {
743			List<Account> accounts = mXmppConnectionService.getAccounts();
744			int enabled = 0;
745			int connected = 0;
746			for (Account account : accounts) {
747				if (account.isOnlineAndConnected()) {
748					connected++;
749					enabled++;
750				} else if (account.isEnabled()) {
751					enabled++;
752				}
753			}
754			mBuilder.setContentText(mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
755		} else {
756			mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_open_conversations));
757		}
758		mBuilder.setContentIntent(createOpenConversationsIntent());
759		mBuilder.setWhen(0);
760		mBuilder.setPriority(Config.SHOW_CONNECTED_ACCOUNTS ? NotificationCompat.PRIORITY_DEFAULT : NotificationCompat.PRIORITY_MIN);
761		mBuilder.setSmallIcon(R.drawable.ic_link_white_24dp);
762		return mBuilder.build();
763	}
764
765	private PendingIntent createOpenConversationsIntent() {
766		return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService, ConversationsActivity.class), 0);
767	}
768
769	public void updateErrorNotification() {
770		final List<Account> errors = new ArrayList<>();
771		for (final Account account : mXmppConnectionService.getAccounts()) {
772			if (account.hasErrorStatus() && account.showErrorNotification()) {
773				errors.add(account);
774			}
775		}
776		if (mXmppConnectionService.keepForegroundService()) {
777			notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
778		}
779		final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
780		if (errors.size() == 0) {
781			cancel(ERROR_NOTIFICATION_ID);
782			return;
783		} else if (errors.size() == 1) {
784			mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
785			mBuilder.setContentText(errors.get(0).getJid().asBareJid().toString());
786		} else {
787			mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
788			mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
789		}
790		mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
791				mXmppConnectionService.getString(R.string.try_again),
792				createTryAgainIntent());
793		mBuilder.setDeleteIntent(createDismissErrorIntent());
794		mBuilder.setVisibility(NotificationCompat.VISIBILITY_PRIVATE);
795		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
796			mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
797		} else {
798			mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
799		}
800		mBuilder.setLocalOnly(true);
801		mBuilder.setPriority(NotificationCompat.PRIORITY_LOW);
802		mBuilder.setContentIntent(PendingIntent.getActivity(mXmppConnectionService,
803				145,
804				new Intent(mXmppConnectionService, ManageAccountActivity.class),
805				PendingIntent.FLAG_UPDATE_CURRENT));
806		notify(ERROR_NOTIFICATION_ID, mBuilder.build());
807	}
808
809	public Notification updateFileAddingNotification(int current, Message message) {
810		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
811		mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.transcoding_video));
812		mBuilder.setProgress(100, current, false);
813		mBuilder.setSmallIcon(R.drawable.ic_hourglass_empty_white_24dp);
814		mBuilder.setContentIntent(createContentIntent(message.getConversation()));
815		Notification notification = mBuilder.build();
816		notify(FOREGROUND_NOTIFICATION_ID, notification);
817		return notification;
818	}
819
820	private void notify(String tag, int id, Notification notification) {
821		final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
822		try {
823			notificationManager.notify(tag, id, notification);
824		} catch (RuntimeException e) {
825			Log.d(Config.LOGTAG, "unable to make notification", e);
826		}
827	}
828
829	private void notify(int id, Notification notification) {
830		final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
831		try {
832			notificationManager.notify(id, notification);
833		} catch (RuntimeException e) {
834			Log.d(Config.LOGTAG, "unable to make notification", e);
835		}
836	}
837
838	private void cancel(int id) {
839		final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
840		try {
841			notificationManager.cancel(id);
842		} catch (RuntimeException e) {
843			Log.d(Config.LOGTAG, "unable to cancel notification", e);
844		}
845	}
846
847	private void cancel(String tag, int id) {
848		final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
849		try {
850			notificationManager.cancel(tag, id);
851		} catch (RuntimeException e) {
852			Log.d(Config.LOGTAG, "unable to cancel notification", e);
853		}
854	}
855}