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