NotificationService.java

  1package eu.siacs.conversations.services;
  2
  3import java.util.ArrayList;
  4import java.util.LinkedHashMap;
  5import java.util.regex.Matcher;
  6import java.util.regex.Pattern;
  7
  8import android.app.Notification;
  9import android.app.NotificationManager;
 10import android.app.PendingIntent;
 11import android.content.Context;
 12import android.content.Intent;
 13import android.content.SharedPreferences;
 14import android.net.Uri;
 15import android.os.PowerManager;
 16import android.support.v4.app.NotificationCompat;
 17import android.support.v4.app.TaskStackBuilder;
 18import android.text.Html;
 19import android.util.DisplayMetrics;
 20
 21import eu.siacs.conversations.R;
 22import eu.siacs.conversations.entities.Account;
 23import eu.siacs.conversations.entities.Conversation;
 24import eu.siacs.conversations.entities.Message;
 25import eu.siacs.conversations.ui.ConversationActivity;
 26
 27public class NotificationService {
 28
 29	private XmppConnectionService mXmppConnectionService;
 30
 31	private LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<String, ArrayList<Message>>();
 32
 33	public int NOTIFICATION_ID = 0x2342;
 34	private Conversation mOpenConversation;
 35	private boolean mIsInForeground;
 36
 37	public NotificationService(XmppConnectionService service) {
 38		this.mXmppConnectionService = service;
 39	}
 40
 41	public void push(Message message) {
 42		PowerManager pm = (PowerManager) mXmppConnectionService
 43				.getSystemService(Context.POWER_SERVICE);
 44		boolean isScreenOn = pm.isScreenOn();
 45
 46		if (this.mIsInForeground && isScreenOn
 47				&& this.mOpenConversation == message.getConversation()) {
 48			return;
 49		}
 50		synchronized (notifications) {
 51			String conversationUuid = message.getConversationUuid();
 52			if (notifications.containsKey(conversationUuid)) {
 53				notifications.get(conversationUuid).add(message);
 54			} else {
 55				ArrayList<Message> mList = new ArrayList<Message>();
 56				mList.add(message);
 57				notifications.put(conversationUuid, mList);
 58			}
 59		}
 60		Account account = message.getConversation().getAccount();
 61		updateNotification((!(this.mIsInForeground && this.mOpenConversation == null) || !isScreenOn)
 62				&& !account.inGracePeriod());
 63	}
 64
 65	public void clear() {
 66		synchronized (notifications) {
 67			notifications.clear();
 68		}
 69		updateNotification(false);
 70	}
 71
 72	public void clear(Conversation conversation) {
 73		synchronized (notifications) {
 74			notifications.remove(conversation.getUuid());
 75		}
 76		updateNotification(false);
 77	}
 78
 79	private void updateNotification(boolean notify) {
 80		NotificationManager notificationManager = (NotificationManager) mXmppConnectionService
 81				.getSystemService(Context.NOTIFICATION_SERVICE);
 82		SharedPreferences preferences = mXmppConnectionService.getPreferences();
 83
 84		String ringtone = preferences.getString("notification_ringtone", null);
 85		boolean vibrate = preferences.getBoolean("vibrate_on_notification",
 86				true);
 87
 88		if (notifications.size() == 0) {
 89			notificationManager.cancel(NOTIFICATION_ID);
 90		} else {
 91			NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
 92					mXmppConnectionService);
 93			mBuilder.setSmallIcon(R.drawable.ic_notification);
 94			if (notifications.size() == 1) {
 95				ArrayList<Message> messages = notifications.values().iterator()
 96						.next();
 97				if (messages.size() >= 1) {
 98					Conversation conversation = messages.get(0)
 99							.getConversation();
100					mBuilder.setLargeIcon(mXmppConnectionService
101							.getAvatarService().get(conversation, getPixel(64)));
102					mBuilder.setContentTitle(conversation.getName());
103					StringBuilder text = new StringBuilder();
104					for (int i = 0; i < messages.size(); ++i) {
105						text.append(messages.get(i).getReadableBody(
106								mXmppConnectionService));
107						if (i != messages.size() - 1) {
108							text.append("\n");
109						}
110					}
111					mBuilder.setStyle(new NotificationCompat.BigTextStyle()
112							.bigText(text.toString()));
113					mBuilder.setContentText(messages.get(0).getReadableBody(
114							mXmppConnectionService));
115					if (notify) {
116						mBuilder.setTicker(messages.get(messages.size() - 1)
117								.getReadableBody(mXmppConnectionService));
118					}
119					mBuilder.setContentIntent(createContentIntent(conversation
120							.getUuid()));
121				} else {
122					notificationManager.cancel(NOTIFICATION_ID);
123					return;
124				}
125			} else {
126				NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
127				style.setBigContentTitle(notifications.size()
128						+ " "
129						+ mXmppConnectionService
130								.getString(R.string.unread_conversations));
131				StringBuilder names = new StringBuilder();
132				Conversation conversation = null;
133				for (ArrayList<Message> messages : notifications.values()) {
134					if (messages.size() > 0) {
135						conversation = messages.get(0).getConversation();
136						String name = conversation.getName();
137						style.addLine(Html.fromHtml("<b>"
138								+ name
139								+ "</b> "
140								+ messages.get(0).getReadableBody(
141										mXmppConnectionService)));
142						names.append(name);
143						names.append(", ");
144					}
145				}
146				if (names.length() >= 2) {
147					names.delete(names.length() - 2, names.length());
148				}
149				mBuilder.setContentTitle(notifications.size()
150						+ " "
151						+ mXmppConnectionService
152								.getString(R.string.unread_conversations));
153				mBuilder.setContentText(names.toString());
154				mBuilder.setStyle(style);
155				if (conversation != null) {
156					mBuilder.setContentIntent(createContentIntent(conversation
157							.getUuid()));
158				}
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.setDeleteIntent(createDeleteIntent());
171			mBuilder.setLights(0xffffffff, 2000, 4000);
172			Notification notification = mBuilder.build();
173			notificationManager.notify(NOTIFICATION_ID, notification);
174		}
175	}
176
177	private PendingIntent createContentIntent(String conversationUuid) {
178		TaskStackBuilder stackBuilder = TaskStackBuilder
179				.create(mXmppConnectionService);
180		stackBuilder.addParentStack(ConversationActivity.class);
181
182		Intent viewConversationIntent = new Intent(mXmppConnectionService,
183				ConversationActivity.class);
184		viewConversationIntent.setAction(Intent.ACTION_VIEW);
185		viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
186				conversationUuid);
187		viewConversationIntent.setType(ConversationActivity.VIEW_CONVERSATION);
188
189		stackBuilder.addNextIntent(viewConversationIntent);
190
191		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
192				PendingIntent.FLAG_UPDATE_CURRENT);
193		return resultPendingIntent;
194	}
195
196	private PendingIntent createDeleteIntent() {
197		Intent intent = new Intent(mXmppConnectionService,
198				XmppConnectionService.class);
199		intent.setAction("clear_notification");
200		return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
201	}
202
203	public static boolean wasHighlightedOrPrivate(Message message) {
204		String nick = message.getConversation().getMucOptions().getActualNick();
205		Pattern highlight = generateNickHighlightPattern(nick);
206		if (message.getBody() == null || nick == null) {
207			return false;
208		}
209		Matcher m = highlight.matcher(message.getBody());
210		return (m.find() || message.getType() == Message.TYPE_PRIVATE);
211	}
212
213	private static Pattern generateNickHighlightPattern(String nick) {
214		// We expect a word boundary, i.e. space or start of string, followed by
215		// the
216		// nick (matched in case-insensitive manner), followed by optional
217		// punctuation (for example "bob: i disagree" or "how are you alice?"),
218		// followed by another word boundary.
219		return Pattern.compile("\\b" + nick + "\\p{Punct}?\\b",
220				Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
221	}
222
223	public void setOpenConversation(Conversation conversation) {
224		this.mOpenConversation = conversation;
225	}
226
227	public void setIsInForeground(boolean foreground) {
228		this.mIsInForeground = foreground;
229	}
230
231	private int getPixel(int dp) {
232		DisplayMetrics metrics = mXmppConnectionService.getResources()
233				.getDisplayMetrics();
234		return ((int) (dp * metrics.density));
235	}
236}