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.preference.PreferenceManager;
 13import android.support.v4.app.NotificationCompat;
 14import android.support.v4.app.NotificationCompat.BigPictureStyle;
 15import android.support.v4.app.NotificationCompat.Builder;
 16import android.support.v4.app.NotificationManagerCompat;
 17import android.support.v4.app.NotificationCompat.CarExtender.UnreadConversation;
 18import android.support.v4.app.RemoteInput;
 19import android.support.v4.content.ContextCompat;
 20import android.text.SpannableString;
 21import android.text.style.StyleSpan;
 22import android.util.DisplayMetrics;
 23import android.util.Log;
 24import android.util.Pair;
 25
 26import java.io.File;
 27import java.io.FileNotFoundException;
 28import java.util.ArrayList;
 29import java.util.Calendar;
 30import java.util.HashMap;
 31import java.util.Iterator;
 32import java.util.LinkedHashMap;
 33import java.util.List;
 34import java.util.Map;
 35import java.util.concurrent.atomic.AtomicInteger;
 36import java.util.regex.Matcher;
 37import java.util.regex.Pattern;
 38
 39import eu.siacs.conversations.Config;
 40import eu.siacs.conversations.R;
 41import eu.siacs.conversations.entities.Account;
 42import eu.siacs.conversations.entities.Contact;
 43import eu.siacs.conversations.entities.Conversation;
 44import eu.siacs.conversations.entities.Message;
 45import eu.siacs.conversations.persistance.FileBackend;
 46import eu.siacs.conversations.ui.ConversationActivity;
 47import eu.siacs.conversations.ui.ManageAccountActivity;
 48import eu.siacs.conversations.ui.SettingsActivity;
 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().toBareJid()+": 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().toBareJid()+": 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().toBareJid()+": 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			notifications.remove(conversation.getUuid());
