1package eu.siacs.conversations.services;
2
3import android.app.Notification;
4import android.app.PendingIntent;
5import android.content.Intent;
6import android.content.SharedPreferences;
7import android.content.res.Resources;
8import android.graphics.Bitmap;
9import android.graphics.Typeface;
10import android.net.Uri;
11import android.os.Build;
12import android.os.SystemClock;
13import android.preference.PreferenceManager;
14import android.support.v4.app.NotificationCompat;
15import android.support.v4.app.NotificationCompat.BigPictureStyle;
16import android.support.v4.app.NotificationCompat.Builder;
17import android.support.v4.app.NotificationManagerCompat;
18import android.support.v4.app.NotificationCompat.CarExtender.UnreadConversation;
19import android.support.v4.app.RemoteInput;
20import android.support.v4.content.ContextCompat;
21import android.text.SpannableString;
22import android.text.style.StyleSpan;
23import android.util.DisplayMetrics;
24import android.util.Log;
25import android.util.Pair;
26
27import java.io.File;
28import java.io.FileNotFoundException;
29import java.io.IOException;
30import java.util.ArrayList;
31import java.util.Calendar;
32import java.util.HashMap;
33import java.util.Iterator;
34import java.util.LinkedHashMap;
35import java.util.List;
36import java.util.Map;
37import java.util.concurrent.atomic.AtomicInteger;
38import java.util.regex.Matcher;
39import java.util.regex.Pattern;
40
41import eu.siacs.conversations.Config;
42import eu.siacs.conversations.R;
43import eu.siacs.conversations.entities.Account;
44import eu.siacs.conversations.entities.Contact;
45import eu.siacs.conversations.entities.Conversation;
46import eu.siacs.conversations.entities.Conversational;
47import eu.siacs.conversations.entities.Message;
48import eu.siacs.conversations.persistance.FileBackend;
49import eu.siacs.conversations.ui.ConversationsActivity;
50import eu.siacs.conversations.ui.ManageAccountActivity;
51import eu.siacs.conversations.ui.TimePreference;
52import eu.siacs.conversations.utils.GeoHelper;
53import eu.siacs.conversations.utils.UIHelper;
54import eu.siacs.conversations.xmpp.XmppConnection;
55
56public class NotificationService {
57
58 public static final Object CATCHUP_LOCK = new Object();
59
60 private static final String CONVERSATIONS_GROUP = "eu.siacs.conversations";
61 private final XmppConnectionService mXmppConnectionService;
62
63 private final LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<>();
64
65 private static final int NOTIFICATION_ID_MULTIPLIER = 1024 * 1024;
66
67 public static final int NOTIFICATION_ID = 2 * NOTIFICATION_ID_MULTIPLIER;
68 public static final int FOREGROUND_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 4;
69 public static final int ERROR_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 6;
70
71 private Conversation mOpenConversation;
72 private boolean mIsInForeground;
73 private long mLastNotification;
74
75 private final HashMap<Conversation, AtomicInteger> mBacklogMessageCounter = new HashMap<>();
76
77 public NotificationService(final XmppConnectionService service) {
78 this.mXmppConnectionService = service;
79 }
80
81 public boolean notify(final Message message) {
82 final Conversation conversation = (Conversation) message.getConversation();
83 return message.getStatus() == Message.STATUS_RECEIVED
84 && notificationsEnabled()
85 && !conversation.isMuted()
86 && (conversation.alwaysNotify() || wasHighlightedOrPrivate(message))
87 && (!conversation.isWithStranger() || notificationsFromStrangers())
88 ;
89 }
90
91 public boolean notificationsEnabled() {
92 return mXmppConnectionService.getBooleanPreference("show_notification", R.bool.show_notification);
93 }
94
95 private boolean notificationsFromStrangers() {
96 return mXmppConnectionService.getBooleanPreference("notifications_from_strangers", R.bool.notifications_from_strangers);
97 }
98
99 public boolean isQuietHours() {
100 if (!mXmppConnectionService.getBooleanPreference("enable_quiet_hours", R.bool.enable_quiet_hours)) {
101 return false;
102 }
103 final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
104 final long startTime = preferences.getLong("quiet_hours_start", TimePreference.DEFAULT_VALUE) % Config.MILLISECONDS_IN_DAY;
105 final long endTime = preferences.getLong("quiet_hours_end", TimePreference.DEFAULT_VALUE) % Config.MILLISECONDS_IN_DAY;
106 final long nowTime = Calendar.getInstance().getTimeInMillis() % Config.MILLISECONDS_IN_DAY;
107
108 if (endTime < startTime) {
109 return nowTime > startTime || nowTime < endTime;
110 } else {
111 return nowTime > startTime && nowTime < endTime;
112 }
113 }
114
115 public void pushFromBacklog(final Message message) {
116 if (notify(message)) {
117 synchronized (notifications) {
118 getBacklogMessageCounter((Conversation) message.getConversation()).incrementAndGet();
119 pushToStack(message);
120 }
121 }
122 }
123
124 private AtomicInteger getBacklogMessageCounter(Conversation conversation) {
125 synchronized (mBacklogMessageCounter) {
126 if (!mBacklogMessageCounter.containsKey(conversation)) {
127 mBacklogMessageCounter.put(conversation, new AtomicInteger(0));
128 }
129 return mBacklogMessageCounter.get(conversation);
130 }
131 }
132
133 public void pushFromDirectReply(final Message message) {
134 synchronized (notifications) {
135 pushToStack(message);
136 updateNotification(false);
137 }
138 }
139
140 public void finishBacklog(boolean notify, Account account) {
141 synchronized (notifications) {
142 mXmppConnectionService.updateUnreadCountBadge();
143 if (account == null || !notify) {
144 updateNotification(notify);
145 } else {
146 updateNotification(getBacklogMessageCount(account) > 0);
147 }
148 }
149 }
150
151 private int getBacklogMessageCount(Account account) {
152 int count = 0;
153 synchronized (this.mBacklogMessageCounter) {
154 for (Iterator<Map.Entry<Conversation, AtomicInteger>> it = mBacklogMessageCounter.entrySet().iterator(); it.hasNext(); ) {
155 Map.Entry<Conversation, AtomicInteger> entry = it.next();
156 if (entry.getKey().getAccount() == account) {
157 count += entry.getValue().get();
158 it.remove();
159 }
160 }
161 }
162 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": backlog message count=" + count);
163 return count;
164 }
165
166 public void finishBacklog(boolean notify) {
167 finishBacklog(notify, null);
168 }
169
170 private void pushToStack(final Message message) {
171 final String conversationUuid = message.getConversationUuid();
172 if (notifications.containsKey(conversationUuid)) {
173 notifications.get(conversationUuid).add(message);
174 } else {
175 final ArrayList<Message> mList = new ArrayList<>();
176 mList.add(message);
177 notifications.put(conversationUuid, mList);
178 }
179 }
180
181 public void push(final Message message) {
182 synchronized (CATCHUP_LOCK) {
183 final XmppConnection connection = message.getConversation().getAccount().getXmppConnection();
184 if (connection.isWaitingForSmCatchup()) {
185 connection.incrementSmCatchupMessageCounter();
186 pushFromBacklog(message);
187 } else {
188 pushNow(message);
189 }
190 }
191 }
192
193 private void pushNow(final Message message) {
194 mXmppConnectionService.updateUnreadCountBadge();
195 if (!notify(message)) {
196 Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because turned off");
197 return;
198 }
199 final boolean isScreenOn = mXmppConnectionService.isInteractive();
200 if (this.mIsInForeground && isScreenOn && this.mOpenConversation == message.getConversation()) {
201 Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because conversation is open");
202 return;
203 }
204 synchronized (notifications) {
205 pushToStack(message);
206 final Account account = message.getConversation().getAccount();
207 final boolean doNotify = (!(this.mIsInForeground && this.mOpenConversation == null) || !isScreenOn)
208 && !account.inGracePeriod()
209 && !this.inMiniGracePeriod(account);
210 updateNotification(doNotify);
211 }
212 }
213
214 public void clear() {
215 synchronized (notifications) {
216 for (ArrayList<Message> messages : notifications.values()) {
217 markAsReadIfHasDirectReply(messages);
218 }
219 notifications.clear();
220 updateNotification(false);
221 }
222 }
223
224 public void clear(final Conversation conversation) {
225 synchronized (this.mBacklogMessageCounter) {
226 this.mBacklogMessageCounter.remove(conversation);
227 }
228 synchronized (notifications) {
229 markAsReadIfHasDirectReply(conversation);
230 if (notifications.remove(conversation.getUuid()) != null) {
231 cancel(conversation.getUuid(), NOTIFICATION_ID);
232 updateNotification(false, true);
233 }
234 }
235 }
236
237 private void markAsReadIfHasDirectReply(final Conversation conversation) {
238 markAsReadIfHasDirectReply(notifications.get(conversation.getUuid()));
239 }
240
241 private void markAsReadIfHasDirectReply(final ArrayList<Message> messages) {
242 if (messages != null && messages.size() > 0) {
243 Message last = messages.get(messages.size() - 1);
244 if (last.getStatus() != Message.STATUS_RECEIVED) {
245 if (mXmppConnectionService.markRead((Conversation) last.getConversation(), false)) {
246 mXmppConnectionService.updateConversationUi();
247 }
248 }
249 }
250 }
251
252 private void setNotificationColor(final Builder mBuilder) {
253 mBuilder.setColor(ContextCompat.getColor(mXmppConnectionService, R.color.green600));
254 }
255
256 public void updateNotification(final boolean notify) {
257 updateNotification(notify, false);
258 }
259
260 public void updateNotification(final boolean notify, boolean summaryOnly) {
261 final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
262
263 if (notifications.size() == 0) {
264 cancel(NOTIFICATION_ID);
265 } else {
266 if (notify) {
267 this.markLastNotification();
268 }
269 final Builder mBuilder;
270 if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
271 mBuilder = buildSingleConversations(notifications.values().iterator().next());
272 modifyForSoundVibrationAndLight(mBuilder, notify, preferences);
273 notify(NOTIFICATION_ID, mBuilder.build());
274 } else {
275 mBuilder = buildMultipleConversation();
276 modifyForSoundVibrationAndLight(mBuilder, notify, preferences);
277 if (!summaryOnly) {
278 for (Map.Entry<String, ArrayList<Message>> entry : notifications.entrySet()) {
279 Builder singleBuilder = buildSingleConversations(entry.getValue());
280 singleBuilder.setGroup(CONVERSATIONS_GROUP);
281 setNotificationColor(singleBuilder);
282 notify(entry.getKey(), NOTIFICATION_ID, singleBuilder.build());
283 }
284 }
285 notify(NOTIFICATION_ID, mBuilder.build());
286 }
287 }
288 }
289
290
291 private void modifyForSoundVibrationAndLight(Builder mBuilder, boolean notify, SharedPreferences preferences) {
292 final Resources resources = mXmppConnectionService.getResources();
293 final String ringtone = preferences.getString("notification_ringtone", resources.getString(R.string.notification_ringtone));
294 final boolean vibrate = preferences.getBoolean("vibrate_on_notification", resources.getBoolean(R.bool.vibrate_on_notification));
295 final boolean led = preferences.getBoolean("led", resources.getBoolean(R.bool.led));
296 final boolean headsup = preferences.getBoolean("notification_headsup", resources.getBoolean(R.bool.headsup_notifications));
297 if (notify && !isQuietHours()) {
298 if (vibrate) {
299 final int dat = 70;
300 final long[] pattern = {0, 3 * dat, dat, dat};
301 mBuilder.setVibrate(pattern);
302 } else {
303 mBuilder.setVibrate(new long[]{0});
304 }
305 Uri uri = Uri.parse(ringtone);
306 try {
307 mBuilder.setSound(fixRingtoneUri(uri));
308 } catch (SecurityException e) {
309 Log.d(Config.LOGTAG, "unable to use custom notification sound " + uri.toString());
310 }
311 }
312 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
313 mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
314 }
315 mBuilder.setPriority(notify ? (headsup ? NotificationCompat.PRIORITY_HIGH : NotificationCompat.PRIORITY_DEFAULT) : NotificationCompat.PRIORITY_LOW);
316 setNotificationColor(mBuilder);
317 mBuilder.setDefaults(0);
318 if (led) {
319 mBuilder.setLights(0xff00FF00, 2000, 3000);
320 }
321 }
322
323 private Uri fixRingtoneUri(Uri uri) {
324 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && "file".equals(uri.getScheme())) {
325 return FileBackend.getUriForFile(mXmppConnectionService, new File(uri.getPath()));
326 } else {
327 return uri;
328 }
329 }
330
331 private Builder buildMultipleConversation() {
332 final Builder mBuilder = new NotificationCompat.Builder(
333 mXmppConnectionService);
334 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
335 style.setBigContentTitle(notifications.size()
336 + " "
337 + mXmppConnectionService
338 .getString(R.string.unread_conversations));
339 final StringBuilder names = new StringBuilder();
340 Conversation conversation = null;
341 for (final ArrayList<Message> messages : notifications.values()) {
342 if (messages.size() > 0) {
343 conversation = (Conversation) messages.get(0).getConversation();
344 final String name = conversation.getName().toString();
345 SpannableString styledString;
346 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
347 int count = messages.size();
348 styledString = new SpannableString(name + ": " + mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
349 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
350 style.addLine(styledString);
351 } else {
352 styledString = new SpannableString(name + ": " + UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
353 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
354 style.addLine(styledString);
355 }
356 names.append(name);
357 names.append(", ");
358 }
359 }
360 if (names.length() >= 2) {
361 names.delete(names.length() - 2, names.length());
362 }
363 mBuilder.setContentTitle(notifications.size()
364 + " "
365 + mXmppConnectionService
366 .getString(R.string.unread_conversations));
367 mBuilder.setContentText(names.toString());
368 mBuilder.setStyle(style);
369 if (conversation != null) {
370 mBuilder.setContentIntent(createContentIntent(conversation));
371 }
372 mBuilder.setGroupSummary(true);
373 mBuilder.setGroup(CONVERSATIONS_GROUP);
374 mBuilder.setDeleteIntent(createDeleteIntent(null));
375 mBuilder.setSmallIcon(R.drawable.ic_notification);
376 return mBuilder;
377 }
378
379 private Builder buildSingleConversations(final ArrayList<Message> messages) {
380 final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
381 if (messages.size() >= 1) {
382 final Conversation conversation = (Conversation) messages.get(0).getConversation();
383 final UnreadConversation.Builder mUnreadBuilder = new UnreadConversation.Builder(conversation.getName().toString());
384 mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
385 .get(conversation, getPixel(64)));
386 mBuilder.setContentTitle(conversation.getName());
387 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
388 int count = messages.size();
389 mBuilder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
390 } else {
391 Message message;
392 if ((message = getImage(messages)) != null) {
393 modifyForImage(mBuilder, mUnreadBuilder, message, messages);
394 } else {
395 modifyForTextOnly(mBuilder, mUnreadBuilder, messages);
396 }
397 RemoteInput remoteInput = new RemoteInput.Builder("text_reply").setLabel(UIHelper.getMessageHint(mXmppConnectionService, conversation)).build();
398 PendingIntent markAsReadPendingIntent = createReadPendingIntent(conversation);
399 NotificationCompat.Action markReadAction = new NotificationCompat.Action.Builder(
400 R.drawable.ic_drafts_white_24dp,
401 mXmppConnectionService.getString(R.string.mark_as_read),
402 markAsReadPendingIntent).build();
403 String replyLabel = mXmppConnectionService.getString(R.string.reply);
404 NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
405 R.drawable.ic_send_text_offline,
406 replyLabel,
407 createReplyIntent(conversation, false)).addRemoteInput(remoteInput).build();
408 NotificationCompat.Action wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_wear_reply,
409 replyLabel,
410 createReplyIntent(conversation, true)).addRemoteInput(remoteInput).build();
411 mBuilder.extend(new NotificationCompat.WearableExtender().addAction(wearReplyAction));
412 mUnreadBuilder.setReplyAction(createReplyIntent(conversation, true), remoteInput);
413 mUnreadBuilder.setReadPendingIntent(markAsReadPendingIntent);
414 mBuilder.extend(new NotificationCompat.CarExtender().setUnreadConversation(mUnreadBuilder.build()));
415 int addedActionsCount = 1;
416 mBuilder.addAction(markReadAction);
417 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
418 mBuilder.addAction(replyAction);
419 ++addedActionsCount;
420 }
421
422 if (displaySnoozeAction(messages)) {
423 String label = mXmppConnectionService.getString(R.string.snooze);
424 PendingIntent pendingSnoozeIntent = createSnoozeIntent(conversation);
425 NotificationCompat.Action snoozeAction = new NotificationCompat.Action.Builder(
426 R.drawable.ic_notifications_paused_white_24dp,
427 label,
428 pendingSnoozeIntent).build();
429 mBuilder.addAction(snoozeAction);
430 ++addedActionsCount;
431 }
432 if (addedActionsCount < 3) {
433 final Message firstLocationMessage = getFirstLocationMessage(messages);
434 if (firstLocationMessage != null) {
435 String label = mXmppConnectionService.getResources().getString(R.string.show_location);
436 PendingIntent pendingShowLocationIntent = createShowLocationIntent(firstLocationMessage);
437 NotificationCompat.Action locationAction = new NotificationCompat.Action.Builder(
438 R.drawable.ic_room_white_24dp,
439 label,
440 pendingShowLocationIntent).build();
441 mBuilder.addAction(locationAction);
442 ++addedActionsCount;
443 }
444 }
445 if (addedActionsCount < 3) {
446 Message firstDownloadableMessage = getFirstDownloadableMessage(messages);
447 if (firstDownloadableMessage != null) {
448 String label = mXmppConnectionService.getResources().getString(R.string.download_x_file, UIHelper.getFileDescriptionString(mXmppConnectionService, firstDownloadableMessage));
449 PendingIntent pendingDownloadIntent = createDownloadIntent(firstDownloadableMessage);
450 NotificationCompat.Action downloadAction = new NotificationCompat.Action.Builder(
451 R.drawable.ic_file_download_white_24dp,
452 label,
453 pendingDownloadIntent).build();
454 mBuilder.addAction(downloadAction);
455 ++addedActionsCount;
456 }
457 }
458 }
459 if (conversation.getMode() == Conversation.MODE_SINGLE) {
460 Contact contact = conversation.getContact();
461 Uri systemAccount = contact.getSystemAccount();
462 if (systemAccount != null) {
463 mBuilder.addPerson(systemAccount.toString());
464 }
465 }
466 mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
467 mBuilder.setSmallIcon(R.drawable.ic_notification);
468 mBuilder.setDeleteIntent(createDeleteIntent(conversation));
469 mBuilder.setContentIntent(createContentIntent(conversation));
470 }
471 return mBuilder;
472 }
473
474 private static boolean displaySnoozeAction(List<Message> messages) {
475 int numberOfMessagesWithoutReply = 0;
476 for (Message message : messages) {
477 if (message.getStatus() == Message.STATUS_RECEIVED) {
478 ++numberOfMessagesWithoutReply;
479 } else {
480 return false;
481 }
482 }
483 return numberOfMessagesWithoutReply >= 3;
484 }
485
486 private void modifyForImage(final Builder builder, final UnreadConversation.Builder uBuilder,
487 final Message message, final ArrayList<Message> messages) {
488 try {
489 final Bitmap bitmap = mXmppConnectionService.getFileBackend()
490 .getThumbnail(message, getPixel(288), false);
491 final ArrayList<Message> tmp = new ArrayList<>();
492 for (final Message msg : messages) {
493 if (msg.getType() == Message.TYPE_TEXT
494 && msg.getTransferable() == null) {
495 tmp.add(msg);
496 }
497 }
498 final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
499 bigPictureStyle.bigPicture(bitmap);
500 if (tmp.size() > 0) {
501 CharSequence text = getMergedBodies(tmp);
502 bigPictureStyle.setSummaryText(text);
503 builder.setContentText(text);
504 } else {
505 builder.setContentText(UIHelper.getFileDescriptionString(mXmppConnectionService, message));
506 }
507 builder.setStyle(bigPictureStyle);
508 } catch (final IOException e) {
509 modifyForTextOnly(builder, uBuilder, messages);
510 }
511 }
512
513 private void modifyForTextOnly(final Builder builder, final UnreadConversation.Builder uBuilder, final ArrayList<Message> messages) {
514 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
515 NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(mXmppConnectionService.getString(R.string.me));
516 final Conversation conversation = (Conversation) messages.get(0).getConversation();
517 if (conversation.getMode() == Conversation.MODE_MULTI) {
518 messagingStyle.setConversationTitle(conversation.getName());
519 }
520 for (Message message : messages) {
521 String sender = message.getStatus() == Message.STATUS_RECEIVED ? UIHelper.getMessageDisplayName(message) : null;
522 messagingStyle.addMessage(UIHelper.getMessagePreview(mXmppConnectionService, message).first, message.getTimeSent(), sender);
523 }
524 builder.setStyle(messagingStyle);
525 } else {
526 if (messages.get(0).getConversation().getMode() == Conversation.MODE_SINGLE) {
527 builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
528 builder.setContentText(UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
529 } else {
530 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
531 SpannableString styledString;
532 for (Message message : messages) {
533 final String name = UIHelper.getMessageDisplayName(message);
534 styledString = new SpannableString(name + ": " + message.getBody());
535 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
536 style.addLine(styledString);
537 }
538 builder.setStyle(style);
539 int count = messages.size();
540 if (count == 1) {
541 final String name = UIHelper.getMessageDisplayName(messages.get(0));
542 styledString = new SpannableString(name + ": " + messages.get(0).getBody());
543 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
544 builder.setContentText(styledString);
545 } else {
546 builder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
547 }
548 }
549 }
550 /** message preview for Android Auto **/
551 for (Message message : messages) {
552 Pair<CharSequence, Boolean> preview = UIHelper.getMessagePreview(mXmppConnectionService, message);
553 // only show user written text
554 if (!preview.second) {
555 uBuilder.addMessage(preview.first.toString());
556 uBuilder.setLatestTimestamp(message.getTimeSent());
557 }
558 }
559 }
560
561 private Message getImage(final Iterable<Message> messages) {
562 Message image = null;
563 for (final Message message : messages) {
564 if (message.getStatus() != Message.STATUS_RECEIVED) {
565 return null;
566 }
567 if (message.getType() != Message.TYPE_TEXT
568 && message.getTransferable() == null
569 && message.getEncryption() != Message.ENCRYPTION_PGP
570 && message.getFileParams().height > 0) {
571 image = message;
572 }
573 }
574 return image;
575 }
576
577 private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
578 for (final Message message : messages) {
579 if (message.getTransferable() != null || (message.getType() == Message.TYPE_TEXT && message.treatAsDownloadable())) {
580 return message;
581 }
582 }
583 return null;
584 }
585
586 private Message getFirstLocationMessage(final Iterable<Message> messages) {
587 for (final Message message : messages) {
588 if (message.isGeoUri()) {
589 return message;
590 }
591 }
592 return null;
593 }
594
595 private CharSequence getMergedBodies(final ArrayList<Message> messages) {
596 final StringBuilder text = new StringBuilder();
597 for (Message message : messages) {
598 if (text.length() != 0) {
599 text.append("\n");
600 }
601 text.append(UIHelper.getMessagePreview(mXmppConnectionService, message).first);
602 }
603 return text.toString();
604 }
605
606 private PendingIntent createShowLocationIntent(final Message message) {
607 Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(mXmppConnectionService, message);
608 for (Intent intent : intents) {
609 if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
610 return PendingIntent.getActivity(mXmppConnectionService, generateRequestCode(message.getConversation(), 18), intent, PendingIntent.FLAG_UPDATE_CURRENT);
611 }
612 }
613 return createOpenConversationsIntent();
614 }
615
616 private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
617 final Intent viewConversationIntent = new Intent(mXmppConnectionService, ConversationsActivity.class);
618 viewConversationIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
619 viewConversationIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversationUuid);
620 if (downloadMessageUuid != null) {
621 viewConversationIntent.putExtra(ConversationsActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
622 return PendingIntent.getActivity(mXmppConnectionService,
623 generateRequestCode(conversationUuid, 8),
624 viewConversationIntent,
625 PendingIntent.FLAG_UPDATE_CURRENT);
626 } else {
627 return PendingIntent.getActivity(mXmppConnectionService,
628 generateRequestCode(conversationUuid, 10),
629 viewConversationIntent,
630 PendingIntent.FLAG_UPDATE_CURRENT);
631 }
632 }
633
634 private int generateRequestCode(String uuid, int actionId) {
635 return (actionId * NOTIFICATION_ID_MULTIPLIER) + (uuid.hashCode() % NOTIFICATION_ID_MULTIPLIER);
636 }
637
638 private int generateRequestCode(Conversational conversation, int actionId) {
639 return generateRequestCode(conversation.getUuid(), actionId);
640 }
641
642 private PendingIntent createDownloadIntent(final Message message) {
643 return createContentIntent(message.getConversationUuid(), message.getUuid());
644 }
645
646 private PendingIntent createContentIntent(final Conversational conversation) {
647 return createContentIntent(conversation.getUuid(), null);
648 }
649
650 private PendingIntent createDeleteIntent(Conversation conversation) {
651 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
652 intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
653 if (conversation != null) {
654 intent.putExtra("uuid", conversation.getUuid());
655 return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 20), intent, 0);
656 }
657 return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
658 }
659
660 private PendingIntent createReplyIntent(Conversation conversation, boolean dismissAfterReply) {
661 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
662 intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
663 intent.putExtra("uuid", conversation.getUuid());
664 intent.putExtra("dismiss_notification", dismissAfterReply);
665 final int id = generateRequestCode(conversation, dismissAfterReply ? 12 : 14);
666 return PendingIntent.getService(mXmppConnectionService, id, intent, 0);
667 }
668
669 private PendingIntent createReadPendingIntent(Conversation conversation) {
670 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
671 intent.setAction(XmppConnectionService.ACTION_MARK_AS_READ);
672 intent.putExtra("uuid", conversation.getUuid());
673 intent.setPackage(mXmppConnectionService.getPackageName());
674 return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 16), intent, PendingIntent.FLAG_UPDATE_CURRENT);
675 }
676
677 public PendingIntent createSnoozeIntent(Conversation conversation) {
678 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
679 intent.setAction(XmppConnectionService.ACTION_SNOOZE);
680 intent.putExtra("uuid", conversation.getUuid());
681 intent.setPackage(mXmppConnectionService.getPackageName());
682 return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 22), intent, PendingIntent.FLAG_UPDATE_CURRENT);
683 }
684
685 private PendingIntent createTryAgainIntent() {
686 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
687 intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
688 return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
689 }
690
691 private PendingIntent createDismissErrorIntent() {
692 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
693 intent.setAction(XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS);
694 return PendingIntent.getService(mXmppConnectionService, 69, intent, 0);
695 }
696
697 private boolean wasHighlightedOrPrivate(final Message message) {
698 if (message.getConversation() instanceof Conversation) {
699 Conversation conversation = (Conversation) message.getConversation();
700 final String nick = conversation.getMucOptions().getActualNick();
701 final Pattern highlight = generateNickHighlightPattern(nick);
702 if (message.getBody() == null || nick == null) {
703 return false;
704 }
705 final Matcher m = highlight.matcher(message.getBody());
706 return (m.find() || message.getType() == Message.TYPE_PRIVATE);
707 } else {
708 return false;
709 }
710 }
711
712 public static Pattern generateNickHighlightPattern(final String nick) {
713 return Pattern.compile("(?<=(^|\\s))" + Pattern.quote(nick) + "\\b");
714 }
715
716 public void setOpenConversation(final Conversation conversation) {
717 this.mOpenConversation = conversation;
718 }
719
720 public void setIsInForeground(final boolean foreground) {
721 this.mIsInForeground = foreground;
722 }
723
724 private int getPixel(final int dp) {
725 final DisplayMetrics metrics = mXmppConnectionService.getResources()
726 .getDisplayMetrics();
727 return ((int) (dp * metrics.density));
728 }
729
730 private void markLastNotification() {
731 this.mLastNotification = SystemClock.elapsedRealtime();
732 }
733
734 private boolean inMiniGracePeriod(final Account account) {
735 final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
736 : Config.MINI_GRACE_PERIOD * 2;
737 return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
738 }
739
740 public Notification createForegroundNotification() {
741 final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
742
743 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.conversations_foreground_service));
744 if (Config.SHOW_CONNECTED_ACCOUNTS) {
745 List<Account> accounts = mXmppConnectionService.getAccounts();
746 int enabled = 0;
747 int connected = 0;
748 for (Account account : accounts) {
749 if (account.isOnlineAndConnected()) {
750 connected++;
751 enabled++;
752 } else if (account.isEnabled()) {
753 enabled++;
754 }
755 }
756 mBuilder.setContentText(mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
757 } else {
758 mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_open_conversations));
759 }
760 mBuilder.setContentIntent(createOpenConversationsIntent());
761 mBuilder.setWhen(0);
762 mBuilder.setPriority(Config.SHOW_CONNECTED_ACCOUNTS ? NotificationCompat.PRIORITY_DEFAULT : NotificationCompat.PRIORITY_MIN);
763 mBuilder.setSmallIcon(R.drawable.ic_link_white_24dp);
764 return mBuilder.build();
765 }
766
767 private PendingIntent createOpenConversationsIntent() {
768 return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService, ConversationsActivity.class), 0);
769 }
770
771 public void updateErrorNotification() {
772 if (Config.SUPPRESS_ERROR_NOTIFICATION) {
773 cancel(ERROR_NOTIFICATION_ID);
774 return;
775 }
776 final List<Account> errors = new ArrayList<>();
777 for (final Account account : mXmppConnectionService.getAccounts()) {
778 if (account.hasErrorStatus() && account.showErrorNotification()) {
779 errors.add(account);
780 }
781 }
782 if (mXmppConnectionService.keepForegroundService()) {
783 notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
784 }
785 final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
786 if (errors.size() == 0) {
787 cancel(ERROR_NOTIFICATION_ID);
788 return;
789 } else if (errors.size() == 1) {
790 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
791 mBuilder.setContentText(errors.get(0).getJid().asBareJid().toString());
792 } else {
793 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
794 mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
795 }
796 mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
797 mXmppConnectionService.getString(R.string.try_again),
798 createTryAgainIntent());
799 mBuilder.setDeleteIntent(createDismissErrorIntent());
800 mBuilder.setVisibility(NotificationCompat.VISIBILITY_PRIVATE);
801 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
802 mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
803 } else {
804 mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
805 }
806 mBuilder.setLocalOnly(true);
807 mBuilder.setPriority(NotificationCompat.PRIORITY_LOW);
808 mBuilder.setContentIntent(PendingIntent.getActivity(mXmppConnectionService,
809 145,
810 new Intent(mXmppConnectionService, ManageAccountActivity.class),
811 PendingIntent.FLAG_UPDATE_CURRENT));
812 notify(ERROR_NOTIFICATION_ID, mBuilder.build());
813 }
814
815 public Notification updateFileAddingNotification(int current, Message message) {
816 NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
817 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.transcoding_video));
818 mBuilder.setProgress(100, current, false);
819 mBuilder.setSmallIcon(R.drawable.ic_hourglass_empty_white_24dp);
820 mBuilder.setContentIntent(createContentIntent(message.getConversation()));
821 Notification notification = mBuilder.build();
822 notify(FOREGROUND_NOTIFICATION_ID, notification);
823 return notification;
824 }
825
826 private void notify(String tag, int id, Notification notification) {
827 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
828 try {
829 notificationManager.notify(tag, id, notification);
830 } catch (RuntimeException e) {
831 Log.d(Config.LOGTAG, "unable to make notification", e);
832 }
833 }
834
835 private void notify(int id, Notification notification) {
836 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
837 try {
838 notificationManager.notify(id, notification);
839 } catch (RuntimeException e) {
840 Log.d(Config.LOGTAG, "unable to make notification", e);
841 }
842 }
843
844 private void cancel(int id) {
845 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
846 try {
847 notificationManager.cancel(id);
848 } catch (RuntimeException e) {
849 Log.d(Config.LOGTAG, "unable to cancel notification", e);
850 }
851 }
852
853 private void cancel(String tag, int id) {
854 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
855 try {
856 notificationManager.cancel(tag, id);
857 } catch (RuntimeException e) {
858 Log.d(Config.LOGTAG, "unable to cancel notification", e);
859 }
860 }
861}