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.DownloadableFile;
32import eu.siacs.conversations.entities.Message;
33import eu.siacs.conversations.ui.ConversationActivity;
34
35public class NotificationService {
36
37 private XmppConnectionService mXmppConnectionService;
38
39 private LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<String, ArrayList<Message>>();
40
41 public static int NOTIFICATION_ID = 0x2342;
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 if (message.getType() == Message.TYPE_FILE) {
271 return mXmppConnectionService.getString(R.string.file_offered_for_download);
272 } else {
273 return mXmppConnectionService.getText(
274 R.string.image_offered_for_download).toString();
275 }
276 } else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
277 return mXmppConnectionService.getText(
278 R.string.encrypted_message_received).toString();
279 } else if (message.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
280 return mXmppConnectionService.getText(R.string.decryption_failed)
281 .toString();
282 } else if (message.getType() == Message.TYPE_FILE) {
283 DownloadableFile file = mXmppConnectionService.getFileBackend().getFile(message);
284 return mXmppConnectionService.getString(R.string.file,file.getMimeType());
285 } else if (message.getType() == Message.TYPE_IMAGE) {
286 return mXmppConnectionService.getText(R.string.image_file)
287 .toString();
288 } else {
289 return message.getBody().trim();
290 }
291 }
292
293 private PendingIntent createContentIntent(String conversationUuid) {
294 TaskStackBuilder stackBuilder = TaskStackBuilder
295 .create(mXmppConnectionService);
296 stackBuilder.addParentStack(ConversationActivity.class);
297
298 Intent viewConversationIntent = new Intent(mXmppConnectionService,
299 ConversationActivity.class);
300 viewConversationIntent.setAction(Intent.ACTION_VIEW);
301 viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
302 conversationUuid);
303 viewConversationIntent.setType(ConversationActivity.VIEW_CONVERSATION);
304
305 stackBuilder.addNextIntent(viewConversationIntent);
306
307 PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
308 PendingIntent.FLAG_UPDATE_CURRENT);
309 return resultPendingIntent;
310 }
311
312 private PendingIntent createDeleteIntent() {
313 Intent intent = new Intent(mXmppConnectionService,
314 XmppConnectionService.class);
315 intent.setAction("clear_notification");
316 return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
317 }
318
319 private boolean wasHighlightedOrPrivate(Message message) {
320 String nick = message.getConversation().getMucOptions().getActualNick();
321 Pattern highlight = generateNickHighlightPattern(nick);
322 if (message.getBody() == null || nick == null) {
323 return false;
324 }
325 Matcher m = highlight.matcher(message.getBody());
326 return (m.find() || message.getType() == Message.TYPE_PRIVATE);
327 }
328
329 private static Pattern generateNickHighlightPattern(String nick) {
330 // We expect a word boundary, i.e. space or start of string, followed by
331 // the
332 // nick (matched in case-insensitive manner), followed by optional
333 // punctuation (for example "bob: i disagree" or "how are you alice?"),
334 // followed by another word boundary.
335 return Pattern.compile("\\b" + nick + "\\p{Punct}?\\b",
336 Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
337 }
338
339 public void setOpenConversation(Conversation conversation) {
340 this.mOpenConversation = conversation;
341 }
342
343 public void setIsInForeground(boolean foreground) {
344 this.mIsInForeground = foreground;
345 }
346
347 private int getPixel(int dp) {
348 DisplayMetrics metrics = mXmppConnectionService.getResources()
349 .getDisplayMetrics();
350 return ((int) (dp * metrics.density));
351 }
352
353 private void markLastNotification() {
354 this.mLastNotification = SystemClock.elapsedRealtime();
355 }
356
357 private boolean inMiniGracePeriod(Account account) {
358 int miniGrace = account.getStatus() == Account.STATUS_ONLINE ? Config.MINI_GRACE_PERIOD
359 : Config.MINI_GRACE_PERIOD * 2;
360 return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
361 }
362}