228			final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
229			notificationManager.cancel(conversation.getUuid(), NOTIFICATION_ID);
230			updateNotification(false);
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		final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
255		final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
256
257		if (notifications.size() == 0) {
258			notificationManager.cancel(NOTIFICATION_ID);
259		} else {
260			if (notify) {
261				this.markLastNotification();
262			}
263			final Builder mBuilder;
264			if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
265				mBuilder = buildSingleConversations(notifications.values().iterator().next());
266				modifyForSoundVibrationAndLight(mBuilder, notify, preferences);
267				notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
268			} else {
269				mBuilder = buildMultipleConversation();
270				modifyForSoundVibrationAndLight(mBuilder, notify, preferences);
271				for(Map.Entry<String,ArrayList<Message>> entry : notifications.entrySet()) {
272					Builder singleBuilder = buildSingleConversations(entry.getValue());
273					singleBuilder.setGroup(CONVERSATIONS_GROUP);
274					modifyForSoundVibrationAndLight(singleBuilder,notify,preferences);
275					notificationManager.notify(entry.getKey(), NOTIFICATION_ID ,singleBuilder.build());
276				}
277				notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
278			}
279		}
280	}
281
282
283	private void modifyForSoundVibrationAndLight(Builder mBuilder, boolean notify, SharedPreferences preferences) {
284		final String ringtone = preferences.getString("notification_ringtone", null);
285		final boolean vibrate = preferences.getBoolean("vibrate_on_notification", true);
286		final boolean led = preferences.getBoolean("led", true);
287		final boolean headsup = preferences.getBoolean("notification_headsup", mXmppConnectionService.getResources().getBoolean(R.bool.headsup_notifications));
288		if (notify && !isQuietHours()) {
289			if (vibrate) {
290				final int dat = 70;
291				final long[] pattern = {0, 3 * dat, dat, dat};
292				mBuilder.setVibrate(pattern);
293			} else {
294				mBuilder.setVibrate(new long[]{0});
295			}
296			if (ringtone != null) {
297				Uri uri = Uri.parse(ringtone);
298				try {
299					mBuilder.setSound(fixRingtoneUri(uri));
300				} catch (SecurityException e) {
301					Log.d(Config.LOGTAG,"unable to use custom notification sound "+uri.toString());
302				}
303			}
304		}
305		if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
306			mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
307		}
308		mBuilder.setPriority(notify ? (headsup ? NotificationCompat.PRIORITY_HIGH : NotificationCompat.PRIORITY_DEFAULT) : NotificationCompat.PRIORITY_LOW);
309		setNotificationColor(mBuilder);
310		mBuilder.setDefaults(0);
311		if (led) {
312			mBuilder.setLights(0xff00FF00, 2000, 3000);
313		}
314	}
315
316	private Uri fixRingtoneUri(Uri uri) {
317		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && "file".equals(uri.getScheme())) {
318			return FileBackend.getUriForFile(mXmppConnectionService,new File(uri.getPath()));
319		} else {
320			return uri;
321		}
322	}
323
324	private Builder buildMultipleConversation() {
325		final Builder mBuilder = new NotificationCompat.Builder(
326				mXmppConnectionService);
327		final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
328		style.setBigContentTitle(notifications.size()
329				+ " "
330				+ mXmppConnectionService
331				.getString(R.string.unread_conversations));
332		final StringBuilder names = new StringBuilder();
333		Conversation conversation = null;
334		for (final ArrayList<Message> messages : notifications.values()) {
335			if (messages.size() > 0) {
336				conversation = messages.get(0).getConversation();
337				final String name = conversation.getName();
338				SpannableString styledString;
339				if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
340					int count = messages.size();
341					styledString = new SpannableString(name + ": " + mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages,count,count));
342					styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
343					style.addLine(styledString);
344				} else {
345					styledString = new SpannableString(name + ": " + UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
346					styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
347					style.addLine(styledString);
348				}
349				names.append(name);
350				names.append(", ");
351			}
352		}
353		if (names.length() >= 2) {
354			names.delete(names.length() - 2, names.length());
355		}
356		mBuilder.setContentTitle(notifications.size()
357				+ " "
358				+ mXmppConnectionService
359				.getString(R.string.unread_conversations));
360		mBuilder.setContentText(names.toString());
361		mBuilder.setStyle(style);
362		if (conversation != null) {
363			mBuilder.setContentIntent(createContentIntent(conversation));
364		}
365		mBuilder.setGroupSummary(true);
366		mBuilder.setGroup(CONVERSATIONS_GROUP);
367		mBuilder.setDeleteIntent(createDeleteIntent(null));
368		mBuilder.setSmallIcon(R.drawable.ic_notification);
369		return mBuilder;
370	}
371
372	private Builder buildSingleConversations(final ArrayList<Message> messages) {
373		final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
374		if (messages.size() >= 1) {
375			final Conversation conversation = messages.get(0).getConversation();
376			final UnreadConversation.Builder mUnreadBuilder = new UnreadConversation.Builder(conversation.getName());
377			mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
378					.get(conversation, getPixel(64)));
379			mBuilder.setContentTitle(conversation.getName());
380			if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
381				int count = messages.size();
382				mBuilder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages,count,count));
383			} else {
384				Message message;
385				if ((message = getImage(messages)) != null) {
386					modifyForImage(mBuilder, mUnreadBuilder, message, messages);
387				} else {
388					modifyForTextOnly(mBuilder, mUnreadBuilder, messages);
389				}
390				RemoteInput remoteInput = new RemoteInput.Builder("text_reply").setLabel(UIHelper.getMessageHint(mXmppConnectionService, conversation)).build();
391				NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(R.drawable.ic_send_text_offline, "Reply", createReplyIntent(conversation, false)).addRemoteInput(remoteInput).build();
392				NotificationCompat.Action wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_wear_reply, "Reply", createReplyIntent(conversation, true)).addRemoteInput(remoteInput).build();
393				mBuilder.extend(new NotificationCompat.WearableExtender().addAction(wearReplyAction));
394				mUnreadBuilder.setReplyAction(createReplyIntent(conversation, true), remoteInput);
395				mUnreadBuilder.setReadPendingIntent(createReadPendingIntent(conversation));
396				mBuilder.extend(new NotificationCompat.CarExtender().setUnreadConversation(mUnreadBuilder.build()));
397				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
398					mBuilder.addAction(replyAction);
399				}
400				if ((message = getFirstDownloadableMessage(messages)) != null) {
401					mBuilder.addAction(
402							Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ?
403									R.drawable.ic_file_download_white_24dp : R.drawable.ic_action_download,
404							mXmppConnectionService.getResources().getString(R.string.download_x_file,
405									UIHelper.getFileDescriptionString(mXmppConnectionService, message)),
406							createDownloadIntent(message)
407					);
408				}
409				if ((message = getFirstLocationMessage(messages)) != null) {
410					mBuilder.addAction(R.drawable.ic_room_white_24dp,
411							mXmppConnectionService.getString(R.string.show_location),
412							createShowLocationIntent(message));
413				}
414			}
415			if (conversation.getMode() == Conversation.MODE_SINGLE) {
416				Contact contact = conversation.getContact();
417				Uri systemAccount = contact.getSystemAccount();
418				if (systemAccount != null) {
419					mBuilder.addPerson(systemAccount.toString());
420				}
421			}
422			mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
423			mBuilder.setSmallIcon(R.drawable.ic_notification);
424			mBuilder.setDeleteIntent(createDeleteIntent(conversation));
425			mBuilder.setContentIntent(createContentIntent(conversation));
426		}
427		return mBuilder;
428	}
429
430	private void modifyForImage(final Builder builder, final UnreadConversation.Builder uBuilder,
431								final Message message, final ArrayList<Message> messages) {
432		try {
433			final Bitmap bitmap = mXmppConnectionService.getFileBackend()
434					.getThumbnail(message, getPixel(288), false);
435			final ArrayList<Message> tmp = new ArrayList<>();
436			for (final Message msg : messages) {
437				if (msg.getType() == Message.TYPE_TEXT
438						&& msg.getTransferable() == null) {
439					tmp.add(msg);
440				}
441			}
442			final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
443			bigPictureStyle.bigPicture(bitmap);
444			if (tmp.size() > 0) {
445				CharSequence text = getMergedBodies(tmp);
446				bigPictureStyle.setSummaryText(text);
447				builder.setContentText(text);
448			} else {
449				builder.setContentText(mXmppConnectionService.getString(
450						R.string.received_x_file,
451						UIHelper.getFileDescriptionString(mXmppConnectionService, message)));
452			}
453			builder.setStyle(bigPictureStyle);
454		} catch (final FileNotFoundException e) {
455			modifyForTextOnly(builder, uBuilder, messages);
456		}
457	}
458
459	private void modifyForTextOnly(final Builder builder, final UnreadConversation.Builder uBuilder, final ArrayList<Message> messages) {
460		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
461			NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(mXmppConnectionService.getString(R.string.me));
462			Conversation conversation = messages.get(0).getConversation();
463			if (conversation.getMode() == Conversation.MODE_MULTI) {
464				messagingStyle.setConversationTitle(conversation.getName());
465			}
466			for (Message message : messages) {
467				String sender = message.getStatus() == Message.STATUS_RECEIVED ? UIHelper.getMessageDisplayName(message) : null;
468				messagingStyle.addMessage(UIHelper.getMessagePreview(mXmppConnectionService,message).first, message.getTimeSent(), sender);
469			}
470			builder.setStyle(messagingStyle);
471		} else {
472			if(messages.get(0).getConversation().getMode() == Conversation.MODE_SINGLE) {
473				builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
474				builder.setContentText(UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
475			} else {
476				final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
477				SpannableString styledString;
478				for (Message message : messages) {
479					final String name = UIHelper.getMessageDisplayName(message);
480					styledString = new SpannableString(name + ": " + message.getBody());
481					styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
482					style.addLine(styledString);
483				}
484				builder.setStyle(style);
485				int count = messages.size();
486				if(count == 1) {
487					final String name = UIHelper.getMessageDisplayName(messages.get(0));
488					styledString = new SpannableString(name + ": " + messages.get(0).getBody());
489					styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
490					builder.setContentText(styledString);
491				} else {
492					builder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages,count,count));
493				}
494			}
495		}
496		/** message preview for Android Auto **/
497		for (Message message : messages) {
498			Pair<String,Boolean> preview = UIHelper.getMessagePreview(mXmppConnectionService, message);
499			// only show user written text
500			if (preview.second == false) {
501				uBuilder.addMessage(preview.first);
502				uBuilder.setLatestTimestamp(message.getTimeSent());
503			}
504		}
505	}
506
507	private Message getImage(final Iterable<Message> messages) {
508		Message image = null;
509		for (final Message message : messages) {
510			if (message.getStatus() != Message.STATUS_RECEIVED) {
511				return null;
512			}
513			if (message.getType() != Message.TYPE_TEXT
514					&& message.getTransferable() == null
515					&& message.getEncryption() != Message.ENCRYPTION_PGP
516					&& message.getFileParams().height > 0) {
517				image = message;
518			}
519		}
520		return image;
521	}
522
523	private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
524		for (final Message message : messages) {
525			if (message.getTransferable() != null || (message.getType() == Message.TYPE_TEXT && message.treatAsDownloadable())) {
526				return message;
527			}
528		}
529		return null;
530	}
531
532	private Message getFirstLocationMessage(final Iterable<Message> messages) {
533		for (final Message message : messages) {
534			if (message.isGeoUri()) {
535				return message;
536			}
537		}
538		return null;
539	}
540
541	private CharSequence getMergedBodies(final ArrayList<Message> messages) {
542		final StringBuilder text = new StringBuilder();
543		for(Message message : messages) {
544			if (text.length() != 0) {
545				text.append("\n");
546			}
547			text.append(UIHelper.getMessagePreview(mXmppConnectionService, message).first);
548		}
549		return text.toString();
550	}
551
552	private PendingIntent createShowLocationIntent(final Message message) {
553		Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(message);
554		for (Intent intent : intents) {
555			if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
556				return PendingIntent.getActivity(mXmppConnectionService, 18, intent, PendingIntent.FLAG_UPDATE_CURRENT);
557			}
558		}
559		return createOpenConversationsIntent();
560	}
561
562	private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
563		final Intent viewConversationIntent = new Intent(mXmppConnectionService,ConversationActivity.class);
564		viewConversationIntent.setAction(ConversationActivity.ACTION_VIEW_CONVERSATION);
565		viewConversationIntent.putExtra(ConversationActivity.CONVERSATION, conversationUuid);
566		if (downloadMessageUuid != null) {
567			viewConversationIntent.putExtra(ConversationActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
568			return PendingIntent.getActivity(mXmppConnectionService,
569					(conversationUuid.hashCode() % NOTIFICATION_ID_MULTIPLIER) + 8 * NOTIFICATION_ID_MULTIPLIER,
570					viewConversationIntent,
571					PendingIntent.FLAG_UPDATE_CURRENT);
572		} else {
573			return PendingIntent.getActivity(mXmppConnectionService,
574					(conversationUuid.hashCode() % NOTIFICATION_ID_MULTIPLIER) + 10 * NOTIFICATION_ID_MULTIPLIER,
575					viewConversationIntent,
576					PendingIntent.FLAG_UPDATE_CURRENT);
577		}
578	}
579
580	private PendingIntent createDownloadIntent(final Message message) {
581		return createContentIntent(message.getConversationUuid(), message.getUuid());
582	}
583
584	private PendingIntent createContentIntent(final Conversation conversation) {
585		return createContentIntent(conversation.getUuid(), null);
586	}
587
588	private PendingIntent createDeleteIntent(Conversation conversation) {
589		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
590		intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
591		if (conversation != null) {
592			intent.putExtra("uuid", conversation.getUuid());
593			return PendingIntent.getService(mXmppConnectionService, (conversation.getUuid().hashCode() % NOTIFICATION_ID_MULTIPLIER) + 12 * NOTIFICATION_ID_MULTIPLIER, intent, 0);
594		}
595		return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
596	}
597
598	private PendingIntent createReplyIntent(Conversation conversation, boolean dismissAfterReply) {
599		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
600		intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
601		intent.putExtra("uuid",conversation.getUuid());
602		intent.putExtra("dismiss_notification",dismissAfterReply);
603		int id =  (conversation.getUuid().hashCode() % NOTIFICATION_ID_MULTIPLIER) + (dismissAfterReply ? 12 : 14) * NOTIFICATION_ID_MULTIPLIER;
604		return PendingIntent.getService(mXmppConnectionService, id, intent, 0);
605	}
606
607	private PendingIntent createReadPendingIntent(Conversation conversation) {
608		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
609		intent.setAction(XmppConnectionService.ACTION_MARK_AS_READ);
610		intent.putExtra("uuid", conversation.getUuid());
611		intent.setPackage(mXmppConnectionService.getPackageName());
612		return PendingIntent.getService(mXmppConnectionService, (conversation.getUuid().hashCode() % NOTIFICATION_ID_MULTIPLIER) + 16 * NOTIFICATION_ID_MULTIPLIER, intent, PendingIntent.FLAG_UPDATE_CURRENT);
613	}
614
615	private PendingIntent createDisableForeground() {
616		final Intent intent = new Intent(mXmppConnectionService,
617				XmppConnectionService.class);
618		intent.setAction(XmppConnectionService.ACTION_DISABLE_FOREGROUND);
619		return PendingIntent.getService(mXmppConnectionService, 34, intent, 0);
620	}
621
622	private PendingIntent createTryAgainIntent() {
623		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
624		intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
625		return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
626	}
627
628	private PendingIntent createDismissErrorIntent() {
629		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
630		intent.setAction(XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS);
631		return PendingIntent.getService(mXmppConnectionService, 69, intent, 0);
632	}
633
634	private boolean wasHighlightedOrPrivate(final Message message) {
635		final String nick = message.getConversation().getMucOptions().getActualNick();
636		final Pattern highlight = generateNickHighlightPattern(nick);
637		if (message.getBody() == null || nick == null) {
638			return false;
639		}
640		final Matcher m = highlight.matcher(message.getBody());
641		return (m.find() || message.getType() == Message.TYPE_PRIVATE);
642	}
643
644	public static Pattern generateNickHighlightPattern(final String nick) {
645		// We expect a word boundary, i.e. space or start of string, followed by
646		// the
647		// nick (matched in case-insensitive manner), followed by optional
648		// punctuation (for example "bob: i disagree" or "how are you alice?"),
649		// followed by another word boundary.
650		return Pattern.compile("\\b" + Pattern.quote(nick) + "\\p{Punct}?\\b",
651				Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
652	}
653
654	public void setOpenConversation(final Conversation conversation) {
655		this.mOpenConversation = conversation;
656	}
657
658	public void setIsInForeground(final boolean foreground) {
659		this.mIsInForeground = foreground;
660	}
661
662	private int getPixel(final int dp) {
663		final DisplayMetrics metrics = mXmppConnectionService.getResources()
664				.getDisplayMetrics();
665		return ((int) (dp * metrics.density));
666	}
667
668	private void markLastNotification() {
669		this.mLastNotification = SystemClock.elapsedRealtime();
670	}
671
672	private boolean inMiniGracePeriod(final Account account) {
673		final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
674				: Config.MINI_GRACE_PERIOD * 2;
675		return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
676	}
677
678	public Notification createForegroundNotification() {
679		final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
680
681		mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.conversations_foreground_service));
682		if (Config.SHOW_CONNECTED_ACCOUNTS) {
683			List<Account> accounts = mXmppConnectionService.getAccounts();
684			int enabled = 0;
685			int connected = 0;
686			for (Account account : accounts) {
687				if (account.isOnlineAndConnected()) {
688					connected++;
689					enabled++;
690				} else if (!account.isOptionSet(Account.OPTION_DISABLED)) {
691					enabled++;
692				}
693			}
694			mBuilder.setContentText(mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
695		} else {
696			mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_open_conversations));
697		}
698		mBuilder.setContentIntent(createOpenConversationsIntent());
699		mBuilder.setWhen(0);
700		mBuilder.setPriority(Config.SHOW_CONNECTED_ACCOUNTS ? NotificationCompat.PRIORITY_DEFAULT : NotificationCompat.PRIORITY_MIN);
701		mBuilder.setSmallIcon(R.drawable.ic_link_white_24dp);
702		if (Config.SHOW_DISABLE_FOREGROUND) {
703			final int cancelIcon;
704			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
705				mBuilder.setCategory(Notification.CATEGORY_SERVICE);
706				cancelIcon = R.drawable.ic_cancel_white_24dp;
707			} else {
708				cancelIcon = R.drawable.ic_action_cancel;
709			}
710			mBuilder.addAction(cancelIcon,
711					mXmppConnectionService.getString(R.string.disable_foreground_service),
712					createDisableForeground());
713		}
714		return mBuilder.build();
715	}
716
717	private PendingIntent createOpenConversationsIntent() {
718		return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService, ConversationActivity.class), 0);
719	}
720
721	public void updateErrorNotification() {
722		final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
723		final List<Account> errors = new ArrayList<>();
724		for (final Account account : mXmppConnectionService.getAccounts()) {
725			if (account.hasErrorStatus() && account.showErrorNotification()) {
726				errors.add(account);
727			}
728		}
729		if (mXmppConnectionService.keepForegroundService()) {
730			notificationManager.notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
731		}
732		final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
733		if (errors.size() == 0) {
734			notificationManager.cancel(ERROR_NOTIFICATION_ID);
735			return;
736		} else if (errors.size() == 1) {
737			mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
738			mBuilder.setContentText(errors.get(0).getJid().toBareJid().toString());
739		} else {
740			mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
741			mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
742		}
743		mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
744				mXmppConnectionService.getString(R.string.try_again),
745				createTryAgainIntent());
746		mBuilder.setDeleteIntent(createDismissErrorIntent());
747		mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
748		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
749			mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
750		} else {
751			mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
752		}
753		mBuilder.setContentIntent(PendingIntent.getActivity(mXmppConnectionService,
754				145,
755				new Intent(mXmppConnectionService,ManageAccountActivity.class),
756				PendingIntent.FLAG_UPDATE_CURRENT));
757		notificationManager.notify(ERROR_NOTIFICATION_ID, mBuilder.build());
758	}
759}