conversations-classic/src/main/java/eu/siacs/conversations/services/NotificationService.java

741 lines
30 KiB
Java
Raw Normal View History

2014-09-28 13:21:56 +00:00
package eu.siacs.conversations.services;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Typeface;
2014-09-28 13:21:56 +00:00
import android.net.Uri;
import android.os.Build;
import android.os.SystemClock;
2014-09-28 13:21:56 +00:00
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.BigPictureStyle;
import android.support.v4.app.NotificationCompat.Builder;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.app.NotificationCompat.CarExtender.UnreadConversation;
2016-08-25 15:30:44 +00:00
import android.support.v4.app.RemoteInput;
import android.support.v4.content.ContextCompat;
import android.text.SpannableString;
import android.text.style.StyleSpan;
2014-10-21 12:57:16 +00:00
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Pair;
2014-09-28 13:21:56 +00:00
2014-11-05 20:37:40 +00:00
import java.io.FileNotFoundException;
import java.util.ArrayList;
2014-12-14 07:02:17 +00:00
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
2014-11-05 20:37:40 +00:00
import java.util.LinkedHashMap;
import java.util.List;
2016-08-25 13:20:06 +00:00
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
2014-11-05 20:37:40 +00:00
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import eu.siacs.conversations.Config;
2014-09-28 13:21:56 +00:00
import eu.siacs.conversations.R;
import eu.siacs.conversations.entities.Account;
2016-08-26 11:35:01 +00:00
import eu.siacs.conversations.entities.Contact;
2014-09-28 13:21:56 +00:00
import eu.siacs.conversations.entities.Conversation;
import eu.siacs.conversations.entities.Message;
import eu.siacs.conversations.ui.ConversationActivity;
import eu.siacs.conversations.ui.ManageAccountActivity;
2016-11-30 09:45:39 +00:00
import eu.siacs.conversations.ui.SettingsActivity;
2014-12-14 07:02:17 +00:00
import eu.siacs.conversations.ui.TimePreference;
import eu.siacs.conversations.utils.GeoHelper;
import eu.siacs.conversations.utils.UIHelper;
import eu.siacs.conversations.xmpp.XmppConnection;
2014-09-28 13:21:56 +00:00
public class NotificationService {
2016-08-25 13:20:06 +00:00
private static final String CONVERSATIONS_GROUP = "eu.siacs.conversations";
private final XmppConnectionService mXmppConnectionService;
2014-09-28 13:21:56 +00:00
2014-12-14 07:02:17 +00:00
private final LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<>();
2014-09-28 13:21:56 +00:00
private static final int NOTIFICATION_ID_MULTIPLIER = 1024 * 1024;
public static final int NOTIFICATION_ID = 2 * NOTIFICATION_ID_MULTIPLIER;
public static final int FOREGROUND_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 4;
public static final int ERROR_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 6;
2014-09-29 16:28:13 +00:00
private Conversation mOpenConversation;
private boolean mIsInForeground;
private long mLastNotification;
private final HashMap<Conversation,AtomicInteger> mBacklogMessageCounter = new HashMap<>();
public NotificationService(final XmppConnectionService service) {
2014-09-28 13:21:56 +00:00
this.mXmppConnectionService = service;
}
public boolean notify(final Message message) {
return message.getStatus() == Message.STATUS_RECEIVED
&& notificationsEnabled()
&& !message.getConversation().isMuted()
&& (message.getConversation().alwaysNotify() || wasHighlightedOrPrivate(message))
&& (!message.getConversation().isWithStranger() || notificationsFromStrangers())
;
2014-11-05 20:37:40 +00:00
}
public boolean notificationsEnabled() {
return mXmppConnectionService.getPreferences().getBoolean("show_notification", true);
}
private boolean notificationsFromStrangers() {
return mXmppConnectionService.getPreferences().getBoolean("notifications_from_strangers",
mXmppConnectionService.getResources().getBoolean(R.bool.notifications_from_strangers));
}
2014-12-14 07:02:17 +00:00
public boolean isQuietHours() {
if (!mXmppConnectionService.getPreferences().getBoolean("enable_quiet_hours", false)) {
return false;
}
2014-12-16 23:03:16 +00:00
final long startTime = mXmppConnectionService.getPreferences().getLong("quiet_hours_start", TimePreference.DEFAULT_VALUE) % Config.MILLISECONDS_IN_DAY;
final long endTime = mXmppConnectionService.getPreferences().getLong("quiet_hours_end", TimePreference.DEFAULT_VALUE) % Config.MILLISECONDS_IN_DAY;
final long nowTime = Calendar.getInstance().getTimeInMillis() % Config.MILLISECONDS_IN_DAY;
if (endTime < startTime) {
return nowTime > startTime || nowTime < endTime;
} else {
return nowTime > startTime && nowTime < endTime;
2014-12-14 07:02:17 +00:00
}
}
public void pushFromBacklog(final Message message) {
if (notify(message)) {
synchronized (notifications) {
getBacklogMessageCounter(message.getConversation()).incrementAndGet();
pushToStack(message);
}
}
}
private AtomicInteger getBacklogMessageCounter(Conversation conversation) {
synchronized (mBacklogMessageCounter) {
if (!mBacklogMessageCounter.containsKey(conversation)) {
mBacklogMessageCounter.put(conversation,new AtomicInteger(0));
}
return mBacklogMessageCounter.get(conversation);
}
}
2016-08-25 15:30:44 +00:00
public void pushFromDirectReply(final Message message) {
synchronized (notifications) {
pushToStack(message);
updateNotification(false);
}
}
public void finishBacklog(boolean notify, Account account) {
synchronized (notifications) {
mXmppConnectionService.updateUnreadCountBadge();
if (account == null || !notify) {
updateNotification(notify);
} else {
updateNotification(getBacklogMessageCount(account) > 0);
}
}
}
private int getBacklogMessageCount(Account account) {
int count = 0;
synchronized (this.mBacklogMessageCounter) {
for(Iterator<Map.Entry<Conversation, AtomicInteger>> it = mBacklogMessageCounter.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<Conversation, AtomicInteger> entry = it.next();
if (entry.getKey().getAccount() == account) {
count += entry.getValue().get();
it.remove();
}
}
}
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": backlog message count="+count);
return count;
}
public void finishBacklog(boolean notify) {
finishBacklog(notify,null);
}
private void pushToStack(final Message message) {
final String conversationUuid = message.getConversationUuid();
if (notifications.containsKey(conversationUuid)) {
notifications.get(conversationUuid).add(message);
} else {
final ArrayList<Message> mList = new ArrayList<>();
mList.add(message);
notifications.put(conversationUuid, mList);
}
}
public void push(final Message message) {
synchronized (message.getConversation().getAccount()) {
final XmppConnection connection = message.getConversation().getAccount().getXmppConnection();
if (connection.isWaitingForSmCatchup()) {
connection.incrementSmCatchupMessageCounter();
pushFromBacklog(message);
} else {
pushNow(message);
}
}
}
private void pushNow(final Message message) {
mXmppConnectionService.updateUnreadCountBadge();
2014-11-05 20:37:40 +00:00
if (!notify(message)) {
Log.d(Config.LOGTAG,message.getConversation().getAccount().getJid().toBareJid()+": suppressing notification because turned off");
2014-11-05 20:37:40 +00:00
return;
}
final boolean isScreenOn = mXmppConnectionService.isInteractive();
if (this.mIsInForeground && isScreenOn && this.mOpenConversation == message.getConversation()) {
Log.d(Config.LOGTAG,message.getConversation().getAccount().getJid().toBareJid()+": suppressing notification because conversation is open");
2014-10-07 11:37:50 +00:00
return;
}
2014-10-15 12:33:13 +00:00
synchronized (notifications) {
pushToStack(message);
final Account account = message.getConversation().getAccount();
final boolean doNotify = (!(this.mIsInForeground && this.mOpenConversation == null) || !isScreenOn)
&& !account.inGracePeriod()
&& !this.inMiniGracePeriod(account);
updateNotification(doNotify);
2014-09-28 13:21:56 +00:00
}
}
public void clear() {
2014-10-15 12:33:13 +00:00
synchronized (notifications) {
for(ArrayList<Message> messages : notifications.values()) {
markAsReadIfHasDirectReply(messages);
}
2014-10-15 12:33:13 +00:00
notifications.clear();
2014-10-21 22:25:28 +00:00
updateNotification(false);
2014-10-15 12:33:13 +00:00
}
2014-09-28 13:21:56 +00:00
}
public void clear(final Conversation conversation) {
synchronized (this.mBacklogMessageCounter) {
this.mBacklogMessageCounter.remove(conversation);
}
2014-10-15 12:33:13 +00:00
synchronized (notifications) {
markAsReadIfHasDirectReply(conversation);
2014-10-15 12:33:13 +00:00
notifications.remove(conversation.getUuid());
final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
notificationManager.cancel(conversation.getUuid(), NOTIFICATION_ID);
2014-10-21 22:25:28 +00:00
updateNotification(false);
2014-10-15 12:33:13 +00:00
}
2014-09-28 13:21:56 +00:00
}
private void markAsReadIfHasDirectReply(final Conversation conversation) {
markAsReadIfHasDirectReply(notifications.get(conversation.getUuid()));
}
private void markAsReadIfHasDirectReply(final ArrayList<Message> messages) {
if (messages != null && messages.size() > 0) {
Message last = messages.get(messages.size() - 1);
if (last.getStatus() != Message.STATUS_RECEIVED) {
if (mXmppConnectionService.markRead(last.getConversation(), false)) {
mXmppConnectionService.updateConversationUi();
}
}
}
}
private void setNotificationColor(final Builder mBuilder) {
mBuilder.setColor(ContextCompat.getColor(mXmppConnectionService, R.color.primary500));
}
2015-10-15 22:21:47 +00:00
public void updateNotification(final boolean notify) {
final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
final SharedPreferences preferences = mXmppConnectionService.getPreferences();
2014-09-28 13:21:56 +00:00
if (notifications.size() == 0) {
2014-10-21 12:57:16 +00:00
notificationManager.cancel(NOTIFICATION_ID);
2014-09-28 13:21:56 +00:00
} else {
if (notify) {
this.markLastNotification();
}
final Builder mBuilder;
2016-08-25 15:30:44 +00:00
if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
2016-08-25 13:20:06 +00:00
mBuilder = buildSingleConversations(notifications.values().iterator().next());
modifyForSoundVibrationAndLight(mBuilder, notify, preferences);
notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
2014-09-28 13:21:56 +00:00
} else {
mBuilder = buildMultipleConversation();
2016-08-25 13:20:06 +00:00
modifyForSoundVibrationAndLight(mBuilder, notify, preferences);
for(Map.Entry<String,ArrayList<Message>> entry : notifications.entrySet()) {
Builder singleBuilder = buildSingleConversations(entry.getValue());
singleBuilder.setGroup(CONVERSATIONS_GROUP);
modifyForSoundVibrationAndLight(singleBuilder,notify,preferences);
2016-08-25 15:30:44 +00:00
notificationManager.notify(entry.getKey(), NOTIFICATION_ID ,singleBuilder.build());
2014-09-28 13:21:56 +00:00
}
notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
2014-09-28 13:21:56 +00:00
}
2016-08-25 13:20:06 +00:00
}
}
private void modifyForSoundVibrationAndLight(Builder mBuilder, boolean notify, SharedPreferences preferences) {
final String ringtone = preferences.getString("notification_ringtone", null);
final boolean vibrate = preferences.getBoolean("vibrate_on_notification", true);
final boolean led = preferences.getBoolean("led", true);
if (notify && !isQuietHours()) {
if (vibrate) {
final int dat = 70;
final long[] pattern = {0, 3 * dat, dat, dat};
mBuilder.setVibrate(pattern);
} else {
mBuilder.setVibrate(new long[]{0});
}
2016-08-25 13:20:06 +00:00
if (ringtone != null) {
mBuilder.setSound(Uri.parse(ringtone));
}
2016-08-25 13:20:06 +00:00
}
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
}
mBuilder.setPriority(notify ? NotificationCompat.PRIORITY_DEFAULT : NotificationCompat.PRIORITY_LOW);
2016-08-25 13:20:06 +00:00
setNotificationColor(mBuilder);
mBuilder.setDefaults(0);
if (led) {
mBuilder.setLights(0xff00FF00, 2000, 3000);
2014-09-28 13:21:56 +00:00
}
}
private Builder buildMultipleConversation() {
final Builder mBuilder = new NotificationCompat.Builder(
mXmppConnectionService);
final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
style.setBigContentTitle(notifications.size()
+ " "
+ mXmppConnectionService
2014-11-05 20:37:40 +00:00
.getString(R.string.unread_conversations));
final StringBuilder names = new StringBuilder();
Conversation conversation = null;
for (final ArrayList<Message> messages : notifications.values()) {
if (messages.size() > 0) {
conversation = messages.get(0).getConversation();
final String name = conversation.getName();
SpannableString styledString;
if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
int count = messages.size();
styledString = new SpannableString(name + ": " + mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages,count,count));
styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
style.addLine(styledString);
} else {
styledString = new SpannableString(name + ": " + UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
style.addLine(styledString);
}
names.append(name);
names.append(", ");
}
}
if (names.length() >= 2) {
names.delete(names.length() - 2, names.length());
}
mBuilder.setContentTitle(notifications.size()
+ " "
+ mXmppConnectionService
2014-11-05 20:37:40 +00:00
.getString(R.string.unread_conversations));
mBuilder.setContentText(names.toString());
mBuilder.setStyle(style);
if (conversation != null) {
mBuilder.setContentIntent(createContentIntent(conversation));
}
2016-08-25 13:20:06 +00:00
mBuilder.setGroupSummary(true);
mBuilder.setGroup(CONVERSATIONS_GROUP);
mBuilder.setDeleteIntent(createDeleteIntent(null));
mBuilder.setSmallIcon(R.drawable.ic_notification);
return mBuilder;
}
2016-08-25 13:20:06 +00:00
private Builder buildSingleConversations(final ArrayList<Message> messages) {
final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
if (messages.size() >= 1) {
final Conversation conversation = messages.get(0).getConversation();
final UnreadConversation.Builder mUnreadBuilder = new UnreadConversation.Builder(conversation.getName());
mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
.get(conversation, getPixel(64)));
mBuilder.setContentTitle(conversation.getName());
if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
int count = messages.size();
mBuilder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages,count,count));
} else {
Message message;
if ((message = getImage(messages)) != null) {
modifyForImage(mBuilder, mUnreadBuilder, message, messages);
} else {
modifyForTextOnly(mBuilder, mUnreadBuilder, messages);
}
2016-09-06 10:13:50 +00:00
RemoteInput remoteInput = new RemoteInput.Builder("text_reply").setLabel(UIHelper.getMessageHint(mXmppConnectionService, conversation)).build();
NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(R.drawable.ic_send_text_offline, "Reply", createReplyIntent(conversation, false)).addRemoteInput(remoteInput).build();
NotificationCompat.Action wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_wear_reply, "Reply", createReplyIntent(conversation, true)).addRemoteInput(remoteInput).build();
mBuilder.extend(new NotificationCompat.WearableExtender().addAction(wearReplyAction));
mUnreadBuilder.setReplyAction(createReplyIntent(conversation, true), remoteInput);
mUnreadBuilder.setReadPendingIntent(createReadPendingIntent(conversation));
mBuilder.extend(new NotificationCompat.CarExtender().setUnreadConversation(mUnreadBuilder.build()));
2016-08-25 15:30:44 +00:00
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mBuilder.addAction(replyAction);
}
if ((message = getFirstDownloadableMessage(messages)) != null) {
mBuilder.addAction(
Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ?
R.drawable.ic_file_download_white_24dp : R.drawable.ic_action_download,
mXmppConnectionService.getResources().getString(R.string.download_x_file,
UIHelper.getFileDescriptionString(mXmppConnectionService, message)),
createDownloadIntent(message)
);
}
if ((message = getFirstLocationMessage(messages)) != null) {
mBuilder.addAction(R.drawable.ic_room_white_24dp,
mXmppConnectionService.getString(R.string.show_location),
createShowLocationIntent(message));
}
}
2016-08-26 11:35:01 +00:00
if (conversation.getMode() == Conversation.MODE_SINGLE) {
Contact contact = conversation.getContact();
Uri systemAccount = contact.getSystemAccount();
if (systemAccount != null) {
mBuilder.addPerson(systemAccount.toString());
}
}
2016-08-25 13:20:06 +00:00
mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
mBuilder.setSmallIcon(R.drawable.ic_notification);
mBuilder.setDeleteIntent(createDeleteIntent(conversation));
mBuilder.setContentIntent(createContentIntent(conversation));
}
return mBuilder;
}
private void modifyForImage(final Builder builder, final UnreadConversation.Builder uBuilder,
final Message message, final ArrayList<Message> messages) {
try {
final Bitmap bitmap = mXmppConnectionService.getFileBackend()
.getThumbnail(message, getPixel(288), false);
final ArrayList<Message> tmp = new ArrayList<>();
for (final Message msg : messages) {
if (msg.getType() == Message.TYPE_TEXT
2015-07-10 13:11:03 +00:00
&& msg.getTransferable() == null) {
tmp.add(msg);
}
}
final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
bigPictureStyle.bigPicture(bitmap);
if (tmp.size() > 0) {
2016-08-25 15:30:44 +00:00
CharSequence text = getMergedBodies(tmp);
bigPictureStyle.setSummaryText(text);
builder.setContentText(text);
} else {
builder.setContentText(mXmppConnectionService.getString(
R.string.received_x_file,
UIHelper.getFileDescriptionString(mXmppConnectionService, message)));
}
builder.setStyle(bigPictureStyle);
} catch (final FileNotFoundException e) {
modifyForTextOnly(builder, uBuilder, messages);
}
}
private void modifyForTextOnly(final Builder builder, final UnreadConversation.Builder uBuilder, final ArrayList<Message> messages) {
2016-08-25 13:20:06 +00:00
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(mXmppConnectionService.getString(R.string.me));
Conversation conversation = messages.get(0).getConversation();
if (conversation.getMode() == Conversation.MODE_MULTI) {
messagingStyle.setConversationTitle(conversation.getName());
}
2016-08-25 13:20:06 +00:00
for (Message message : messages) {
String sender = message.getStatus() == Message.STATUS_RECEIVED ? UIHelper.getMessageDisplayName(message) : null;
2016-08-25 15:30:44 +00:00
messagingStyle.addMessage(UIHelper.getMessagePreview(mXmppConnectionService,message).first, message.getTimeSent(), sender);
2016-08-25 13:20:06 +00:00
}
builder.setStyle(messagingStyle);
} else {
if(messages.get(0).getConversation().getMode() == Conversation.MODE_SINGLE) {
builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
builder.setContentText(UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
} else {
final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
SpannableString styledString;
for (Message message : messages) {
final String name = UIHelper.getMessageDisplayName(message);
styledString = new SpannableString(name + ": " + message.getBody());
styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
style.addLine(styledString);
}
builder.setStyle(style);
int count = messages.size();
if(count == 1) {
final String name = UIHelper.getMessageDisplayName(messages.get(0));
styledString = new SpannableString(name + ": " + messages.get(0).getBody());
styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
builder.setContentText(styledString);
} else {
builder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages,count,count));
}
}
}
/** message preview for Android Auto **/
for (Message message : messages) {
Pair<String,Boolean> preview = UIHelper.getMessagePreview(mXmppConnectionService, message);
// only show user written text
if (preview.second == false) {
uBuilder.addMessage(preview.first);
uBuilder.setLatestTimestamp(message.getTimeSent());
}
}
}
private Message getImage(final Iterable<Message> messages) {
2016-08-25 15:30:44 +00:00
Message image = null;
for (final Message message : messages) {
2016-08-25 15:30:44 +00:00
if (message.getStatus() != Message.STATUS_RECEIVED) {
return null;
}
if (message.getType() != Message.TYPE_TEXT
2015-07-10 13:11:03 +00:00
&& message.getTransferable() == null
&& message.getEncryption() != Message.ENCRYPTION_PGP
&& message.getFileParams().height > 0) {
2016-08-25 15:30:44 +00:00
image = message;
}
}
2016-08-25 15:30:44 +00:00
return image;
}
private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
for (final Message message : messages) {
if (message.getTransferable() != null || (message.getType() == Message.TYPE_TEXT && message.treatAsDownloadable())) {
return message;
}
}
return null;
}
private Message getFirstLocationMessage(final Iterable<Message> messages) {
for (final Message message : messages) {
if (GeoHelper.isGeoUri(message.getBody())) {
return message;
}
}
return null;
}
private CharSequence getMergedBodies(final ArrayList<Message> messages) {
final StringBuilder text = new StringBuilder();
for(Message message : messages) {
if (text.length() != 0) {
text.append("\n");
}
text.append(UIHelper.getMessagePreview(mXmppConnectionService, message).first);
}
return text.toString();
}
private PendingIntent createShowLocationIntent(final Message message) {
Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(message);
for (Intent intent : intents) {
if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
return PendingIntent.getActivity(mXmppConnectionService, 18, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
return createOpenConversationsIntent();
}
private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
final Intent viewConversationIntent = new Intent(mXmppConnectionService,ConversationActivity.class);
viewConversationIntent.setAction(ConversationActivity.ACTION_VIEW_CONVERSATION);
2016-08-25 13:20:06 +00:00
viewConversationIntent.putExtra(ConversationActivity.CONVERSATION, conversationUuid);
if (downloadMessageUuid != null) {
viewConversationIntent.putExtra(ConversationActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
return PendingIntent.getActivity(mXmppConnectionService,
(conversationUuid.hashCode() % NOTIFICATION_ID_MULTIPLIER) + 8 * NOTIFICATION_ID_MULTIPLIER,
viewConversationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
} else {
return PendingIntent.getActivity(mXmppConnectionService,
(conversationUuid.hashCode() % NOTIFICATION_ID_MULTIPLIER) + 10 * NOTIFICATION_ID_MULTIPLIER,
viewConversationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
2014-09-28 13:21:56 +00:00
}
private PendingIntent createDownloadIntent(final Message message) {
return createContentIntent(message.getConversationUuid(), message.getUuid());
}
private PendingIntent createContentIntent(final Conversation conversation) {
return createContentIntent(conversation.getUuid(), null);
}
2016-08-25 13:20:06 +00:00
private PendingIntent createDeleteIntent(Conversation conversation) {
final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
2016-08-25 13:20:06 +00:00
if (conversation != null) {
intent.putExtra("uuid", conversation.getUuid());
return PendingIntent.getService(mXmppConnectionService, (conversation.getUuid().hashCode() % NOTIFICATION_ID_MULTIPLIER) + 12 * NOTIFICATION_ID_MULTIPLIER, intent, 0);
2016-08-25 13:20:06 +00:00
}
return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
}
private PendingIntent createReplyIntent(Conversation conversation, boolean dismissAfterReply) {
2016-08-25 15:30:44 +00:00
final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
intent.putExtra("uuid",conversation.getUuid());
intent.putExtra("dismiss_notification",dismissAfterReply);
int id = (conversation.getUuid().hashCode() % NOTIFICATION_ID_MULTIPLIER) + (dismissAfterReply ? 12 : 14) * NOTIFICATION_ID_MULTIPLIER;
return PendingIntent.getService(mXmppConnectionService, id, intent, 0);
2016-08-25 15:30:44 +00:00
}
private PendingIntent createReadPendingIntent(Conversation conversation) {
final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
intent.setAction(XmppConnectionService.ACTION_MARK_AS_READ);
intent.putExtra("uuid", conversation.getUuid());
intent.setPackage(mXmppConnectionService.getPackageName());
return PendingIntent.getService(mXmppConnectionService, (conversation.getUuid().hashCode() % NOTIFICATION_ID_MULTIPLIER) + 16 * NOTIFICATION_ID_MULTIPLIER, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
private PendingIntent createDisableForeground() {
final Intent intent = new Intent(mXmppConnectionService,
XmppConnectionService.class);
intent.setAction(XmppConnectionService.ACTION_DISABLE_FOREGROUND);
2015-02-10 16:13:34 +00:00
return PendingIntent.getService(mXmppConnectionService, 34, intent, 0);
}
private PendingIntent createTryAgainIntent() {
final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
}
private PendingIntent createDismissErrorIntent() {
final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
intent.setAction(XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS);
return PendingIntent.getService(mXmppConnectionService, 69, intent, 0);
2014-10-02 15:36:02 +00:00
}
private boolean wasHighlightedOrPrivate(final Message message) {
final String nick = message.getConversation().getMucOptions().getActualNick();
final Pattern highlight = generateNickHighlightPattern(nick);
2014-10-03 09:55:38 +00:00
if (message.getBody() == null || nick == null) {
return false;
}
final Matcher m = highlight.matcher(message.getBody());
return (m.find() || message.getType() == Message.TYPE_PRIVATE);
}
public static Pattern generateNickHighlightPattern(final String nick) {
// We expect a word boundary, i.e. space or start of string, followed by
// the
// nick (matched in case-insensitive manner), followed by optional
// punctuation (for example "bob: i disagree" or "how are you alice?"),
// followed by another word boundary.
2015-04-28 07:32:58 +00:00
return Pattern.compile("\\b" + Pattern.quote(nick) + "\\p{Punct}?\\b",
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
}
public void setOpenConversation(final Conversation conversation) {
2014-09-29 16:28:13 +00:00
this.mOpenConversation = conversation;
}
public void setIsInForeground(final boolean foreground) {
2014-09-29 16:28:13 +00:00
this.mIsInForeground = foreground;
}
2014-10-21 12:57:16 +00:00
private int getPixel(final int dp) {
final DisplayMetrics metrics = mXmppConnectionService.getResources()
.getDisplayMetrics();
2014-10-21 12:57:16 +00:00
return ((int) (dp * metrics.density));
}
private void markLastNotification() {
this.mLastNotification = SystemClock.elapsedRealtime();
}
private boolean inMiniGracePeriod(final Account account) {
final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
: Config.MINI_GRACE_PERIOD * 2;
return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
}
public Notification createForegroundNotification() {
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
2015-01-22 04:00:35 +00:00
mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.conversations_foreground_service));
if (Config.SHOW_CONNECTED_ACCOUNTS) {
List<Account> accounts = mXmppConnectionService.getAccounts();
int enabled = 0;
int connected = 0;
for (Account account : accounts) {
if (account.isOnlineAndConnected()) {
connected++;
enabled++;
} else if (!account.isOptionSet(Account.OPTION_DISABLED)) {
enabled++;
}
}
mBuilder.setContentText(mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
} else {
mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_open_conversations));
}
mBuilder.setContentIntent(createOpenConversationsIntent());
mBuilder.setWhen(0);
mBuilder.setPriority(Config.SHOW_CONNECTED_ACCOUNTS ? NotificationCompat.PRIORITY_DEFAULT : NotificationCompat.PRIORITY_MIN);
2015-09-22 06:50:54 +00:00
mBuilder.setSmallIcon(R.drawable.ic_link_white_24dp);
if (Config.SHOW_DISABLE_FOREGROUND) {
2016-08-25 13:20:06 +00:00
final int cancelIcon;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBuilder.setCategory(Notification.CATEGORY_SERVICE);
cancelIcon = R.drawable.ic_cancel_white_24dp;
} else {
cancelIcon = R.drawable.ic_action_cancel;
}
mBuilder.addAction(cancelIcon,
mXmppConnectionService.getString(R.string.disable_foreground_service),
createDisableForeground());
}
return mBuilder.build();
}
private PendingIntent createOpenConversationsIntent() {
return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService, ConversationActivity.class), 0);
}
public void updateErrorNotification() {
final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
final List<Account> errors = new ArrayList<>();
for (final Account account : mXmppConnectionService.getAccounts()) {
if (account.hasErrorStatus() && account.showErrorNotification()) {
errors.add(account);
}
}
2016-11-30 09:45:39 +00:00
if (mXmppConnectionService.getPreferences().getBoolean(SettingsActivity.KEEP_FOREGROUND_SERVICE, false)) {
notificationManager.notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
}
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
if (errors.size() == 0) {
notificationManager.cancel(ERROR_NOTIFICATION_ID);
return;
} else if (errors.size() == 1) {
mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
mBuilder.setContentText(errors.get(0).getJid().toBareJid().toString());
} else {
mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
}
2015-02-10 16:13:34 +00:00
mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
mXmppConnectionService.getString(R.string.try_again),
createTryAgainIntent());
mBuilder.setDeleteIntent(createDismissErrorIntent());
mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
2015-01-22 04:00:35 +00:00
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
2015-04-28 12:28:51 +00:00
mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
2015-01-22 04:00:35 +00:00
} else {
mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
}
mBuilder.setContentIntent(PendingIntent.getActivity(mXmppConnectionService,
145,
new Intent(mXmppConnectionService,ManageAccountActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT));
notificationManager.notify(ERROR_NOTIFICATION_ID, mBuilder.build());
}
2014-09-28 13:21:56 +00:00
}