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.PowerManager;
 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 java.io.FileNotFoundException;
 21import java.util.ArrayList;
 22import java.util.Calendar;
 23import java.util.LinkedHashMap;
 24import java.util.List;
 25import java.util.regex.Matcher;
 26import java.util.regex.Pattern;
 27
 28import eu.siacs.conversations.Config;
 29import eu.siacs.conversations.R;
 30import eu.siacs.conversations.entities.Account;
 31import eu.siacs.conversations.entities.Conversation;
 32import eu.siacs.conversations.entities.Downloadable;
 33import eu.siacs.conversations.entities.DownloadableFile;
 34import eu.siacs.conversations.entities.Message;
 35import eu.siacs.conversations.ui.ConversationActivity;
 36import eu.siacs.conversations.ui.ManageAccountActivity;
 37import eu.siacs.conversations.ui.TimePreference;
 38
 39public class NotificationService {
 40
 41	private XmppConnectionService mXmppConnectionService;
 42
 43	private final LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<>();
 44
 45	public static int NOTIFICATION_ID = 0x2342;
 46	public static int FOREGROUND_NOTIFICATION_ID = 0x8899;
 47	public static int ERROR_NOTIFICATION_ID = 0x5678;
 48
 49	private Conversation mOpenConversation;
 50	private boolean mIsInForeground;
 51	private long mLastNotification;
 52
 53	public NotificationService(XmppConnectionService service) {
 54		this.mXmppConnectionService = service;
 55	}
 56
 57	public boolean notify(Message message) {
 58		return (message.getStatus() == Message.STATUS_RECEIVED)
 59			&& notificationsEnabled()
 60			&& !isQuietHours()
 61			&& !message.getConversation().isMuted()
 62			&& (message.getConversation().getMode() == Conversation.MODE_SINGLE
 63					|| conferenceNotificationsEnabled()
 64					|| wasHighlightedOrPrivate(message)
 65				 );
 66	}
 67
 68	public boolean notificationsEnabled() {
 69		return mXmppConnectionService.getPreferences().getBoolean("show_notification", true);
 70	}
 71
 72	public boolean isQuietHours() {
 73		if (!mXmppConnectionService.getPreferences().getBoolean("enable_quiet_hours", false)) {
 74			return false;
 75		}
 76		final Calendar startTime = Calendar.getInstance();
 77		startTime.setTimeInMillis(mXmppConnectionService.getPreferences().getLong("quiet_hours_start", TimePreference.DEFAULT_VALUE));
 78		final Calendar endTime = Calendar.getInstance();
 79		endTime.setTimeInMillis(mXmppConnectionService.getPreferences().getLong("quiet_hours_end", TimePreference.DEFAULT_VALUE));
 80		final Calendar nowTime = Calendar.getInstance();
 81
 82		startTime.set(nowTime.get(Calendar.YEAR), nowTime.get(Calendar.MONTH), nowTime.get(Calendar.DATE));
 83		endTime.set(nowTime.get(Calendar.YEAR), nowTime.get(Calendar.MONTH), nowTime.get(Calendar.DATE));
 84
 85		if (endTime.before(startTime)) {
 86			endTime.add(Calendar.DATE, 1);
 87		}
 88
 89		return nowTime.after(startTime) && nowTime.before(endTime);
 90	}
 91
 92	public boolean conferenceNotificationsEnabled() {
 93		return mXmppConnectionService.getPreferences().getBoolean("always_notify_in_conference", false);
 94	}
 95
 96	public void push(Message message) {
 97		if (!notify(message)) {
 98			return;
 99		}
100		PowerManager pm = (PowerManager) mXmppConnectionService
101			.getSystemService(Context.POWER_SERVICE);
102		boolean isScreenOn = pm.isScreenOn();
103
104		if (this.mIsInForeground && isScreenOn
105				&& this.mOpenConversation == message.getConversation()) {
106			return;
107				}
108		synchronized (notifications) {
109			String conversationUuid = message.getConversationUuid();
110			if (notifications.containsKey(conversationUuid)) {
111				notifications.get(conversationUuid).add(message);
112			} else {
113				ArrayList<Message> mList = new ArrayList<>();
114				mList.add(message);
115				notifications.put(conversationUuid, mList);
116			}
117			Account account = message.getConversation().getAccount();
118			updateNotification((!(this.mIsInForeground && this.mOpenConversation == null) || !isScreenOn)
119					&& !account.inGracePeriod()
120					&& !this.inMiniGracePeriod(account));
121		}
122
123	}
124
125	public void clear() {
126		synchronized (notifications) {
127			notifications.clear();
128			updateNotification(false);
129		}
130	}
131
132	public void clear(Conversation conversation) {
133		synchronized (notifications) {
134			notifications.remove(conversation.getUuid());
135			updateNotification(false);
136		}
137	}
138
139	private void updateNotification(boolean notify) {
140		NotificationManager notificationManager = (NotificationManager) mXmppConnectionService
141			.getSystemService(Context.NOTIFICATION_SERVICE);
142		SharedPreferences preferences = mXmppConnectionService.getPreferences();
143
144		String ringtone = preferences.getString("notification_ringtone", null);
145		boolean vibrate = preferences.getBoolean("vibrate_on_notification",
146				true);
147
148		if (notifications.size() == 0) {
149			notificationManager.cancel(NOTIFICATION_ID);
150		} else {
151			if (notify) {
152				this.markLastNotification();
153			}
154			Builder mBuilder;
155			if (notifications.size() == 1) {
156				mBuilder = buildSingleConversations(notify);
157			} else {
158				mBuilder = buildMultipleConversation();
159			}
160			if (notify) {
161				if (vibrate) {
162					int dat = 70;
163					long[] pattern = {0, 3 * dat, dat, dat};
164					mBuilder.setVibrate(pattern);
165				}
166				if (ringtone != null) {
167					mBuilder.setSound(Uri.parse(ringtone));
168				}
169			}
170			mBuilder.setSmallIcon(R.drawable.ic_notification);
171			mBuilder.setDeleteIntent(createDeleteIntent());
172			mBuilder.setLights(0xffffffff, 2000, 4000);
173			Notification notification = mBuilder.build();
174			notificationManager.notify(NOTIFICATION_ID, notification);
175		}
176	}
177
178	private Builder buildMultipleConversation() {
179		Builder mBuilder = new NotificationCompat.Builder(
180				mXmppConnectionService);
181		NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
182		style.setBigContentTitle(notifications.size()
183				+ " "
184				+ mXmppConnectionService
185				.getString(R.string.unread_conversations));
186		StringBuilder names = new StringBuilder();
187		Conversation conversation = null;
188		for (ArrayList<Message> messages : notifications.values()) {
189			if (messages.size() > 0) {
190				conversation = messages.get(0).getConversation();
191				String name = conversation.getName();
192				style.addLine(Html.fromHtml("<b>" + name + "</b> "
193							+ getReadableBody(messages.get(0))));
194				names.append(name);
195				names.append(", ");
196			}
197		}
198		if (names.length() >= 2) {
199			names.delete(names.length() - 2, names.length());
200		}
201		mBuilder.setContentTitle(notifications.size()
202				+ " "
203				+ mXmppConnectionService
204				.getString(R.string.unread_conversations));
205		mBuilder.setContentText(names.toString());
206		mBuilder.setStyle(style);
207		if (conversation != null) {
208			mBuilder.setContentIntent(createContentIntent(conversation
209						.getUuid()));
210		}
211		return mBuilder;
212	}
213
214	private Builder buildSingleConversations(boolean notify) {
215		Builder mBuilder = new NotificationCompat.Builder(
216				mXmppConnectionService);
217		ArrayList<Message> messages = notifications.values().iterator().next();
218		if (messages.size() >= 1) {
219			Conversation conversation = messages.get(0).getConversation();
220			mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
221					.get(conversation, getPixel(64)));
222			mBuilder.setContentTitle(conversation.getName());
223			Message message;
224			if ((message = getImage(messages)) != null) {
225				modifyForImage(mBuilder, message, messages, notify);
226			} else {
227				modifyForTextOnly(mBuilder, messages, notify);
228			}
229			mBuilder.setContentIntent(createContentIntent(conversation
230						.getUuid()));
231		}
232		return mBuilder;
233
234	}
235
236	private void modifyForImage(Builder builder, Message message,
237			ArrayList<Message> messages, boolean notify) {
238		try {
239			Bitmap bitmap = mXmppConnectionService.getFileBackend()
240				.getThumbnail(message, getPixel(288), false);
241			ArrayList<Message> tmp = new ArrayList<>();
242			for (Message msg : messages) {
243				if (msg.getType() == Message.TYPE_TEXT
244						&& msg.getDownloadable() == null) {
245					tmp.add(msg);
246						}
247			}
248			BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
249			bigPictureStyle.bigPicture(bitmap);
250			if (tmp.size() > 0) {
251				bigPictureStyle.setSummaryText(getMergedBodies(tmp));
252				builder.setContentText(getReadableBody(tmp.get(0)));
253			} else {
254				builder.setContentText(mXmppConnectionService.getString(R.string.image_file));
255			}
256			builder.setStyle(bigPictureStyle);
257		} catch (FileNotFoundException e) {
258			modifyForTextOnly(builder, messages, notify);
259		}
260	}
261
262	private void modifyForTextOnly(Builder builder,
263			ArrayList<Message> messages, boolean notify) {
264		builder.setStyle(new NotificationCompat.BigTextStyle()
265				.bigText(getMergedBodies(messages)));
266		builder.setContentText(getReadableBody(messages.get(0)));
267		if (notify) {
268			builder.setTicker(getReadableBody(messages.get(messages.size() - 1)));
269		}
270	}
271
272	private Message getImage(ArrayList<Message> messages) {
273		for (Message message : messages) {
274			if (message.getType() == Message.TYPE_IMAGE
275					&& message.getDownloadable() == null
276					&& message.getEncryption() != Message.ENCRYPTION_PGP) {
277				return message;
278					}
279		}
280		return null;
281	}
282
283	private String getMergedBodies(ArrayList<Message> messages) {
284		StringBuilder text = new StringBuilder();
285		for (int i = 0; i < messages.size(); ++i) {
286			text.append(getReadableBody(messages.get(i)));
287			if (i != messages.size() - 1) {
288				text.append("\n");
289			}
290		}
291		return text.toString();
292	}
293
294	private String getReadableBody(Message message) {
295		if (message.getDownloadable() != null
296				&& (message.getDownloadable().getStatus() == Downloadable.STATUS_OFFER || message
297					.getDownloadable().getStatus() == Downloadable.STATUS_OFFER_CHECK_FILESIZE)) {
298			if (message.getType() == Message.TYPE_FILE) {
299				return mXmppConnectionService.getString(R.string.file_offered_for_download);
300			} else {
301				return mXmppConnectionService.getText(
302						R.string.image_offered_for_download).toString();
303			}
304		} else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
305			return mXmppConnectionService.getText(
306					R.string.encrypted_message_received).toString();
307		} else if (message.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
308			return mXmppConnectionService.getText(R.string.decryption_failed)
309				.toString();
310		} else if (message.getType() == Message.TYPE_FILE) {
311			DownloadableFile file = mXmppConnectionService.getFileBackend().getFile(message);
312			return mXmppConnectionService.getString(R.string.file,file.getMimeType());
313		} else if (message.getType() == Message.TYPE_IMAGE) {
314			return mXmppConnectionService.getText(R.string.image_file)
315				.toString();
316		} else {
317			return message.getBody().trim();
318		}
319	}
320
321	private PendingIntent createContentIntent(String conversationUuid) {
322		TaskStackBuilder stackBuilder = TaskStackBuilder
323			.create(mXmppConnectionService);
324		stackBuilder.addParentStack(ConversationActivity.class);
325
326		Intent viewConversationIntent = new Intent(mXmppConnectionService,
327				ConversationActivity.class);
328		viewConversationIntent.setAction(Intent.ACTION_VIEW);
329		if (conversationUuid!=null) {
330			viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
331					conversationUuid);
332			viewConversationIntent.setType(ConversationActivity.VIEW_CONVERSATION);
333		}
334
335		stackBuilder.addNextIntent(viewConversationIntent);
336
337		return stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
338	}
339
340	private PendingIntent createDeleteIntent() {
341		Intent intent = new Intent(mXmppConnectionService,
342				XmppConnectionService.class);
343		intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
344		return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
345	}
346
347	private PendingIntent createDisableForeground() {
348		Intent intent = new Intent(mXmppConnectionService,
349				XmppConnectionService.class);
350		intent.setAction(XmppConnectionService.ACTION_DISABLE_FOREGROUND);
351		return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
352	}
353
354	private boolean wasHighlightedOrPrivate(Message message) {
355		String nick = message.getConversation().getMucOptions().getActualNick();
356		Pattern highlight = generateNickHighlightPattern(nick);
357		if (message.getBody() == null || nick == null) {
358			return false;
359		}
360		Matcher m = highlight.matcher(message.getBody());
361		return (m.find() || message.getType() == Message.TYPE_PRIVATE);
362	}
363
364	private static Pattern generateNickHighlightPattern(String nick) {
365		// We expect a word boundary, i.e. space or start of string, followed by
366		// the
367		// nick (matched in case-insensitive manner), followed by optional
368		// punctuation (for example "bob: i disagree" or "how are you alice?"),
369		// followed by another word boundary.
370		return Pattern.compile("\\b" + nick + "\\p{Punct}?\\b",
371				Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
372	}
373
374	public void setOpenConversation(Conversation conversation) {
375		this.mOpenConversation = conversation;
376	}
377
378	public void setIsInForeground(boolean foreground) {
379		this.mIsInForeground = foreground;
380	}
381
382	private int getPixel(int dp) {
383		DisplayMetrics metrics = mXmppConnectionService.getResources()
384			.getDisplayMetrics();
385		return ((int) (dp * metrics.density));
386	}
387
388	private void markLastNotification() {
389		this.mLastNotification = SystemClock.elapsedRealtime();
390	}
391
392	private boolean inMiniGracePeriod(Account account) {
393		int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
394			: Config.MINI_GRACE_PERIOD * 2;
395		return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
396	}
397
398	public Notification createForegroundNotification() {
399		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
400		mBuilder.setSmallIcon(R.drawable.ic_stat_communication_import_export);
401		mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.conversations_foreground_service));
402		mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_disable));
403		mBuilder.setContentIntent(createDisableForeground());
404		mBuilder.setWhen(0);
405		mBuilder.setPriority(NotificationCompat.PRIORITY_MIN);
406		return mBuilder.build();
407	}
408
409	public void updateErrorNotification() {
410		NotificationManager mNotificationManager = (NotificationManager) mXmppConnectionService.getSystemService(Context.NOTIFICATION_SERVICE);
411		List<Account> errors = new ArrayList<>();
412		for (Account account : mXmppConnectionService.getAccounts()) {
413			if (account.hasErrorStatus()) {
414				errors.add(account);
415			}
416		}
417		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
418		if (errors.size() == 0) {
419			mNotificationManager.cancel(ERROR_NOTIFICATION_ID);
420			return;
421		} else if (errors.size() == 1) {
422			mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
423			mBuilder.setContentText(errors.get(0).getJid().toBareJid().toString());
424		} else {
425			mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
426			mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
427		}
428		mBuilder.setOngoing(true);
429		mBuilder.setLights(0xffffffff, 2000, 4000);
430		mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
431		TaskStackBuilder stackBuilder = TaskStackBuilder.create(mXmppConnectionService);
432		stackBuilder.addParentStack(ConversationActivity.class);
433
434		Intent manageAccountsIntent = new Intent(mXmppConnectionService,ManageAccountActivity.class);
435		stackBuilder.addNextIntent(manageAccountsIntent);
436
437		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
438
439		mBuilder.setContentIntent(resultPendingIntent);
440		Notification notification = mBuilder.build();
441		mNotificationManager.notify(ERROR_NOTIFICATION_ID, notification);
442	}
443}