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