NotificationService.java

  1package eu.siacs.conversations.services;
  2
  3import android.app.Notification;
  4import android.app.NotificationManager;
  5import android.app.PendingIntent;
  6import android.content.Context;
  7import android.content.Intent;
  8import android.content.SharedPreferences;
  9import android.graphics.Bitmap;
 10import android.net.Uri;
 11import android.os.Build;
 12import android.os.SystemClock;
 13import android.support.v4.app.NotificationCompat;
 14import android.support.v4.app.NotificationCompat.BigPictureStyle;
 15import android.support.v4.app.NotificationCompat.Builder;
 16import android.support.v4.app.TaskStackBuilder;
 17import android.text.Html;
 18import android.util.DisplayMetrics;
 19
 20import org.json.JSONArray;
 21import org.json.JSONObject;
 22
 23import java.io.FileNotFoundException;
 24import java.util.ArrayList;
 25import java.util.Calendar;
 26import java.util.HashMap;
 27import java.util.LinkedHashMap;
 28import java.util.List;
 29import java.util.regex.Matcher;
 30import java.util.regex.Pattern;
 31
 32import eu.siacs.conversations.Config;
 33import eu.siacs.conversations.R;
 34import eu.siacs.conversations.entities.Account;
 35import eu.siacs.conversations.entities.Conversation;
 36import eu.siacs.conversations.entities.Message;
 37import eu.siacs.conversations.ui.ConversationActivity;
 38import eu.siacs.conversations.ui.ManageAccountActivity;
 39import eu.siacs.conversations.ui.TimePreference;
 40import eu.siacs.conversations.utils.GeoHelper;
 41import eu.siacs.conversations.utils.UIHelper;
 42
 43public class NotificationService {
 44
 45	private final XmppConnectionService mXmppConnectionService;
 46
 47	private final LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<>();
 48
 49	public static final int NOTIFICATION_ID = 0x2342;
 50	public static final int FOREGROUND_NOTIFICATION_ID = 0x8899;
 51	public static final int ERROR_NOTIFICATION_ID = 0x5678;
 52
 53	private Conversation mOpenConversation;
 54	private boolean mIsInForeground;
 55	private long mLastNotification;
 56
 57	public NotificationService(final XmppConnectionService service) {
 58		this.mXmppConnectionService = service;
 59	}
 60
 61	public boolean notify(final Message message) {
 62		return (message.getStatus() == Message.STATUS_RECEIVED)
 63			&& notificationsEnabled()
 64			&& !message.getConversation().isMuted()
 65			&& (message.getConversation().isPnNA()
 66					|| conferenceNotificationsEnabled()
 67					|| wasHighlightedOrPrivate(message)
 68				 );
 69	}
 70
 71	public void notifyPebble(final Message message) {
 72		final Intent i = new Intent("com.getpebble.action.SEND_NOTIFICATION");
 73
 74		final Conversation conversation = message.getConversation();
 75		final JSONObject jsonData = new JSONObject(new HashMap<String, String>(2) {{
 76			put("title", conversation.getName());
 77			put("body", message.getBody());
 78		}});
 79		final String notificationData = new JSONArray().put(jsonData).toString();
 80
 81		i.putExtra("messageType", "PEBBLE_ALERT");
 82		i.putExtra("sender", "Conversations"); /* XXX: Shouldn't be hardcoded, e.g., AbstractGenerator.APP_NAME); */
 83		i.putExtra("notificationData", notificationData);
 84		// notify Pebble App
 85		i.setPackage("com.getpebble.android");
 86		mXmppConnectionService.sendBroadcast(i);
 87		// notify Gadgetbridge
 88		i.setPackage("nodomain.freeyourgadget.gadgetbridge");
 89		mXmppConnectionService.sendBroadcast(i);
 90	}
 91
 92
 93	public boolean notificationsEnabled() {
 94		return mXmppConnectionService.getPreferences().getBoolean("show_notification", true);
 95	}
 96
 97	public boolean isQuietHours() {
 98		if (!mXmppConnectionService.getPreferences().getBoolean("enable_quiet_hours", false)) {
 99			return false;
100		}
101		final long startTime = mXmppConnectionService.getPreferences().getLong("quiet_hours_start", TimePreference.DEFAULT_VALUE) % Config.MILLISECONDS_IN_DAY;
102		final long endTime = mXmppConnectionService.getPreferences().getLong("quiet_hours_end", TimePreference.DEFAULT_VALUE) % Config.MILLISECONDS_IN_DAY;
103		final long nowTime = Calendar.getInstance().getTimeInMillis() % Config.MILLISECONDS_IN_DAY;
104
105		if (endTime < startTime) {
106			return nowTime > startTime || nowTime < endTime;
107		} else {
108			return nowTime > startTime && nowTime < endTime;
109		}
110	}
111
112	public boolean conferenceNotificationsEnabled() {
113		return mXmppConnectionService.getPreferences().getBoolean("always_notify_in_conference", false);
114	}
115
116	public void pushFromBacklog(final Message message) {
117		if (notify(message)) {
118			pushToStack(message);
119		}
120	}
121
122	public void finishBacklog() {
123		synchronized (notifications) {
124			mXmppConnectionService.updateUnreadCountBadge();
125			updateNotification(false);
126		}
127	}
128
129	private void pushToStack(final Message message) {
130		final String conversationUuid = message.getConversationUuid();
131		if (notifications.containsKey(conversationUuid)) {
132			notifications.get(conversationUuid).add(message);
133		} else {
134			final ArrayList<Message> mList = new ArrayList<>();
135			mList.add(message);
136			notifications.put(conversationUuid, mList);
137		}
138	}
139
140	public void push(final Message message) {
141		mXmppConnectionService.updateUnreadCountBadge();
142		if (!notify(message)) {
143			return;
144		}
145		final boolean isScreenOn = mXmppConnectionService.isInteractive();
146		if (this.mIsInForeground && isScreenOn && this.mOpenConversation == message.getConversation()) {
147			return;
148		}
149		synchronized (notifications) {
150			pushToStack(message);
151			final Account account = message.getConversation().getAccount();
152			final boolean doNotify = (!(this.mIsInForeground && this.mOpenConversation == null) || !isScreenOn)
153					&& !account.inGracePeriod()
154					&& !this.inMiniGracePeriod(account);
155			updateNotification(doNotify);
156			if (doNotify) {
157				notifyPebble(message);
158			}
159		}
160	}
161
162	public void clear() {
163		synchronized (notifications) {
164			notifications.clear();
165			updateNotification(false);
166		}
167	}
168
169	public void clear(final Conversation conversation) {
170		synchronized (notifications) {
171			notifications.remove(conversation.getUuid());
172			updateNotification(false);
173		}
174	}
175
176	private void setNotificationColor(final Builder mBuilder) {
177		mBuilder.setColor(mXmppConnectionService.getResources().getColor(R.color.primary));
178	}
179
180	private void updateNotification(final boolean notify) {
181		final NotificationManager notificationManager = (NotificationManager) mXmppConnectionService
182			.getSystemService(Context.NOTIFICATION_SERVICE);
183		final SharedPreferences preferences = mXmppConnectionService.getPreferences();
184
185		final String ringtone = preferences.getString("notification_ringtone", null);
186		final boolean vibrate = preferences.getBoolean("vibrate_on_notification", true);
187
188		if (notifications.size() == 0) {
189			notificationManager.cancel(NOTIFICATION_ID);
190		} else {
191			if (notify) {
192				this.markLastNotification();
193			}
194			final Builder mBuilder;
195			if (notifications.size() == 1) {
196				mBuilder = buildSingleConversations(notify);
197			} else {
198				mBuilder = buildMultipleConversation();
199			}
200			if (notify && !isQuietHours()) {
201				if (vibrate) {
202					final int dat = 70;
203					final long[] pattern = {0, 3 * dat, dat, dat};
204					mBuilder.setVibrate(pattern);
205				}
206				if (ringtone != null) {
207					mBuilder.setSound(Uri.parse(ringtone));
208				}
209			}
210			if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
211				mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
212			}
213			setNotificationColor(mBuilder);
214			mBuilder.setDefaults(0);
215			mBuilder.setSmallIcon(R.drawable.ic_notification);
216			mBuilder.setDeleteIntent(createDeleteIntent());
217			mBuilder.setLights(0xff00FF00, 2000, 3000);
218			final Notification notification = mBuilder.build();
219			notificationManager.notify(NOTIFICATION_ID, notification);
220		}
221	}
222
223	private Builder buildMultipleConversation() {
224		final Builder mBuilder = new NotificationCompat.Builder(
225				mXmppConnectionService);
226		final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
227		style.setBigContentTitle(notifications.size()
228				+ " "
229				+ mXmppConnectionService
230				.getString(R.string.unread_conversations));
231		final StringBuilder names = new StringBuilder();
232		Conversation conversation = null;
233		for (final ArrayList<Message> messages : notifications.values()) {
234			if (messages.size() > 0) {
235				conversation = messages.get(0).getConversation();
236				final String name = conversation.getName();
237				style.addLine(Html.fromHtml("<b>" + name + "</b> "
238							+ UIHelper.getMessagePreview(mXmppConnectionService,messages.get(0)).first));
239				names.append(name);
240				names.append(", ");
241			}
242		}
243		if (names.length() >= 2) {
244			names.delete(names.length() - 2, names.length());
245		}
246		mBuilder.setContentTitle(notifications.size()
247				+ " "
248				+ mXmppConnectionService
249				.getString(R.string.unread_conversations));
250		mBuilder.setContentText(names.toString());
251		mBuilder.setStyle(style);
252		if (conversation != null) {
253			mBuilder.setContentIntent(createContentIntent(conversation));
254		}
255		return mBuilder;
256	}
257
258	private Builder buildSingleConversations(final boolean notify) {
259		final Builder mBuilder = new NotificationCompat.Builder(
260				mXmppConnectionService);
261		final ArrayList<Message> messages = notifications.values().iterator().next();
262		if (messages.size() >= 1) {
263			final Conversation conversation = messages.get(0).getConversation();
264			mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
265					.get(conversation, getPixel(64)));
266			mBuilder.setContentTitle(conversation.getName());
267			Message message;
268			if ((message = getImage(messages)) != null) {
269				modifyForImage(mBuilder, message, messages, notify);
270			} else {
271				modifyForTextOnly(mBuilder, messages, notify);
272			}
273			if ((message = getFirstDownloadableMessage(messages)) != null) {
274				mBuilder.addAction(
275						Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ?
276								R.drawable.ic_file_download_white_24dp : R.drawable.ic_action_download,
277						mXmppConnectionService.getResources().getString(R.string.download_x_file,
278							UIHelper.getFileDescriptionString(mXmppConnectionService, message)),
279						createDownloadIntent(message)
280						);
281			}
282			if ((message = getFirstLocationMessage(messages)) != null) {
283				mBuilder.addAction(R.drawable.ic_room_white_24dp,
284						mXmppConnectionService.getString(R.string.show_location),
285						createShowLocationIntent(message));
286			}
287			mBuilder.setContentIntent(createContentIntent(conversation));
288		}
289		return mBuilder;
290	}
291
292	private void modifyForImage(final Builder builder, final Message message,
293			final ArrayList<Message> messages, final boolean notify) {
294		try {
295			final Bitmap bitmap = mXmppConnectionService.getFileBackend()
296				.getThumbnail(message, getPixel(288), false);
297			final ArrayList<Message> tmp = new ArrayList<>();
298			for (final Message msg : messages) {
299				if (msg.getType() == Message.TYPE_TEXT
300						&& msg.getTransferable() == null) {
301					tmp.add(msg);
302						}
303			}
304			final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
305			bigPictureStyle.bigPicture(bitmap);
306			if (tmp.size() > 0) {
307				bigPictureStyle.setSummaryText(getMergedBodies(tmp));
308				builder.setContentText(UIHelper.getMessagePreview(mXmppConnectionService,tmp.get(0)).first);
309			} else {
310				builder.setContentText(mXmppConnectionService.getString(
311						R.string.received_x_file,
312						UIHelper.getFileDescriptionString(mXmppConnectionService,message)));
313			}
314			builder.setStyle(bigPictureStyle);
315		} catch (final FileNotFoundException e) {
316			modifyForTextOnly(builder, messages, notify);
317		}
318	}
319
320	private void modifyForTextOnly(final Builder builder,
321			final ArrayList<Message> messages, final boolean notify) {
322		builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
323		builder.setContentText(UIHelper.getMessagePreview(mXmppConnectionService,messages.get(0)).first);
324		if (notify) {
325			builder.setTicker(UIHelper.getMessagePreview(mXmppConnectionService,messages.get(messages.size() - 1)).first);
326		}
327	}
328
329	private Message getImage(final Iterable<Message> messages) {
330		for (final Message message : messages) {
331			if (message.getType() != Message.TYPE_TEXT
332					&& message.getTransferable() == null
333					&& message.getEncryption() != Message.ENCRYPTION_PGP
334					&& message.getFileParams().height > 0) {
335				return message;
336					}
337		}
338		return null;
339	}
340
341	private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
342		for (final Message message : messages) {
343			if ((message.getType() == Message.TYPE_FILE || message.getType() == Message.TYPE_IMAGE) &&
344					message.getTransferable() != null) {
345				return message;
346			}
347		}
348		return null;
349	}
350
351	private Message getFirstLocationMessage(final Iterable<Message> messages) {
352		for(final Message message : messages) {
353			if (GeoHelper.isGeoUri(message.getBody())) {
354				return message;
355			}
356		}
357		return null;
358	}
359
360	private CharSequence getMergedBodies(final ArrayList<Message> messages) {
361		final StringBuilder text = new StringBuilder();
362		for (int i = 0; i < messages.size(); ++i) {
363			text.append(UIHelper.getMessagePreview(mXmppConnectionService,messages.get(i)).first);
364			if (i != messages.size() - 1) {
365				text.append("\n");
366			}
367		}
368		return text.toString();
369	}
370
371	private PendingIntent createShowLocationIntent(final Message message) {
372		Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(message);
373		for(Intent intent : intents) {
374			if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
375				return PendingIntent.getActivity(mXmppConnectionService,18,intent,PendingIntent.FLAG_UPDATE_CURRENT);
376			}
377		}
378		return createOpenConversationsIntent();
379	}
380
381	private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
382		final TaskStackBuilder stackBuilder = TaskStackBuilder
383			.create(mXmppConnectionService);
384		stackBuilder.addParentStack(ConversationActivity.class);
385
386		final Intent viewConversationIntent = new Intent(mXmppConnectionService,
387				ConversationActivity.class);
388		if (downloadMessageUuid != null) {
389			viewConversationIntent.setAction(ConversationActivity.ACTION_DOWNLOAD);
390		} else {
391			viewConversationIntent.setAction(Intent.ACTION_VIEW);
392		}
393		if (conversationUuid != null) {
394			viewConversationIntent.putExtra(ConversationActivity.CONVERSATION, conversationUuid);
395			viewConversationIntent.setType(ConversationActivity.VIEW_CONVERSATION);
396		}
397		if (downloadMessageUuid != null) {
398			viewConversationIntent.putExtra(ConversationActivity.MESSAGE, downloadMessageUuid);
399		}
400
401		stackBuilder.addNextIntent(viewConversationIntent);
402
403		return stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
404	}
405
406	private PendingIntent createDownloadIntent(final Message message) {
407		return createContentIntent(message.getConversationUuid(), message.getUuid());
408	}
409
410	private PendingIntent createContentIntent(final Conversation conversation) {
411		return createContentIntent(conversation.getUuid(), null);
412	}
413
414	private PendingIntent createDeleteIntent() {
415		final Intent intent = new Intent(mXmppConnectionService,
416				XmppConnectionService.class);
417		intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
418		return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
419	}
420
421	private PendingIntent createDisableForeground() {
422		final Intent intent = new Intent(mXmppConnectionService,
423				XmppConnectionService.class);
424		intent.setAction(XmppConnectionService.ACTION_DISABLE_FOREGROUND);
425		return PendingIntent.getService(mXmppConnectionService, 34, intent, 0);
426	}
427
428	private PendingIntent createTryAgainIntent() {
429		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
430		intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
431		return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
432	}
433
434	private PendingIntent createDisableAccountIntent(final Account account) {
435		final Intent intent = new Intent(mXmppConnectionService,XmppConnectionService.class);
436		intent.setAction(XmppConnectionService.ACTION_DISABLE_ACCOUNT);
437		intent.putExtra("account",account.getJid().toBareJid().toString());
438		return PendingIntent.getService(mXmppConnectionService,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
439	}
440
441	private boolean wasHighlightedOrPrivate(final Message message) {
442		final String nick = message.getConversation().getMucOptions().getActualNick();
443		final Pattern highlight = generateNickHighlightPattern(nick);
444		if (message.getBody() == null || nick == null) {
445			return false;
446		}
447		final Matcher m = highlight.matcher(message.getBody());
448		return (m.find() || message.getType() == Message.TYPE_PRIVATE);
449	}
450
451	private static Pattern generateNickHighlightPattern(final String nick) {
452		// We expect a word boundary, i.e. space or start of string, followed by
453		// the
454		// nick (matched in case-insensitive manner), followed by optional
455		// punctuation (for example "bob: i disagree" or "how are you alice?"),
456		// followed by another word boundary.
457		return Pattern.compile("\\b" + Pattern.quote(nick) + "\\p{Punct}?\\b",
458				Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
459	}
460
461	public void setOpenConversation(final Conversation conversation) {
462		this.mOpenConversation = conversation;
463	}
464
465	public void setIsInForeground(final boolean foreground) {
466		this.mIsInForeground = foreground;
467	}
468
469	private int getPixel(final int dp) {
470		final DisplayMetrics metrics = mXmppConnectionService.getResources()
471			.getDisplayMetrics();
472		return ((int) (dp * metrics.density));
473	}
474
475	private void markLastNotification() {
476		this.mLastNotification = SystemClock.elapsedRealtime();
477	}
478
479	private boolean inMiniGracePeriod(final Account account) {
480		final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
481			: Config.MINI_GRACE_PERIOD * 2;
482		return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
483	}
484
485	public Notification createForegroundNotification() {
486		final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
487
488		mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.conversations_foreground_service));
489		mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_open_conversations));
490		mBuilder.setContentIntent(createOpenConversationsIntent());
491		mBuilder.setWhen(0);
492		mBuilder.setPriority(NotificationCompat.PRIORITY_MIN);
493		final int cancelIcon;
494		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
495			mBuilder.setCategory(Notification.CATEGORY_SERVICE);
496			cancelIcon = R.drawable.ic_cancel_white_24dp;
497		} else {
498			cancelIcon = R.drawable.ic_action_cancel;
499		}
500		mBuilder.setSmallIcon(R.drawable.ic_link_white_24dp);
501		mBuilder.addAction(cancelIcon,
502				mXmppConnectionService.getString(R.string.disable_foreground_service),
503				createDisableForeground());
504		return mBuilder.build();
505	}
506
507	private PendingIntent createOpenConversationsIntent() {
508		return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService,ConversationActivity.class),0);
509	}
510
511	public void updateErrorNotification() {
512		final NotificationManager mNotificationManager = (NotificationManager) mXmppConnectionService.getSystemService(Context.NOTIFICATION_SERVICE);
513		final List<Account> errors = new ArrayList<>();
514		for (final Account account : mXmppConnectionService.getAccounts()) {
515			if (account.hasErrorStatus()) {
516				errors.add(account);
517			}
518		}
519		final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
520		if (errors.size() == 0) {
521			mNotificationManager.cancel(ERROR_NOTIFICATION_ID);
522			return;
523		} else if (errors.size() == 1) {
524			mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
525			mBuilder.setContentText(errors.get(0).getJid().toBareJid().toString());
526		} else {
527			mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
528			mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
529		}
530		mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
531				mXmppConnectionService.getString(R.string.try_again),
532				createTryAgainIntent());
533		if (errors.size() == 1) {
534			mBuilder.addAction(R.drawable.ic_block_white_24dp,
535					mXmppConnectionService.getString(R.string.disable_account),
536					createDisableAccountIntent(errors.get(0)));
537		}
538		mBuilder.setOngoing(true);
539		//mBuilder.setLights(0xffffffff, 2000, 4000);
540		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
541			mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
542		} else {
543			mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
544		}
545		final TaskStackBuilder stackBuilder = TaskStackBuilder.create(mXmppConnectionService);
546		stackBuilder.addParentStack(ConversationActivity.class);
547
548		final Intent manageAccountsIntent = new Intent(mXmppConnectionService,ManageAccountActivity.class);
549		stackBuilder.addNextIntent(manageAccountsIntent);
550
551		final PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
552
553		mBuilder.setContentIntent(resultPendingIntent);
554		mNotificationManager.notify(ERROR_NOTIFICATION_ID, mBuilder.build());
555	}
556}