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