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