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