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.setDefaults(0);
215 mBuilder.setSmallIcon(R.drawable.ic_notification);
216 mBuilder.setDeleteIntent(createDeleteIntent());
217 mBuilder.setLights(0xffffffff, 2000, 4000);
218 final Notification notification = mBuilder.build();
219 notificationManager.notify(NOTIFICATION_ID, notification);
220 }
221 }
222
223 private Builder buildMultipleConversation() {
224 final Builder mBuilder = new NotificationCompat.Builder(
225 mXmppConnectionService);
226 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
227 style.setBigContentTitle(notifications.size()
228 + " "
229 + mXmppConnectionService
230 .getString(R.string.unread_conversations));
231 final StringBuilder names = new StringBuilder();
232 Conversation conversation = null;
233 for (final ArrayList<Message> messages : notifications.values()) {
234 if (messages.size() > 0) {
235 conversation = messages.get(0).getConversation();
236 final String name = conversation.getName();
237 style.addLine(Html.fromHtml("<b>" + name + "</b> "
238 + UIHelper.getMessagePreview(mXmppConnectionService,messages.get(0)).first));
239 names.append(name);
240 names.append(", ");
241 }
242 }
243 if (names.length() >= 2) {
244 names.delete(names.length() - 2, names.length());
245 }
246 mBuilder.setContentTitle(notifications.size()
247 + " "
248 + mXmppConnectionService
249 .getString(R.string.unread_conversations));
250 mBuilder.setContentText(names.toString());
251 mBuilder.setStyle(style);
252 if (conversation != null) {
253 mBuilder.setContentIntent(createContentIntent(conversation));
254 }
255 return mBuilder;
256 }
257
258 private Builder buildSingleConversations(final boolean notify) {
259 final Builder mBuilder = new NotificationCompat.Builder(
260 mXmppConnectionService);
261 final ArrayList<Message> messages = notifications.values().iterator().next();
262 if (messages.size() >= 1) {
263 final Conversation conversation = messages.get(0).getConversation();
264 mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
265 .get(conversation, getPixel(64)));
266 mBuilder.setContentTitle(conversation.getName());
267 Message message;
268 if ((message = getImage(messages)) != null) {
269 modifyForImage(mBuilder, message, messages, notify);
270 } else {
271 modifyForTextOnly(mBuilder, messages, notify);
272 }
273 if ((message = getFirstDownloadableMessage(messages)) != null) {
274 mBuilder.addAction(
275 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ?
276 R.drawable.ic_file_download_white_24dp : R.drawable.ic_action_download,
277 mXmppConnectionService.getResources().getString(R.string.download_x_file,
278 UIHelper.getFileDescriptionString(mXmppConnectionService, message)),
279 createDownloadIntent(message)
280 );
281 }
282 mBuilder.setContentIntent(createContentIntent(conversation));
283 }
284 return mBuilder;
285 }
286
287 private void modifyForImage(final Builder builder, final Message message,
288 final ArrayList<Message> messages, final boolean notify) {
289 try {
290 final Bitmap bitmap = mXmppConnectionService.getFileBackend()
291 .getThumbnail(message, getPixel(288), false);
292 final ArrayList<Message> tmp = new ArrayList<>();
293 for (final Message msg : messages) {
294 if (msg.getType() == Message.TYPE_TEXT
295 && msg.getDownloadable() == null) {
296 tmp.add(msg);
297 }
298 }
299 final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
300 bigPictureStyle.bigPicture(bitmap);
301 if (tmp.size() > 0) {
302 bigPictureStyle.setSummaryText(getMergedBodies(tmp));
303 builder.setContentText(UIHelper.getMessagePreview(mXmppConnectionService,tmp.get(0)).first);
304 } else {
305 builder.setContentText(mXmppConnectionService.getString(
306 R.string.received_x_file,
307 UIHelper.getFileDescriptionString(mXmppConnectionService,message)));
308 }
309 builder.setStyle(bigPictureStyle);
310 } catch (final FileNotFoundException e) {
311 modifyForTextOnly(builder, messages, notify);
312 }
313 }
314
315 private void modifyForTextOnly(final Builder builder,
316 final ArrayList<Message> messages, final boolean notify) {
317 builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
318 builder.setContentText(UIHelper.getMessagePreview(mXmppConnectionService,messages.get(0)).first);
319 if (notify) {
320 builder.setTicker(UIHelper.getMessagePreview(mXmppConnectionService,messages.get(messages.size() - 1)).first);
321 }
322 }
323
324 private Message getImage(final Iterable<Message> messages) {
325 for (final Message message : messages) {
326 if (message.getType() == Message.TYPE_IMAGE
327 && message.getDownloadable() == null
328 && message.getEncryption() != Message.ENCRYPTION_PGP) {
329 return message;
330 }
331 }
332 return null;
333 }
334
335 private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
336 for (final Message message : messages) {
337 if ((message.getType() == Message.TYPE_FILE || message.getType() == Message.TYPE_IMAGE) &&
338 message.getDownloadable() != null) {
339 return message;
340 }
341 }
342 return null;
343 }
344
345 private CharSequence getMergedBodies(final ArrayList<Message> messages) {
346 final StringBuilder text = new StringBuilder();
347 for (int i = 0; i < messages.size(); ++i) {
348 text.append(UIHelper.getMessagePreview(mXmppConnectionService,messages.get(i)).first);
349 if (i != messages.size() - 1) {
350 text.append("\n");
351 }
352 }
353 return text.toString();
354 }
355
356 private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
357 final TaskStackBuilder stackBuilder = TaskStackBuilder
358 .create(mXmppConnectionService);
359 stackBuilder.addParentStack(ConversationActivity.class);
360
361 final Intent viewConversationIntent = new Intent(mXmppConnectionService,
362 ConversationActivity.class);
363 if (downloadMessageUuid != null) {
364 viewConversationIntent.setAction(ConversationActivity.ACTION_DOWNLOAD);
365 } else {
366 viewConversationIntent.setAction(Intent.ACTION_VIEW);
367 }
368 if (conversationUuid != null) {
369 viewConversationIntent.putExtra(ConversationActivity.CONVERSATION, conversationUuid);
370 viewConversationIntent.setType(ConversationActivity.VIEW_CONVERSATION);
371 }
372 if (downloadMessageUuid != null) {
373 viewConversationIntent.putExtra(ConversationActivity.MESSAGE, downloadMessageUuid);
374 }
375
376 stackBuilder.addNextIntent(viewConversationIntent);
377
378 return stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
379 }
380
381 private PendingIntent createDownloadIntent(final Message message) {
382 return createContentIntent(message.getConversationUuid(), message.getUuid());
383 }
384
385 private PendingIntent createContentIntent(final Conversation conversation) {
386 return createContentIntent(conversation.getUuid(), null);
387 }
388
389 private PendingIntent createDeleteIntent() {
390 final Intent intent = new Intent(mXmppConnectionService,
391 XmppConnectionService.class);
392 intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
393 return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
394 }
395
396 private PendingIntent createDisableForeground() {
397 final Intent intent = new Intent(mXmppConnectionService,
398 XmppConnectionService.class);
399 intent.setAction(XmppConnectionService.ACTION_DISABLE_FOREGROUND);
400 return PendingIntent.getService(mXmppConnectionService, 34, intent, 0);
401 }
402
403 private PendingIntent createTryAgainIntent() {
404 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
405 intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
406 return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
407 }
408
409 private PendingIntent createDisableAccountIntent(final Account account) {
410 final Intent intent = new Intent(mXmppConnectionService,XmppConnectionService.class);
411 intent.setAction(XmppConnectionService.ACTION_DISABLE_ACCOUNT);
412 intent.putExtra("account",account.getJid().toBareJid().toString());
413 return PendingIntent.getService(mXmppConnectionService,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
414 }
415
416 private boolean wasHighlightedOrPrivate(final Message message) {
417 final String nick = message.getConversation().getMucOptions().getActualNick();
418 final Pattern highlight = generateNickHighlightPattern(nick);
419 if (message.getBody() == null || nick == null) {
420 return false;
421 }
422 final Matcher m = highlight.matcher(message.getBody());
423 return (m.find() || message.getType() == Message.TYPE_PRIVATE);
424 }
425
426 private static Pattern generateNickHighlightPattern(final String nick) {
427 // We expect a word boundary, i.e. space or start of string, followed by
428 // the
429 // nick (matched in case-insensitive manner), followed by optional
430 // punctuation (for example "bob: i disagree" or "how are you alice?"),
431 // followed by another word boundary.
432 return Pattern.compile("\\b" + nick + "\\p{Punct}?\\b",
433 Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
434 }
435
436 public void setOpenConversation(final Conversation conversation) {
437 this.mOpenConversation = conversation;
438 }
439
440 public void setIsInForeground(final boolean foreground) {
441 this.mIsInForeground = foreground;
442 }
443
444 private int getPixel(final int dp) {
445 final DisplayMetrics metrics = mXmppConnectionService.getResources()
446 .getDisplayMetrics();
447 return ((int) (dp * metrics.density));
448 }
449
450 private void markLastNotification() {
451 this.mLastNotification = SystemClock.elapsedRealtime();
452 }
453
454 private boolean inMiniGracePeriod(final Account account) {
455 final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
456 : Config.MINI_GRACE_PERIOD * 2;
457 return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
458 }
459
460 public Notification createForegroundNotification() {
461 final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
462
463 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.conversations_foreground_service));
464 mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_open_conversations));
465 mBuilder.setContentIntent(createOpenConversationsIntent());
466 mBuilder.setWhen(0);
467 mBuilder.setPriority(NotificationCompat.PRIORITY_MIN);
468 final int cancelIcon;
469 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
470 mBuilder.setCategory(Notification.CATEGORY_SERVICE);
471 mBuilder.setSmallIcon(R.drawable.ic_import_export_white_48dp);
472 cancelIcon = R.drawable.ic_cancel_white_24dp;
473 } else {
474 mBuilder.setSmallIcon(R.drawable.ic_stat_communication_import_export);
475 cancelIcon = R.drawable.ic_action_cancel;
476 }
477 mBuilder.addAction(cancelIcon,
478 mXmppConnectionService.getString(R.string.disable_foreground_service),
479 createDisableForeground());
480 setNotificationColor(mBuilder);
481 return mBuilder.build();
482 }
483
484 private PendingIntent createOpenConversationsIntent() {
485 return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService,ConversationActivity.class),0);
486 }
487
488 public void updateErrorNotification() {
489 final NotificationManager mNotificationManager = (NotificationManager) mXmppConnectionService.getSystemService(Context.NOTIFICATION_SERVICE);
490 final List<Account> errors = new ArrayList<>();
491 for (final Account account : mXmppConnectionService.getAccounts()) {
492 if (account.hasErrorStatus()) {
493 errors.add(account);
494 }
495 }
496 final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
497 if (errors.size() == 0) {
498 mNotificationManager.cancel(ERROR_NOTIFICATION_ID);
499 return;
500 } else if (errors.size() == 1) {
501 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
502 mBuilder.setContentText(errors.get(0).getJid().toBareJid().toString());
503 } else {
504 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
505 mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
506 }
507 mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
508 mXmppConnectionService.getString(R.string.try_again),
509 createTryAgainIntent());
510 if (errors.size() == 1) {
511 mBuilder.addAction(R.drawable.ic_block_white_24dp,
512 mXmppConnectionService.getString(R.string.disable_account),
513 createDisableAccountIntent(errors.get(0)));
514 }
515 mBuilder.setOngoing(true);
516 //mBuilder.setLights(0xffffffff, 2000, 4000);
517 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
518 mBuilder.setSmallIcon(R.drawable.ic_warning_white_36dp);
519 } else {
520 mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
521 }
522 final TaskStackBuilder stackBuilder = TaskStackBuilder.create(mXmppConnectionService);
523 stackBuilder.addParentStack(ConversationActivity.class);
524
525 final Intent manageAccountsIntent = new Intent(mXmppConnectionService,ManageAccountActivity.class);
526 stackBuilder.addNextIntent(manageAccountsIntent);
527
528 final PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
529
530 mBuilder.setContentIntent(resultPendingIntent);
531 mNotificationManager.notify(ERROR_NOTIFICATION_ID, mBuilder.build());
532 }
533}