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