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 if (!notify(message)) {
138 return;
139 }
140
141 final boolean isScreenOn = isInteractive();
142
143 if (this.mIsInForeground && isScreenOn && this.mOpenConversation == message.getConversation()) {
144 return;
145 }
146
147 synchronized (notifications) {
148 final String conversationUuid = message.getConversationUuid();
149 if (notifications.containsKey(conversationUuid)) {
150 notifications.get(conversationUuid).add(message);
151 } else {
152 final ArrayList<Message> mList = new ArrayList<>();
153 mList.add(message);
154 notifications.put(conversationUuid, mList);
155 }
156 final Account account = message.getConversation().getAccount();
157 final boolean doNotify = (!(this.mIsInForeground && this.mOpenConversation == null) || !isScreenOn)
158 && !account.inGracePeriod()
159 && !this.inMiniGracePeriod(account);
160 updateNotification(doNotify);
161 if (doNotify) {
162 notifyPebble(message);
163 }
164 }
165 }
166
167 public void clear() {
168 synchronized (notifications) {
169 notifications.clear();
170 updateNotification(false);
171 }
172 }
173
174 public void clear(final Conversation conversation) {
175 synchronized (notifications) {
176 notifications.remove(conversation.getUuid());
177 updateNotification(false);
178 }
179 }
180
181 private void setNotificationColor(final Builder mBuilder) {
182 mBuilder.setColor(mXmppConnectionService.getResources().getColor(R.color.primary));
183 }
184
185 private void updateNotification(final boolean notify) {
186 final NotificationManager notificationManager = (NotificationManager) mXmppConnectionService
187 .getSystemService(Context.NOTIFICATION_SERVICE);
188 final SharedPreferences preferences = mXmppConnectionService.getPreferences();
189
190 final String ringtone = preferences.getString("notification_ringtone", null);
191 final boolean vibrate = preferences.getBoolean("vibrate_on_notification", true);
192
193 if (notifications.size() == 0) {
194 notificationManager.cancel(NOTIFICATION_ID);
195 } else {
196 if (notify) {
197 this.markLastNotification();
198 }
199 final Builder mBuilder;
200 if (notifications.size() == 1) {
201 mBuilder = buildSingleConversations(notify);
202 } else {
203 mBuilder = buildMultipleConversation();
204 }
205 if (notify && !isQuietHours()) {
206 if (vibrate) {
207 final int dat = 70;
208 final long[] pattern = {0, 3 * dat, dat, dat};
209 mBuilder.setVibrate(pattern);
210 }
211 if (ringtone != null) {
212 mBuilder.setSound(Uri.parse(ringtone));
213 }
214 }
215 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
216 mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
217 }
218 setNotificationColor(mBuilder);
219 mBuilder.setDefaults(0);
220 mBuilder.setSmallIcon(R.drawable.ic_notification);
221 mBuilder.setDeleteIntent(createDeleteIntent());
222 mBuilder.setLights(0xff00FF00, 2000, 3000);
223 final Notification notification = mBuilder.build();
224 notificationManager.notify(NOTIFICATION_ID, notification);
225 }
226 }
227
228 private Builder buildMultipleConversation() {
229 final Builder mBuilder = new NotificationCompat.Builder(
230 mXmppConnectionService);
231 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
232 style.setBigContentTitle(notifications.size()
233 + " "
234 + mXmppConnectionService
235 .getString(R.string.unread_conversations));
236 final StringBuilder names = new StringBuilder();
237 Conversation conversation = null;
238 for (final ArrayList<Message> messages : notifications.values()) {
239 if (messages.size() > 0) {
240 conversation = messages.get(0).getConversation();
241 final String name = conversation.getName();
242 style.addLine(Html.fromHtml("<b>" + name + "</b> "
243 + UIHelper.getMessagePreview(mXmppConnectionService,messages.get(0)).first));
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 Message message;
273 if ((message = getImage(messages)) != null) {
274 modifyForImage(mBuilder, message, messages, notify);
275 } else {
276 modifyForTextOnly(mBuilder, messages, notify);
277 }
278 if ((message = getFirstDownloadableMessage(messages)) != null) {
279 mBuilder.addAction(
280 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ?
281 R.drawable.ic_file_download_white_24dp : R.drawable.ic_action_download,
282 mXmppConnectionService.getResources().getString(R.string.download_x_file,
283 UIHelper.getFileDescriptionString(mXmppConnectionService, message)),
284 createDownloadIntent(message)
285 );
286 }
287 if ((message = getFirstLocationMessage(messages)) != null) {
288 mBuilder.addAction(R.drawable.ic_room_white_24dp,
289 mXmppConnectionService.getString(R.string.show_location),
290 createShowLocationIntent(message));
291 }
292 mBuilder.setContentIntent(createContentIntent(conversation));
293 }
294 return mBuilder;
295 }
296
297 private void modifyForImage(final Builder builder, final Message message,
298 final ArrayList<Message> messages, final boolean notify) {
299 try {
300 final Bitmap bitmap = mXmppConnectionService.getFileBackend()
301 .getThumbnail(message, getPixel(288), false);
302 final ArrayList<Message> tmp = new ArrayList<>();
303 for (final Message msg : messages) {
304 if (msg.getType() == Message.TYPE_TEXT
305 && msg.getDownloadable() == null) {
306 tmp.add(msg);
307 }
308 }
309 final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
310 bigPictureStyle.bigPicture(bitmap);
311 if (tmp.size() > 0) {
312 bigPictureStyle.setSummaryText(getMergedBodies(tmp));
313 builder.setContentText(UIHelper.getMessagePreview(mXmppConnectionService,tmp.get(0)).first);
314 } else {
315 builder.setContentText(mXmppConnectionService.getString(
316 R.string.received_x_file,
317 UIHelper.getFileDescriptionString(mXmppConnectionService,message)));
318 }
319 builder.setStyle(bigPictureStyle);
320 } catch (final FileNotFoundException e) {
321 modifyForTextOnly(builder, messages, notify);
322 }
323 }
324
325 private void modifyForTextOnly(final Builder builder,
326 final ArrayList<Message> messages, final boolean notify) {
327 builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
328 builder.setContentText(UIHelper.getMessagePreview(mXmppConnectionService,messages.get(0)).first);
329 if (notify) {
330 builder.setTicker(UIHelper.getMessagePreview(mXmppConnectionService,messages.get(messages.size() - 1)).first);
331 }
332 }
333
334 private Message getImage(final Iterable<Message> messages) {
335 for (final Message message : messages) {
336 if (message.getType() == Message.TYPE_IMAGE
337 && message.getDownloadable() == null
338 && message.getEncryption() != Message.ENCRYPTION_PGP) {
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.getDownloadable() != 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}