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