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().isPnNA()
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_TEXT
336 && message.getTransferable() == null
337 && message.getEncryption() != Message.ENCRYPTION_PGP
338 && message.getFileParams().height > 0) {
339 return message;
340 }
341 }
342 return null;
343 }
344
345 private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
346 for (final Message message : messages) {
347 if ((message.getType() == Message.TYPE_FILE || message.getType() == Message.TYPE_IMAGE) &&
348 message.getTransferable() != null) {
349 return message;
350 }
351 }
352 return null;
353 }
354
355 private Message getFirstLocationMessage(final Iterable<Message> messages) {
356 for(final Message message : messages) {
357 if (GeoHelper.isGeoUri(message.getBody())) {
358 return message;
359 }
360 }
361 return null;
362 }
363
364 private CharSequence getMergedBodies(final ArrayList<Message> messages) {
365 final StringBuilder text = new StringBuilder();
366 for (int i = 0; i < messages.size(); ++i) {
367 text.append(UIHelper.getMessagePreview(mXmppConnectionService,messages.get(i)).first);
368 if (i != messages.size() - 1) {
369 text.append("\n");
370 }
371 }
372 return text.toString();
373 }
374
375 private PendingIntent createShowLocationIntent(final Message message) {
376 Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(message);
377 for(Intent intent : intents) {
378 if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
379 return PendingIntent.getActivity(mXmppConnectionService,18,intent,PendingIntent.FLAG_UPDATE_CURRENT);
380 }
381 }
382 return createOpenConversationsIntent();
383 }
384
385 private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
386 final TaskStackBuilder stackBuilder = TaskStackBuilder
387 .create(mXmppConnectionService);
388 stackBuilder.addParentStack(ConversationActivity.class);
389
390 final Intent viewConversationIntent = new Intent(mXmppConnectionService,
391 ConversationActivity.class);
392 if (downloadMessageUuid != null) {
393 viewConversationIntent.setAction(ConversationActivity.ACTION_DOWNLOAD);
394 } else {
395 viewConversationIntent.setAction(Intent.ACTION_VIEW);
396 }
397 if (conversationUuid != null) {
398 viewConversationIntent.putExtra(ConversationActivity.CONVERSATION, conversationUuid);
399 viewConversationIntent.setType(ConversationActivity.VIEW_CONVERSATION);
400 }
401 if (downloadMessageUuid != null) {
402 viewConversationIntent.putExtra(ConversationActivity.MESSAGE, downloadMessageUuid);
403 }
404
405 stackBuilder.addNextIntent(viewConversationIntent);
406
407 return stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
408 }
409
410 private PendingIntent createDownloadIntent(final Message message) {
411 return createContentIntent(message.getConversationUuid(), message.getUuid());
412 }
413
414 private PendingIntent createContentIntent(final Conversation conversation) {
415 return createContentIntent(conversation.getUuid(), null);
416 }
417
418 private PendingIntent createDeleteIntent() {
419 final Intent intent = new Intent(mXmppConnectionService,
420 XmppConnectionService.class);
421 intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
422 return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
423 }
424
425 private PendingIntent createDisableForeground() {
426 final Intent intent = new Intent(mXmppConnectionService,
427 XmppConnectionService.class);
428 intent.setAction(XmppConnectionService.ACTION_DISABLE_FOREGROUND);
429 return PendingIntent.getService(mXmppConnectionService, 34, intent, 0);
430 }
431
432 private PendingIntent createTryAgainIntent() {
433 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
434 intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
435 return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
436 }
437
438 private PendingIntent createDisableAccountIntent(final Account account) {
439 final Intent intent = new Intent(mXmppConnectionService,XmppConnectionService.class);
440 intent.setAction(XmppConnectionService.ACTION_DISABLE_ACCOUNT);
441 intent.putExtra("account",account.getJid().toBareJid().toString());
442 return PendingIntent.getService(mXmppConnectionService,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
443 }
444
445 private boolean wasHighlightedOrPrivate(final Message message) {
446 final String nick = message.getConversation().getMucOptions().getActualNick();
447 final Pattern highlight = generateNickHighlightPattern(nick);
448 if (message.getBody() == null || nick == null) {
449 return false;
450 }
451 final Matcher m = highlight.matcher(message.getBody());
452 return (m.find() || message.getType() == Message.TYPE_PRIVATE);
453 }
454
455 private static Pattern generateNickHighlightPattern(final String nick) {
456 // We expect a word boundary, i.e. space or start of string, followed by
457 // the
458 // nick (matched in case-insensitive manner), followed by optional
459 // punctuation (for example "bob: i disagree" or "how are you alice?"),
460 // followed by another word boundary.
461 return Pattern.compile("\\b" + Pattern.quote(nick) + "\\p{Punct}?\\b",
462 Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
463 }
464
465 public void setOpenConversation(final Conversation conversation) {
466 this.mOpenConversation = conversation;
467 }
468
469 public void setIsInForeground(final boolean foreground) {
470 this.mIsInForeground = foreground;
471 }
472
473 private int getPixel(final int dp) {
474 final DisplayMetrics metrics = mXmppConnectionService.getResources()
475 .getDisplayMetrics();
476 return ((int) (dp * metrics.density));
477 }
478
479 private void markLastNotification() {
480 this.mLastNotification = SystemClock.elapsedRealtime();
481 }
482
483 private boolean inMiniGracePeriod(final Account account) {
484 final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
485 : Config.MINI_GRACE_PERIOD * 2;
486 return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
487 }
488
489 public Notification createForegroundNotification() {
490 final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
491
492 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.conversations_foreground_service));
493 mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_open_conversations));
494 mBuilder.setContentIntent(createOpenConversationsIntent());
495 mBuilder.setWhen(0);
496 mBuilder.setPriority(NotificationCompat.PRIORITY_MIN);
497 final int cancelIcon;
498 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
499 mBuilder.setCategory(Notification.CATEGORY_SERVICE);
500 mBuilder.setSmallIcon(R.drawable.ic_import_export_white_24dp);
501 cancelIcon = R.drawable.ic_cancel_white_24dp;
502 } else {
503 mBuilder.setSmallIcon(R.drawable.ic_stat_communication_import_export);
504 cancelIcon = R.drawable.ic_action_cancel;
505 }
506 mBuilder.addAction(cancelIcon,
507 mXmppConnectionService.getString(R.string.disable_foreground_service),
508 createDisableForeground());
509 setNotificationColor(mBuilder);
510 return mBuilder.build();
511 }
512
513 private PendingIntent createOpenConversationsIntent() {
514 return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService,ConversationActivity.class),0);
515 }
516
517 public void updateErrorNotification() {
518 final NotificationManager mNotificationManager = (NotificationManager) mXmppConnectionService.getSystemService(Context.NOTIFICATION_SERVICE);
519 final List<Account> errors = new ArrayList<>();
520 for (final Account account : mXmppConnectionService.getAccounts()) {
521 if (account.hasErrorStatus()) {
522 errors.add(account);
523 }
524 }
525 final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
526 if (errors.size() == 0) {
527 mNotificationManager.cancel(ERROR_NOTIFICATION_ID);
528 return;
529 } else if (errors.size() == 1) {
530 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
531 mBuilder.setContentText(errors.get(0).getJid().toBareJid().toString());
532 } else {
533 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
534 mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
535 }
536 mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
537 mXmppConnectionService.getString(R.string.try_again),
538 createTryAgainIntent());
539 if (errors.size() == 1) {
540 mBuilder.addAction(R.drawable.ic_block_white_24dp,
541 mXmppConnectionService.getString(R.string.disable_account),
542 createDisableAccountIntent(errors.get(0)));
543 }
544 mBuilder.setOngoing(true);
545 //mBuilder.setLights(0xffffffff, 2000, 4000);
546 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
547 mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
548 } else {
549 mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
550 }
551 final TaskStackBuilder stackBuilder = TaskStackBuilder.create(mXmppConnectionService);
552 stackBuilder.addParentStack(ConversationActivity.class);
553
554 final Intent manageAccountsIntent = new Intent(mXmppConnectionService,ManageAccountActivity.class);
555 stackBuilder.addNextIntent(manageAccountsIntent);
556
557 final PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
558
559 mBuilder.setContentIntent(resultPendingIntent);
560 mNotificationManager.notify(ERROR_NOTIFICATION_ID, mBuilder.build());
561 }
562}