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