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