1package eu.siacs.conversations.services;
2
3import android.annotation.SuppressLint;
4import android.app.Notification;
5import android.app.NotificationManager;
6import android.app.PendingIntent;
7import android.content.Context;
8import android.content.Intent;
9import android.content.SharedPreferences;
10import android.graphics.Bitmap;
11import android.net.Uri;
12import android.os.Build;
13import android.os.PowerManager;
14import android.os.SystemClock;
15import android.support.v4.app.NotificationCompat;
16import android.support.v4.app.NotificationCompat.BigPictureStyle;
17import android.support.v4.app.NotificationCompat.Builder;
18import android.support.v4.app.TaskStackBuilder;
19import android.text.Html;
20import android.util.DisplayMetrics;
21
22import org.json.JSONArray;
23import org.json.JSONObject;
24
25import java.io.FileNotFoundException;
26import java.util.ArrayList;
27import java.util.Calendar;
28import java.util.HashMap;
29import java.util.LinkedHashMap;
30import java.util.List;
31import java.util.regex.Matcher;
32import java.util.regex.Pattern;
33
34import eu.siacs.conversations.Config;
35import eu.siacs.conversations.R;
36import eu.siacs.conversations.entities.Account;
37import eu.siacs.conversations.entities.Conversation;
38import eu.siacs.conversations.entities.Message;
39import eu.siacs.conversations.ui.ConversationActivity;
40import eu.siacs.conversations.ui.ManageAccountActivity;
41import eu.siacs.conversations.ui.TimePreference;
42import eu.siacs.conversations.utils.GeoHelper;
43import eu.siacs.conversations.utils.UIHelper;
44
45public class NotificationService {
46
47 private final 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(final 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(final Message message) {
74 final Intent i = new Intent("com.getpebble.action.SEND_NOTIFICATION");
75
76 final Conversation conversation = message.getConversation();
77 final JSONObject jsonData = new JSONObject(new HashMap<String, String>(2) {{
78 put("title", conversation.getName());
79 put("body", message.getBody());
80 }});
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 // notify Pebble App
87 i.setPackage("com.getpebble.android");
88 mXmppConnectionService.sendBroadcast(i);
89 // notify Gadgetbridge
90 i.setPackage("nodomain.freeyourgadget.gadgetbridge");
91 mXmppConnectionService.sendBroadcast(i);
92 }
93
94
95 public boolean notificationsEnabled() {
96 return mXmppConnectionService.getPreferences().getBoolean("show_notification", true);
97 }
98
99 public boolean isQuietHours() {
100 if (!mXmppConnectionService.getPreferences().getBoolean("enable_quiet_hours", false)) {
101 return false;
102 }
103 final long startTime = mXmppConnectionService.getPreferences().getLong("quiet_hours_start", TimePreference.DEFAULT_VALUE) % Config.MILLISECONDS_IN_DAY;
104 final long endTime = mXmppConnectionService.getPreferences().getLong("quiet_hours_end", TimePreference.DEFAULT_VALUE) % Config.MILLISECONDS_IN_DAY;
105 final long nowTime = Calendar.getInstance().getTimeInMillis() % Config.MILLISECONDS_IN_DAY;
106
107 if (endTime < startTime) {
108 return nowTime > startTime || nowTime < endTime;
109 } else {
110 return nowTime > startTime && nowTime < endTime;
111 }
112 }
113
114 public boolean conferenceNotificationsEnabled() {
115 return mXmppConnectionService.getPreferences().getBoolean("always_notify_in_conference", false);
116 }
117
118 @SuppressLint("NewApi")
119 @SuppressWarnings("deprecation")
120 private boolean isInteractive() {
121 final PowerManager pm = (PowerManager) mXmppConnectionService
122 .getSystemService(Context.POWER_SERVICE);
123
124 final boolean isScreenOn;
125 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
126 isScreenOn = pm.isScreenOn();
127 } else {
128 isScreenOn = pm.isInteractive();
129 }
130
131 return isScreenOn;
132 }
133
134 public void push(final Message message) {
135 mXmppConnectionService.updateUnreadCountBadge();
136 if (!notify(message)) {
137 return;
138 }
139
140 final boolean isScreenOn = isInteractive();
141
142 if (this.mIsInForeground && isScreenOn && this.mOpenConversation == message.getConversation()) {
143 return;
144 }
145
146 synchronized (notifications) {
147 final String conversationUuid = message.getConversationUuid();
148 if (notifications.containsKey(conversationUuid)) {
149 notifications.get(conversationUuid).add(message);
150 } else {
151 final ArrayList<Message> mList = new ArrayList<>();
152 mList.add(message);
153 notifications.put(conversationUuid, mList);
154 }
155 final Account account = message.getConversation().getAccount();
156 final boolean doNotify = (!(this.mIsInForeground && this.mOpenConversation == null) || !isScreenOn)
157 && !account.inGracePeriod()
158 && !this.inMiniGracePeriod(account);
159 updateNotification(doNotify);
160 if (doNotify) {
161 notifyPebble(message);
162 }
163 }
164 }
165
166 public void clear() {
167 synchronized (notifications) {
168 notifications.clear();
169 updateNotification(false);
170 }
171 }
172
173 public void clear(final Conversation conversation) {
174 synchronized (notifications) {
175 notifications.remove(conversation.getUuid());
176 updateNotification(false);
177 }
178 }
179
180 private void setNotificationColor(final Builder mBuilder) {
181 mBuilder.setColor(mXmppConnectionService.getResources().getColor(R.color.green500));
182 }
183
184 private void updateNotification(final boolean notify) {
185 final NotificationManager notificationManager = (NotificationManager) mXmppConnectionService
186 .getSystemService(Context.NOTIFICATION_SERVICE);
187 final SharedPreferences preferences = mXmppConnectionService.getPreferences();
188
189 final String ringtone = preferences.getString("notification_ringtone", null);
190 final boolean vibrate = preferences.getBoolean("vibrate_on_notification", true);
191
192 if (notifications.size() == 0) {
193 notificationManager.cancel(NOTIFICATION_ID);
194 } else {
195 if (notify) {
196 this.markLastNotification();
197 }
198 final Builder mBuilder;
199 if (notifications.size() == 1) {
200 mBuilder = buildSingleConversations(notify);
201 } else {
202 mBuilder = buildMultipleConversation();
203 }
204 if (notify && !isQuietHours()) {
205 if (vibrate) {
206 final int dat = 70;
207 final long[] pattern = {0, 3 * dat, dat, dat};
208 mBuilder.setVibrate(pattern);
209 }
210 if (ringtone != null) {
211 mBuilder.setSound(Uri.parse(ringtone));
212 }
213 }
214 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
215 mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
216 }
217 setNotificationColor(mBuilder);
218 mBuilder.setDefaults(0);
219 mBuilder.setSmallIcon(R.drawable.ic_notification);
220 mBuilder.setDeleteIntent(createDeleteIntent());
221 mBuilder.setLights(0xff00FF00, 2000, 3000);
222 final Notification notification = mBuilder.build();
223 notificationManager.notify(NOTIFICATION_ID, notification);
224 }
225 }
226
227 private Builder buildMultipleConversation() {
228 final Builder mBuilder = new NotificationCompat.Builder(
229 mXmppConnectionService);
230 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
231 style.setBigContentTitle(notifications.size()
232 + " "
233 + mXmppConnectionService
234 .getString(R.string.unread_conversations));
235 final StringBuilder names = new StringBuilder();
236 Conversation conversation = null;
237 for (final ArrayList<Message> messages : notifications.values()) {
238 if (messages.size() > 0) {
239 conversation = messages.get(0).getConversation();
240 final String name = conversation.getName();
241 style.addLine(Html.fromHtml("<b>" + name + "</b> "
242 + UIHelper.getMessagePreview(mXmppConnectionService,messages.get(0)).first));
243 names.append(name);
244 names.append(", ");
245 }
246 }
247 if (names.length() >= 2) {
248 names.delete(names.length() - 2, names.length());
249 }
250 mBuilder.setContentTitle(notifications.size()
251 + " "
252 + mXmppConnectionService
253 .getString(R.string.unread_conversations));
254 mBuilder.setContentText(names.toString());
255 mBuilder.setStyle(style);
256 if (conversation != null) {
257 mBuilder.setContentIntent(createContentIntent(conversation));
258 }
259 return mBuilder;
260 }
261
262 private Builder buildSingleConversations(final boolean notify) {
263 final Builder mBuilder = new NotificationCompat.Builder(
264 mXmppConnectionService);
265 final ArrayList<Message> messages = notifications.values().iterator().next();
266 if (messages.size() >= 1) {
267 final Conversation conversation = messages.get(0).getConversation();
268 mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
269 .get(conversation, getPixel(64)));
270 mBuilder.setContentTitle(conversation.getName());
271 Message message;
272 if ((message = getImage(messages)) != null) {
273 modifyForImage(mBuilder, message, messages, notify);
274 } else {
275 modifyForTextOnly(mBuilder, messages, notify);
276 }
277 if ((message = getFirstDownloadableMessage(messages)) != null) {
278 mBuilder.addAction(
279 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ?
280 R.drawable.ic_file_download_white_24dp : R.drawable.ic_action_download,
281 mXmppConnectionService.getResources().getString(R.string.download_x_file,
282 UIHelper.getFileDescriptionString(mXmppConnectionService, message)),
283 createDownloadIntent(message)
284 );
285 }
286 if ((message = getFirstLocationMessage(messages)) != null) {
287 mBuilder.addAction(R.drawable.ic_room_white_24dp,
288 mXmppConnectionService.getString(R.string.show_location),
289 createShowLocationIntent(message));
290 }
291 mBuilder.setContentIntent(createContentIntent(conversation));
292 }
293 return mBuilder;
294 }
295
296 private void modifyForImage(final Builder builder, final Message message,
297 final ArrayList<Message> messages, final boolean notify) {
298 try {
299 final Bitmap bitmap = mXmppConnectionService.getFileBackend()
300 .getThumbnail(message, getPixel(288), false);
301 final ArrayList<Message> tmp = new ArrayList<>();
302 for (final Message msg : messages) {
303 if (msg.getType() == Message.TYPE_TEXT
304 && msg.getTransferable() == null) {
305 tmp.add(msg);
306 }
307 }
308 final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
309 bigPictureStyle.bigPicture(bitmap);
310 if (tmp.size() > 0) {
311 bigPictureStyle.setSummaryText(getMergedBodies(tmp));
312 builder.setContentText(UIHelper.getMessagePreview(mXmppConnectionService,tmp.get(0)).first);
313 } else {
314 builder.setContentText(mXmppConnectionService.getString(
315 R.string.received_x_file,
316 UIHelper.getFileDescriptionString(mXmppConnectionService,message)));
317 }
318 builder.setStyle(bigPictureStyle);
319 } catch (final FileNotFoundException e) {
320 modifyForTextOnly(builder, messages, notify);
321 }
322 }
323
324 private void modifyForTextOnly(final Builder builder,
325 final ArrayList<Message> messages, final boolean notify) {
326 builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
327 builder.setContentText(UIHelper.getMessagePreview(mXmppConnectionService,messages.get(0)).first);
328 if (notify) {
329 builder.setTicker(UIHelper.getMessagePreview(mXmppConnectionService,messages.get(messages.size() - 1)).first);
330 }
331 }
332
333 private Message getImage(final Iterable<Message> messages) {
334 for (final Message message : messages) {
335 if (message.getType() == Message.TYPE_IMAGE
336 && message.getTransferable() == null
337 && message.getEncryption() != Message.ENCRYPTION_PGP) {
338 return message;
339 }
340 }
341 return null;
342 }
343
344 private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
345 for (final Message message : messages) {
346 if ((message.getType() == Message.TYPE_FILE || message.getType() == Message.TYPE_IMAGE) &&
347 message.getTransferable() != null) {
348 return message;
349 }
350 }
351 return null;
352 }
353
354 private Message getFirstLocationMessage(final Iterable<Message> messages) {
355 for(final Message message : messages) {
356 if (GeoHelper.isGeoUri(message.getBody())) {
357 return message;
358 }
359 }
360 return null;
361 }
362
363 private CharSequence getMergedBodies(final ArrayList<Message> messages) {
364 final StringBuilder text = new StringBuilder();
365 for (int i = 0; i < messages.size(); ++i) {
366 text.append(UIHelper.getMessagePreview(mXmppConnectionService,messages.get(i)).first);
367 if (i != messages.size() - 1) {
368 text.append("\n");
369 }
370 }
371 return text.toString();
372 }
373
374 private PendingIntent createShowLocationIntent(final Message message) {
375 Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(message);
376 for(Intent intent : intents) {
377 if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
378 return PendingIntent.getActivity(mXmppConnectionService,18,intent,PendingIntent.FLAG_UPDATE_CURRENT);
379 }
380 }
381 return createOpenConversationsIntent();
382 }
383
384 private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
385 final TaskStackBuilder stackBuilder = TaskStackBuilder
386 .create(mXmppConnectionService);
387 stackBuilder.addParentStack(ConversationActivity.class);
388
389 final Intent viewConversationIntent = new Intent(mXmppConnectionService,
390 ConversationActivity.class);
391 if (downloadMessageUuid != null) {
392 viewConversationIntent.setAction(ConversationActivity.ACTION_DOWNLOAD);
393 } else {
394 viewConversationIntent.setAction(Intent.ACTION_VIEW);
395 }
396 if (conversationUuid != null) {
397 viewConversationIntent.putExtra(ConversationActivity.CONVERSATION, conversationUuid);
398 viewConversationIntent.setType(ConversationActivity.VIEW_CONVERSATION);
399 }
400 if (downloadMessageUuid != null) {
401 viewConversationIntent.putExtra(ConversationActivity.MESSAGE, downloadMessageUuid);
402 }
403
404 stackBuilder.addNextIntent(viewConversationIntent);
405
406 return stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
407 }
408
409 private PendingIntent createDownloadIntent(final Message message) {
410 return createContentIntent(message.getConversationUuid(), message.getUuid());
411 }
412
413 private PendingIntent createContentIntent(final Conversation conversation) {
414 return createContentIntent(conversation.getUuid(), null);
415 }
416
417 private PendingIntent createDeleteIntent() {
418 final Intent intent = new Intent(mXmppConnectionService,
419 XmppConnectionService.class);
420 intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
421 return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
422 }
423
424 private PendingIntent createDisableForeground() {
425 final Intent intent = new Intent(mXmppConnectionService,
426 XmppConnectionService.class);
427 intent.setAction(XmppConnectionService.ACTION_DISABLE_FOREGROUND);
428 return PendingIntent.getService(mXmppConnectionService, 34, intent, 0);
429 }
430
431 private PendingIntent createTryAgainIntent() {
432 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
433 intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
434 return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
435 }
436
437 private PendingIntent createDisableAccountIntent(final Account account) {
438 final Intent intent = new Intent(mXmppConnectionService,XmppConnectionService.class);
439 intent.setAction(XmppConnectionService.ACTION_DISABLE_ACCOUNT);
440 intent.putExtra("account",account.getJid().toBareJid().toString());
441 return PendingIntent.getService(mXmppConnectionService,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
442 }
443
444 private boolean wasHighlightedOrPrivate(final Message message) {
445 final String nick = message.getConversation().getMucOptions().getActualNick();
446 final Pattern highlight = generateNickHighlightPattern(nick);
447 if (message.getBody() == null || nick == null) {
448 return false;
449 }
450 final Matcher m = highlight.matcher(message.getBody());
451 return (m.find() || message.getType() == Message.TYPE_PRIVATE);
452 }
453
454 private static Pattern generateNickHighlightPattern(final String nick) {
455 // We expect a word boundary, i.e. space or start of string, followed by
456 // the
457 // nick (matched in case-insensitive manner), followed by optional
458 // punctuation (for example "bob: i disagree" or "how are you alice?"),
459 // followed by another word boundary.
460 return Pattern.compile("\\b" + Pattern.quote(nick) + "\\p{Punct}?\\b",
461 Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
462 }
463
464 public void setOpenConversation(final Conversation conversation) {
465 this.mOpenConversation = conversation;
466 }
467
468 public void setIsInForeground(final boolean foreground) {
469 this.mIsInForeground = foreground;
470 }
471
472 private int getPixel(final int dp) {
473 final DisplayMetrics metrics = mXmppConnectionService.getResources()
474 .getDisplayMetrics();
475 return ((int) (dp * metrics.density));
476 }
477
478 private void markLastNotification() {
479 this.mLastNotification = SystemClock.elapsedRealtime();
480 }
481
482 private boolean inMiniGracePeriod(final Account account) {
483 final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
484 : Config.MINI_GRACE_PERIOD * 2;
485 return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
486 }
487
488 public Notification createForegroundNotification() {
489 final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
490
491 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.conversations_foreground_service));
492 mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_open_conversations));
493 mBuilder.setContentIntent(createOpenConversationsIntent());
494 mBuilder.setWhen(0);
495 mBuilder.setPriority(NotificationCompat.PRIORITY_MIN);
496 final int cancelIcon;
497 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
498 mBuilder.setCategory(Notification.CATEGORY_SERVICE);
499 mBuilder.setSmallIcon(R.drawable.ic_import_export_white_24dp);
500 cancelIcon = R.drawable.ic_cancel_white_24dp;
501 } else {
502 mBuilder.setSmallIcon(R.drawable.ic_stat_communication_import_export);
503 cancelIcon = R.drawable.ic_action_cancel;
504 }
505 mBuilder.addAction(cancelIcon,
506 mXmppConnectionService.getString(R.string.disable_foreground_service),
507 createDisableForeground());
508 setNotificationColor(mBuilder);
509 return mBuilder.build();
510 }
511
512 private PendingIntent createOpenConversationsIntent() {
513 return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService,ConversationActivity.class),0);
514 }
515
516 public void updateErrorNotification() {
517 final NotificationManager mNotificationManager = (NotificationManager) mXmppConnectionService.getSystemService(Context.NOTIFICATION_SERVICE);
518 final List<Account> errors = new ArrayList<>();
519 for (final Account account : mXmppConnectionService.getAccounts()) {
520 if (account.hasErrorStatus()) {
521 errors.add(account);
522 }
523 }
524 final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
525 if (errors.size() == 0) {
526 mNotificationManager.cancel(ERROR_NOTIFICATION_ID);
527 return;
528 } else if (errors.size() == 1) {
529 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
530 mBuilder.setContentText(errors.get(0).getJid().toBareJid().toString());
531 } else {
532 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
533 mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
534 }
535 mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
536 mXmppConnectionService.getString(R.string.try_again),
537 createTryAgainIntent());
538 if (errors.size() == 1) {
539 mBuilder.addAction(R.drawable.ic_block_white_24dp,
540 mXmppConnectionService.getString(R.string.disable_account),
541 createDisableAccountIntent(errors.get(0)));
542 }
543 mBuilder.setOngoing(true);
544 //mBuilder.setLights(0xffffffff, 2000, 4000);
545 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
546 mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
547 } else {
548 mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
549 }
550 final TaskStackBuilder stackBuilder = TaskStackBuilder.create(mXmppConnectionService);
551 stackBuilder.addParentStack(ConversationActivity.class);
552
553 final Intent manageAccountsIntent = new Intent(mXmppConnectionService,ManageAccountActivity.class);
554 stackBuilder.addNextIntent(manageAccountsIntent);
555
556 final PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
557
558 mBuilder.setContentIntent(resultPendingIntent);
559 mNotificationManager.notify(ERROR_NOTIFICATION_ID, mBuilder.build());
560 }
561}