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