NotificationService.java

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