NotificationService.java

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