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