NotificationService.java

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