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 (android.os.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
138				&& this.mOpenConversation == message.getConversation()) {
139			return;
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
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 updateNotification(final boolean notify) {
177		final NotificationManager notificationManager = (NotificationManager) mXmppConnectionService
178			.getSystemService(Context.NOTIFICATION_SERVICE);
179		final SharedPreferences preferences = mXmppConnectionService.getPreferences();
180
181		final String ringtone = preferences.getString("notification_ringtone", null);
182		final boolean vibrate = preferences.getBoolean("vibrate_on_notification", true);
183
184		if (notifications.size() == 0) {
185			notificationManager.cancel(NOTIFICATION_ID);
186		} else {
187			if (notify) {
188				this.markLastNotification();
189			}
190			final Builder mBuilder;
191			if (notifications.size() == 1) {
192				mBuilder = buildSingleConversations(notify);
193			} else {
194				mBuilder = buildMultipleConversation();
195			}
196			if (notify && !isQuietHours()) {
197				if (vibrate) {
198					final int dat = 70;
199					final long[] pattern = {0, 3 * dat, dat, dat};
200					mBuilder.setVibrate(pattern);
201				}
202				if (ringtone != null) {
203					mBuilder.setSound(Uri.parse(ringtone));
204				}
205			}
206			mBuilder.setSmallIcon(R.drawable.ic_notification);
207			mBuilder.setDeleteIntent(createDeleteIntent());
208			mBuilder.setLights(0xffffffff, 2000, 4000);
209			final Notification notification = mBuilder.build();
210			notificationManager.notify(NOTIFICATION_ID, notification);
211		}
212	}
213
214	private Builder buildMultipleConversation() {
215		final Builder mBuilder = new NotificationCompat.Builder(
216				mXmppConnectionService);
217		final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
218		style.setBigContentTitle(notifications.size()
219				+ " "
220				+ mXmppConnectionService
221				.getString(R.string.unread_conversations));
222		final StringBuilder names = new StringBuilder();
223		Conversation conversation = null;
224		for (final ArrayList<Message> messages : notifications.values()) {
225			if (messages.size() > 0) {
226				conversation = messages.get(0).getConversation();
227				final String name = conversation.getName();
228				style.addLine(Html.fromHtml("<b>" + name + "</b> "
229							+ UIHelper.getMessagePreview(mXmppConnectionService,messages.get(0)).first));
230				names.append(name);
231				names.append(", ");
232			}
233		}
234		if (names.length() >= 2) {
235			names.delete(names.length() - 2, names.length());
236		}
237		mBuilder.setContentTitle(notifications.size()
238				+ " "
239				+ mXmppConnectionService
240				.getString(R.string.unread_conversations));
241		mBuilder.setContentText(names.toString());
242		mBuilder.setStyle(style);
243		if (conversation != null) {
244			mBuilder.setContentIntent(createContentIntent(conversation));
245		}
246		return mBuilder;
247	}
248
249	private Builder buildSingleConversations(final boolean notify) {
250		final Builder mBuilder = new NotificationCompat.Builder(
251				mXmppConnectionService);
252		final ArrayList<Message> messages = notifications.values().iterator().next();
253		if (messages.size() >= 1) {
254			final Conversation conversation = messages.get(0).getConversation();
255			mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
256					.get(conversation, getPixel(64)));
257			mBuilder.setContentTitle(conversation.getName());
258			Message message;
259			if ((message = getImage(messages)) != null) {
260				modifyForImage(mBuilder, message, messages, notify);
261			} else {
262				modifyForTextOnly(mBuilder, messages, notify);
263			}
264			if ((message = getFirstDownloadableMessage(messages)) != null) {
265				mBuilder.addAction(
266						R.drawable.ic_action_download,
267						mXmppConnectionService.getResources().getString(
268							message.getType() == Message.TYPE_IMAGE ?
269							R.string.download_image :
270							R.string.download_file
271							),
272						createDownloadIntent(message)
273						);
274			}
275			mBuilder.setContentIntent(createContentIntent(conversation));
276		}
277		return mBuilder;
278	}
279
280	private void modifyForImage(final Builder builder, final Message message,
281			final ArrayList<Message> messages, final boolean notify) {
282		try {
283			final Bitmap bitmap = mXmppConnectionService.getFileBackend()
284				.getThumbnail(message, getPixel(288), false);
285			final ArrayList<Message> tmp = new ArrayList<>();
286			for (final Message msg : messages) {
287				if (msg.getType() == Message.TYPE_TEXT
288						&& msg.getDownloadable() == null) {
289					tmp.add(msg);
290						}
291			}
292			final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
293			bigPictureStyle.bigPicture(bitmap);
294			if (tmp.size() > 0) {
295				bigPictureStyle.setSummaryText(getMergedBodies(tmp));
296				builder.setContentText(UIHelper.getMessagePreview(mXmppConnectionService,tmp.get(0)).first);
297			} else {
298				builder.setContentText(mXmppConnectionService.getString(R.string.image_file));
299			}
300			builder.setStyle(bigPictureStyle);
301		} catch (final FileNotFoundException e) {
302			modifyForTextOnly(builder, messages, notify);
303		}
304	}
305
306	private void modifyForTextOnly(final Builder builder,
307			final ArrayList<Message> messages, final boolean notify) {
308		builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
309		builder.setContentText(UIHelper.getMessagePreview(mXmppConnectionService,messages.get(0)).first);
310		if (notify) {
311			builder.setTicker(UIHelper.getMessagePreview(mXmppConnectionService,messages.get(messages.size() - 1)).first);
312		}
313	}
314
315	private Message getImage(final Iterable<Message> messages) {
316		for (final Message message : messages) {
317			if (message.getType() == Message.TYPE_IMAGE
318					&& message.getDownloadable() == null
319					&& message.getEncryption() != Message.ENCRYPTION_PGP) {
320				return message;
321					}
322		}
323		return null;
324	}
325
326	private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
327		for (final Message message : messages) {
328			if ((message.getType() == Message.TYPE_FILE || message.getType() == Message.TYPE_IMAGE) &&
329					message.getDownloadable() != null) {
330				return message;
331					}
332		}
333		return null;
334	}
335
336	private CharSequence getMergedBodies(final ArrayList<Message> messages) {
337		final StringBuilder text = new StringBuilder();
338		for (int i = 0; i < messages.size(); ++i) {
339			text.append(UIHelper.getMessagePreview(mXmppConnectionService,messages.get(i)).first);
340			if (i != messages.size() - 1) {
341				text.append("\n");
342			}
343		}
344		return text.toString();
345	}
346
347	private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
348		final TaskStackBuilder stackBuilder = TaskStackBuilder
349			.create(mXmppConnectionService);
350		stackBuilder.addParentStack(ConversationActivity.class);
351
352		final Intent viewConversationIntent = new Intent(mXmppConnectionService,
353				ConversationActivity.class);
354		if (downloadMessageUuid != null) {
355			viewConversationIntent.setAction(ConversationActivity.ACTION_DOWNLOAD);
356		} else {
357			viewConversationIntent.setAction(Intent.ACTION_VIEW);
358		}
359		if (conversationUuid != null) {
360			viewConversationIntent.putExtra(ConversationActivity.CONVERSATION, conversationUuid);
361			viewConversationIntent.setType(ConversationActivity.VIEW_CONVERSATION);
362		}
363		if (downloadMessageUuid != null) {
364			viewConversationIntent.putExtra(ConversationActivity.MESSAGE, downloadMessageUuid);
365		}
366
367		stackBuilder.addNextIntent(viewConversationIntent);
368
369		return stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
370	}
371
372	private PendingIntent createDownloadIntent(final Message message) {
373		return createContentIntent(message.getConversationUuid(), message.getUuid());
374	}
375
376	private PendingIntent createContentIntent(final Conversation conversation) {
377		return createContentIntent(conversation.getUuid(), null);
378	}
379
380	private PendingIntent createDeleteIntent() {
381		final Intent intent = new Intent(mXmppConnectionService,
382				XmppConnectionService.class);
383		intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
384		return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
385	}
386
387	private PendingIntent createDisableForeground() {
388		final Intent intent = new Intent(mXmppConnectionService,
389				XmppConnectionService.class);
390		intent.setAction(XmppConnectionService.ACTION_DISABLE_FOREGROUND);
391		return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
392	}
393
394	private boolean wasHighlightedOrPrivate(final Message message) {
395		final String nick = message.getConversation().getMucOptions().getActualNick();
396		final Pattern highlight = generateNickHighlightPattern(nick);
397		if (message.getBody() == null || nick == null) {
398			return false;
399		}
400		final Matcher m = highlight.matcher(message.getBody());
401		return (m.find() || message.getType() == Message.TYPE_PRIVATE);
402	}
403
404	private static Pattern generateNickHighlightPattern(final String nick) {
405		// We expect a word boundary, i.e. space or start of string, followed by
406		// the
407		// nick (matched in case-insensitive manner), followed by optional
408		// punctuation (for example "bob: i disagree" or "how are you alice?"),
409		// followed by another word boundary.
410		return Pattern.compile("\\b" + nick + "\\p{Punct}?\\b",
411				Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
412	}
413
414	public void setOpenConversation(final Conversation conversation) {
415		this.mOpenConversation = conversation;
416	}
417
418	public void setIsInForeground(final boolean foreground) {
419		if (foreground != this.mIsInForeground) {
420			Log.d(Config.LOGTAG,"setIsInForeground("+Boolean.toString(foreground)+")");
421		}
422		this.mIsInForeground = foreground;
423	}
424
425	private int getPixel(final int dp) {
426		final DisplayMetrics metrics = mXmppConnectionService.getResources()
427			.getDisplayMetrics();
428		return ((int) (dp * metrics.density));
429	}
430
431	private void markLastNotification() {
432		this.mLastNotification = SystemClock.elapsedRealtime();
433	}
434
435	private boolean inMiniGracePeriod(final Account account) {
436		final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
437			: Config.MINI_GRACE_PERIOD * 2;
438		return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
439	}
440
441	public Notification createForegroundNotification() {
442		final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
443		mBuilder.setSmallIcon(R.drawable.ic_stat_communication_import_export);
444		mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.conversations_foreground_service));
445		mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_open_conversations));
446		mBuilder.addAction(R.drawable.ic_action_cancel,
447				mXmppConnectionService.getString(R.string.disable_foreground_service),
448				createDisableForeground());
449		mBuilder.setContentIntent(createOpenConversationsIntent());
450		mBuilder.setWhen(0);
451		mBuilder.setPriority(NotificationCompat.PRIORITY_MIN);
452		return mBuilder.build();
453	}
454
455	private PendingIntent createOpenConversationsIntent() {
456		return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService,ConversationActivity.class),0);
457	}
458
459	public void updateErrorNotification() {
460		final NotificationManager mNotificationManager = (NotificationManager) mXmppConnectionService.getSystemService(Context.NOTIFICATION_SERVICE);
461		final List<Account> errors = new ArrayList<>();
462		for (final Account account : mXmppConnectionService.getAccounts()) {
463			if (account.hasErrorStatus()) {
464				errors.add(account);
465			}
466		}
467		final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
468		if (errors.size() == 0) {
469			mNotificationManager.cancel(ERROR_NOTIFICATION_ID);
470			return;
471		} else if (errors.size() == 1) {
472			mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
473			mBuilder.setContentText(errors.get(0).getJid().toBareJid().toString());
474		} else {
475			mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
476			mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
477		}
478		mBuilder.setOngoing(true);
479		//mBuilder.setLights(0xffffffff, 2000, 4000);
480		mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
481		final TaskStackBuilder stackBuilder = TaskStackBuilder.create(mXmppConnectionService);
482		stackBuilder.addParentStack(ConversationActivity.class);
483
484		final Intent manageAccountsIntent = new Intent(mXmppConnectionService,ManageAccountActivity.class);
485		stackBuilder.addNextIntent(manageAccountsIntent);
486
487		final PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
488
489		mBuilder.setContentIntent(resultPendingIntent);
490		mNotificationManager.notify(ERROR_NOTIFICATION_ID, mBuilder.build());
491	}
492}