aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/eu/siacs/conversations/services/XmppConnectionService.java
diff options
context:
space:
mode:
Diffstat (limited to 'src/main/java/eu/siacs/conversations/services/XmppConnectionService.java')
-rw-r--r--src/main/java/eu/siacs/conversations/services/XmppConnectionService.java815
1 files changed, 173 insertions, 642 deletions
diff --git a/src/main/java/eu/siacs/conversations/services/XmppConnectionService.java b/src/main/java/eu/siacs/conversations/services/XmppConnectionService.java
index 09e5d1a9..72a5f8dd 100644
--- a/src/main/java/eu/siacs/conversations/services/XmppConnectionService.java
+++ b/src/main/java/eu/siacs/conversations/services/XmppConnectionService.java
@@ -7,7 +7,6 @@ import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
-import android.content.SharedPreferences;
import android.database.ContentObserver;
import android.graphics.Bitmap;
import android.media.AudioManager;
@@ -17,13 +16,11 @@ import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
-import android.os.FileObserver;
import android.os.IBinder;
import android.os.Looper;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.SystemClock;
-import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.security.KeyChain;
import android.util.DisplayMetrics;
@@ -47,11 +44,9 @@ import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
@@ -60,6 +55,16 @@ import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import de.duenndns.ssl.MemorizingTrustManager;
+import de.thedevstack.android.logcat.Logging;
+import de.thedevstack.conversationsplus.ConversationsPlusApplication;
+import de.thedevstack.conversationsplus.ConversationsPlusPreferences;
+import de.thedevstack.conversationsplus.exceptions.FileCopyException;
+import de.thedevstack.conversationsplus.utils.ImageUtil;
+import de.thedevstack.conversationsplus.utils.MessageUtil;
+import de.thedevstack.conversationsplus.utils.UiUpdateHelper;
+import de.thedevstack.conversationsplus.utils.XmppConnectionServiceAccessor;
+import de.thedevstack.conversationsplus.utils.XmppSendUtil;
+import de.tzur.conversations.Settings;
import eu.siacs.conversations.Config;
import eu.siacs.conversations.R;
import eu.siacs.conversations.crypto.PgpEngine;
@@ -74,7 +79,6 @@ import eu.siacs.conversations.entities.Message;
import eu.siacs.conversations.entities.MucOptions;
import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
import eu.siacs.conversations.entities.Presence;
-import eu.siacs.conversations.entities.PresenceTemplate;
import eu.siacs.conversations.entities.Roster;
import eu.siacs.conversations.entities.ServiceDiscoveryResult;
import eu.siacs.conversations.entities.Transferable;
@@ -83,7 +87,6 @@ import eu.siacs.conversations.generator.IqGenerator;
import eu.siacs.conversations.generator.MessageGenerator;
import eu.siacs.conversations.generator.PresenceGenerator;
import eu.siacs.conversations.http.HttpConnectionManager;
-import eu.siacs.conversations.parser.AbstractParser;
import eu.siacs.conversations.parser.IqParser;
import eu.siacs.conversations.parser.MessageParser;
import eu.siacs.conversations.parser.PresenceParser;
@@ -92,10 +95,10 @@ import eu.siacs.conversations.persistance.FileBackend;
import eu.siacs.conversations.ui.UiCallback;
import eu.siacs.conversations.utils.CryptoHelper;
import eu.siacs.conversations.utils.ExceptionHelper;
+import eu.siacs.conversations.utils.FileUtils;
import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
import eu.siacs.conversations.utils.PRNGFixes;
import eu.siacs.conversations.utils.PhoneHelper;
-import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
import eu.siacs.conversations.utils.Xmlns;
import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.OnBindListener;
@@ -116,7 +119,6 @@ import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
-import eu.siacs.conversations.xmpp.pep.Avatar;
import eu.siacs.conversations.xmpp.stanzas.IqPacket;
import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
@@ -131,11 +133,9 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
private static final String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
public static final String ACTION_GCM_TOKEN_REFRESH = "gcm_token_refresh";
public static final String ACTION_GCM_MESSAGE_RECEIVED = "gcm_message_received";
- private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor();
- private final SerialSingleThreadExecutor mDatabaseExecutor = new SerialSingleThreadExecutor();
private final IBinder mBinder = new XmppConnectionBinder();
private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
- private final IqGenerator mIqGenerator = new IqGenerator(this);
+ private final IqGenerator mIqGenerator = new IqGenerator();
private final List<String> mInProgressAvatarFetches = new ArrayList<>();
public DatabaseBackend databaseBackend;
private ContentObserver contactObserver = new ContentObserver(null) {
@@ -148,7 +148,6 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
startService(intent);
}
};
- private FileBackend fileBackend = new FileBackend(this);
private MemorizingTrustManager mMemorizingTrustManager;
private NotificationService mNotificationService = new NotificationService(
this);
@@ -162,13 +161,13 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
Element error = packet.findChild("error");
String text = error != null ? error.findChildContent("text") : null;
if (text != null) {
- Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": received iq error - " + text);
+ Logging.d(Config.LOGTAG, account.getJid().toBareJid() + ": received iq error - " + text);
}
}
}
};
- private MessageGenerator mMessageGenerator = new MessageGenerator(this);
- private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
+ private MessageGenerator mMessageGenerator = new MessageGenerator();
+ private PresenceGenerator mPresenceGenerator = new PresenceGenerator();
private List<Account> accounts;
private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
this);
@@ -200,20 +199,9 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
};
private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(
this);
- private AvatarService mAvatarService = new AvatarService(this);
private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
private PushManagementService mPushManagementService = new PushManagementService(this);
private OnConversationUpdate mOnConversationUpdate = null;
- private final FileObserver fileObserver = new FileObserver(
- FileBackend.getConversationsImageDirectory()) {
-
- @Override
- public void onEvent(int event, String path) {
- if (event == FileObserver.DELETE) {
- markFileDeleted(path.split("\\.")[0]);
- }
- }
- };
private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
@Override
@@ -229,7 +217,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
if (conversation.getAccount() == account) {
Message message = conversation.findUnsentMessageWithUuid(uuid);
if (message != null) {
- markMessage(message, Message.STATUS_SEND);
+ MessageUtil.markMessage(message, Message.STATUS_SEND);
}
}
}
@@ -289,10 +277,10 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
mMessageArchiveService.executePendingQueries(account);
if (connection != null && connection.getFeatures().csi()) {
if (checkListeners()) {
- Log.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//inactive");
+ Logging.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//inactive");
connection.sendInactive();
} else {
- Log.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//active");
+ Logging.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//active");
connection.sendActive();
}
}
@@ -301,7 +289,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
if (conversation.getAccount() == account
&& !account.pendingConferenceJoins.contains(conversation)) {
if (!conversation.startOtrIfNeeded()) {
- Log.d(Config.LOGTAG,account.getJid().toBareJid()+": couldn't start OTR with "+conversation.getContact().getJid()+" when needed");
+ Logging.d(Config.LOGTAG,account.getJid().toBareJid()+": couldn't start OTR with "+conversation.getContact().getJid()+" when needed");
}
sendUnsentMessages(conversation);
}
@@ -321,7 +309,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
final boolean pushMode = Config.CLOSE_TCP_WHEN_SWITCHING_TO_BACKGROUND
&& mPushManagementService.available(account)
&& checkListeners();
- Log.d(Config.LOGTAG,account.getJid().toBareJid()+": push mode "+Boolean.toString(pushMode));
+ Logging.d(Config.LOGTAG,account.getJid().toBareJid()+": push mode "+Boolean.toString(pushMode));
if (!disabled && !pushMode) {
int timeToReconnect = mRandom.nextInt(20) + 10;
scheduleWakeUpCall(timeToReconnect, account.getUuid().hashCode());
@@ -333,7 +321,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
&& (account.getStatus() != Account.State.NO_INTERNET)) {
if (connection != null) {
int next = connection.getTimeToNextAttempt();
- Log.d(Config.LOGTAG, account.getJid().toBareJid()
+ Logging.d(Config.LOGTAG, account.getJid().toBareJid()
+ ": error connecting account. try again in "
+ next + "s for the "
+ (connection.getAttempt() + 1) + " time");
@@ -353,10 +341,6 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
private boolean mRestoredFromDatabase = false;
- private static String generateFetchKey(Account account, final Avatar avatar) {
- return account.getJid().toBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum;
- }
-
public boolean areMessagesInitialized() {
return this.mRestoredFromDatabase;
}
@@ -374,117 +358,6 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
} else {
return null;
}
-
- }
-
- public FileBackend getFileBackend() {
- return this.fileBackend;
- }
-
- public AvatarService getAvatarService() {
- return this.mAvatarService;
- }
-
- public void attachLocationToConversation(final Conversation conversation,
- final Uri uri,
- final UiCallback<Message> callback) {
- int encryption = conversation.getNextEncryption();
- if (encryption == Message.ENCRYPTION_PGP) {
- encryption = Message.ENCRYPTION_DECRYPTED;
- }
- Message message = new Message(conversation, uri.toString(), encryption);
- if (conversation.getNextCounterpart() != null) {
- message.setCounterpart(conversation.getNextCounterpart());
- }
- if (encryption == Message.ENCRYPTION_DECRYPTED) {
- getPgpEngine().encrypt(message, callback);
- } else {
- callback.success(message);
- }
- }
-
- public void attachFileToConversation(final Conversation conversation,
- final Uri uri,
- final UiCallback<Message> callback) {
- if (FileBackend.weOwnFile(this, uri)) {
- Log.d(Config.LOGTAG,"trying to attach file that belonged to us");
- callback.error(R.string.security_error_invalid_file_access, null);
- return;
- }
- final Message message;
- if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
- message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
- } else {
- message = new Message(conversation, "", conversation.getNextEncryption());
- }
- message.setCounterpart(conversation.getNextCounterpart());
- message.setType(Message.TYPE_FILE);
- String path = getFileBackend().getOriginalPath(uri);
- if (path != null) {
- message.setRelativeFilePath(path);
- getFileBackend().updateFileParams(message);
- if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
- getPgpEngine().encrypt(message, callback);
- } else {
- callback.success(message);
- }
- } else {
- mFileAddingExecutor.execute(new Runnable() {
- @Override
- public void run() {
- try {
- getFileBackend().copyFileToPrivateStorage(message, uri);
- getFileBackend().updateFileParams(message);
- if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
- getPgpEngine().encrypt(message, callback);
- } else {
- callback.success(message);
- }
- } catch (FileBackend.FileCopyException e) {
- callback.error(e.getResId(), message);
- }
- }
- });
- }
- }
-
- public void attachImageToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
- if (FileBackend.weOwnFile(this, uri)) {
- Log.d(Config.LOGTAG,"trying to attach file that belonged to us");
- callback.error(R.string.security_error_invalid_file_access, null);
- return;
- }
- final String compressPictures = getCompressPicturesPreference();
- if ("never".equals(compressPictures)
- || ("auto".equals(compressPictures) && getFileBackend().useImageAsIs(uri))) {
- Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+ ": not compressing picture. sending as file");
- attachFileToConversation(conversation, uri, callback);
- return;
- }
- final Message message;
- if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
- message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
- } else {
- message = new Message(conversation, "", conversation.getNextEncryption());
- }
- message.setCounterpart(conversation.getNextCounterpart());
- message.setType(Message.TYPE_IMAGE);
- mFileAddingExecutor.execute(new Runnable() {
-
- @Override
- public void run() {
- try {
- getFileBackend().copyImageToPrivateStorage(message, uri);
- if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
- getPgpEngine().encrypt(message, callback);
- } else {
- callback.success(message);
- }
- } catch (final FileBackend.FileCopyException e) {
- callback.error(e.getResId(), message);
- }
- }
- });
}
public Conversation find(Bookmark bookmark) {
@@ -518,7 +391,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
mNotificationService.clear();
break;
case ACTION_DISABLE_FOREGROUND:
- getPreferences().edit().putBoolean("keep_foreground_service", false).commit();
+ ConversationsPlusPreferences.commitKeepForegroundService(false);
toggleForegroundService();
break;
case ACTION_TRY_AGAIN:
@@ -538,13 +411,13 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
}
break;
case AudioManager.RINGER_MODE_CHANGED_ACTION:
- if (xaOnSilentMode()) {
+ if (ConversationsPlusPreferences.xaOnSilentMode()) {
refreshAllPresences();
}
break;
case Intent.ACTION_SCREEN_OFF:
case Intent.ACTION_SCREEN_ON:
- if (awayWhenScreenOff()) {
+ if (ConversationsPlusPreferences.awayWhenScreenOff()) {
refreshAllPresences();
}
break;
@@ -582,7 +455,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
long pingTimeoutIn = (lastSent + Config.PING_TIMEOUT * 1000) - SystemClock.elapsedRealtime();
if (lastSent > lastReceived) {
if (pingTimeoutIn < 0) {
- Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": ping timeout");
+ Logging.d(Config.LOGTAG, account.getJid().toBareJid() + ": ping timeout");
this.reconnectAccount(account, true, interactive);
} else {
int secs = (int) (pingTimeoutIn / 1000);
@@ -604,7 +477,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
long discoTimeout = Config.CONNECT_DISCO_TIMEOUT - secondsSinceLastDisco;
long timeout = Config.CONNECT_TIMEOUT - secondsSinceLastConnect;
if (timeout < 0) {
- Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting");
+ Logging.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting");
account.getXmppConnection().resetAttemptCount();
reconnectAccount(account, true, interactive);
} else if (discoTimeout < 0) {
@@ -618,6 +491,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
reconnectAccount(account, true, interactive);
}
}
+
}
if (mOnAccountUpdate != null) {
mOnAccountUpdate.onAccountUpdate();
@@ -640,30 +514,10 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
return START_STICKY;
}
- private boolean xaOnSilentMode() {
- return getPreferences().getBoolean("xa_on_silent_mode", false);
- }
-
- private boolean manuallyChangePresence() {
- return getPreferences().getBoolean("manually_change_presence", false);
- }
-
- private boolean treatVibrateAsSilent() {
- return getPreferences().getBoolean("treat_vibrate_as_silent", false);
- }
-
- private boolean awayWhenScreenOff() {
- return getPreferences().getBoolean("away_when_screen_off", false);
- }
-
- private String getCompressPicturesPreference() {
- return getPreferences().getString("picture_compression", "auto");
- }
-
private Presence.Status getTargetPresence() {
- if (xaOnSilentMode() && isPhoneSilenced()) {
+ if (ConversationsPlusPreferences.xaOnSilentMode() && isPhoneSilenced()) {
return Presence.Status.XA;
- } else if (awayWhenScreenOff() && !isInteractive()) {
+ } else if (ConversationsPlusPreferences.awayWhenScreenOff() && !isInteractive()) {
return Presence.Status.AWAY;
} else {
return Presence.Status.ONLINE;
@@ -686,7 +540,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
private boolean isPhoneSilenced() {
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
- if (treatVibrateAsSilent()) {
+ if (ConversationsPlusPreferences.treatVibrateAsSilent()) {
return audioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL;
} else {
return audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT;
@@ -694,7 +548,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
}
private void resetAllAttemptCounts(boolean reallyAll) {
- Log.d(Config.LOGTAG, "resetting all attempt counts");
+ Logging.d(Config.LOGTAG, "resetting all attempt counts");
for (Account account : accounts) {
if (account.hasErrorStatus() || reallyAll) {
final XmppConnection connection = account.getXmppConnection();
@@ -712,6 +566,25 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
return activeNetwork != null && activeNetwork.isConnected();
}
+ /**
+ * check whether we are allowed to download at the moment
+ */
+ public boolean isDownloadAllowedInConnection() {
+ if (ConversationsPlusPreferences.autoDownloadFileWLAN()) {
+ return isWifiConnected();
+ }
+ return true;
+ }
+
+ /**
+ * check whether wifi is connected
+ */
+ public boolean isWifiConnected() {
+ ConnectivityManager cm = (ConnectivityManager) ConversationsPlusApplication.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
+ NetworkInfo niWifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
+ return niWifi.isConnected();
+ }
+
@SuppressLint("TrulyRandom")
@Override
public void onCreate() {
@@ -734,7 +607,6 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
restoreFromDatabase();
getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
- this.fileObserver.startWatching();
if (Config.supportOpenPgp()) {
this.pgpServiceConnection = new OpenPgpServiceConnection(getApplicationContext(), "org.sufficientlysecure.keychain", new OpenPgpServiceConnection.OnBound() {
@@ -758,6 +630,8 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "XmppConnectionService");
toggleForegroundService();
updateUnreadCountBadge();
+ UiUpdateHelper.initXmppConnectionService(this);
+ XmppConnectionServiceAccessor.initXmppConnectionService(this);
toggleScreenEventReceiver();
}
@@ -781,7 +655,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
}
public void toggleScreenEventReceiver() {
- if (awayWhenScreenOff() && !manuallyChangePresence()) {
+ if (ConversationsPlusPreferences.awayWhenScreenOff()) {
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(this.mEventReceiver, filter);
@@ -795,7 +669,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
}
public void toggleForegroundService() {
- if (getPreferences().getBoolean("keep_foreground_service", false)) {
+ if (ConversationsPlusPreferences.keepForegroundService()) {
startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
} else {
stopForeground(true);
@@ -805,7 +679,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
@Override
public void onTaskRemoved(final Intent rootIntent) {
super.onTaskRemoved(rootIntent);
- if (!getPreferences().getBoolean("keep_foreground_service", false)) {
+ if (!ConversationsPlusPreferences.keepForegroundService()) {
this.logoutAndSave(false);
}
}
@@ -827,7 +701,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
}
}
if (stop || activeAccounts == 0) {
- Log.d(Config.LOGTAG, "good bye");
+ Logging.d(Config.LOGTAG, "good bye");
stopSelf();
}
}
@@ -852,9 +726,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
}
public XmppConnection createConnection(final Account account) {
- final SharedPreferences sharedPref = getPreferences();
- account.setResource(sharedPref.getString("resource", getString(R.string.default_resource))
- .toLowerCase(Locale.getDefault()));
+ account.setResource(ConversationsPlusPreferences.resource().toLowerCase(Locale.getDefault()));
final XmppConnection connection = new XmppConnection(account, this);
connection.setOnMessagePacketReceivedListener(this.mMessageParser);
connection.setOnStatusChangedListener(this.statusListener);
@@ -864,7 +736,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
connection.setOnBindListener(this.mOnBindListener);
connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
- connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
+ connection.addOnAdvancedStreamFeaturesAvailableListener(AvatarService.getInstance());
AxolotlService axolotlService = account.getAxolotlService();
if (axolotlService != null) {
connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
@@ -873,16 +745,16 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
}
public void sendChatState(Conversation conversation) {
- if (sendChatStates()) {
+ if (ConversationsPlusPreferences.chatStates()) {
MessagePacket packet = mMessageGenerator.generateChatState(conversation);
sendMessagePacket(conversation.getAccount(), packet);
}
}
private void sendFileMessage(final Message message, final boolean delay) {
- Log.d(Config.LOGTAG, "send file message");
+ Logging.d(Config.LOGTAG, "send file message");
final Account account = message.getConversation().getAccount();
- if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())) {
+ if (account.httpUploadAvailable(FileBackend.getFile(message,false).getSize())) {
mHttpConnectionManager.createNewUploadConnection(message, delay);
} else {
mJingleConnectionManager.createNewConnection(message);
@@ -910,7 +782,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
new Conversation.OnMessageFound() {
@Override
public void onMessageFound(Message message) {
- markMessage(message, Message.STATUS_SEND_FAILED);
+ MessageUtil.markMessage(message, Message.STATUS_SEND_FAILED);
}
});
}
@@ -919,7 +791,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
switch (message.getEncryption()) {
case Message.ENCRYPTION_NONE:
if (message.needsUploading()) {
- if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
+ if (account.httpUploadAvailable(FileBackend.getFile(message,false).getSize())
|| message.fixCounterpart()) {
this.sendFileMessage(message, delay);
} else {
@@ -932,7 +804,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
case Message.ENCRYPTION_PGP:
case Message.ENCRYPTION_DECRYPTED:
if (message.needsUploading()) {
- if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
+ if (account.httpUploadAvailable(FileBackend.getFile(message,false).getSize())
|| message.fixCounterpart()) {
this.sendFileMessage(message, delay);
} else {
@@ -959,17 +831,17 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
if (message.fixCounterpart()) {
conversation.startOtrSession(message.getCounterpart().getResourcepart(), true);
} else {
- Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not fix counterpart for OTR message to contact "+message.getContact().getJid());
+ Logging.d(Config.LOGTAG,account.getJid().toBareJid()+": could not fix counterpart for OTR message to contact "+message.getContact().getJid());
break;
}
} else {
- Log.d(Config.LOGTAG,account.getJid().toBareJid()+" OTR session with "+message.getContact()+" is in wrong state: "+otrSession.getSessionStatus().toString());
+ Logging.d(Config.LOGTAG,account.getJid().toBareJid()+" OTR session with "+message.getContact()+" is in wrong state: "+otrSession.getSessionStatus().toString());
}
break;
case Message.ENCRYPTION_AXOLOTL:
message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
if (message.needsUploading()) {
- if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
+ if (account.httpUploadAvailable(FileBackend.getFile(message,false).getSize())
|| message.fixCounterpart()) {
this.sendFileMessage(message, delay);
} else {
@@ -1009,7 +881,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
break;
case Message.ENCRYPTION_OTR:
if (!conversation.hasValidOtrSession() && message.getCounterpart() != null) {
- Log.d(Config.LOGTAG,account.getJid().toBareJid()+": create otr session without starting for "+message.getContact().getJid());
+ Logging.d(Config.LOGTAG,account.getJid().toBareJid()+": create otr session without starting for "+message.getContact().getJid());
conversation.startOtrSession(message.getCounterpart().getResourcepart(), false);
}
break;
@@ -1022,16 +894,16 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
if (resend) {
if (packet != null && addToConversation) {
if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
- markMessage(message, Message.STATUS_UNSEND);
+ MessageUtil.markMessage(message, Message.STATUS_UNSEND);
} else {
- markMessage(message, Message.STATUS_SEND);
+ MessageUtil.markMessage(message, Message.STATUS_SEND);
}
}
} else {
if (addToConversation) {
conversation.add(message);
}
- if (message.getEncryption() == Message.ENCRYPTION_NONE || saveEncryptedMessages()) {
+ if (message.getEncryption() == Message.ENCRYPTION_NONE || !ConversationsPlusPreferences.dontSaveEncrypted()) {
if (saveInDb) {
databaseBackend.createMessage(message);
} else if (message.edited()) {
@@ -1045,7 +917,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
mMessageGenerator.addDelay(packet, message.getTimeSent());
}
if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
- if (this.sendChatStates()) {
+ if (ConversationsPlusPreferences.chatStates()) {
packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
}
}
@@ -1070,10 +942,10 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
public void fetchRosterFromServer(final Account account) {
final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
if (!"".equals(account.getRosterVersion())) {
- Log.d(Config.LOGTAG, account.getJid().toBareJid()
+ Logging.d(Config.LOGTAG, account.getJid().toBareJid()
+ ": fetching roster version " + account.getRosterVersion());
} else {
- Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
+ Logging.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
}
iqPacket.query(Xmlns.ROSTER).setAttribute("ver", account.getRosterVersion());
sendIqPacket(account, iqPacket, mIqParser);
@@ -1091,7 +963,6 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
final Element query = packet.query();
final HashMap<Jid, Bookmark> bookmarks = new HashMap<>();
final Element storage = query.findChild("storage", "storage:bookmarks");
- final boolean autojoin = respectAutojoin();
if (storage != null) {
for (final Element item : storage.getChildren()) {
if (item.getName().equals("conference")) {
@@ -1103,7 +974,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
Conversation conversation = find(bookmark);
if (conversation != null) {
conversation.setBookmark(bookmark);
- } else if (bookmark.autojoin() && bookmark.getJid() != null && autojoin) {
+ } else if (bookmark.autojoin() && bookmark.getJid() != null && ConversationsPlusPreferences.autojoin()) {
conversation = findOrCreateConversation(
account, bookmark.getJid(), true);
conversation.setBookmark(bookmark);
@@ -1114,7 +985,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
}
account.setBookmarks(new ArrayList<>(bookmarks.values()));
} else {
- Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not fetch bookmarks");
+ Logging.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not fetch bookmarks");
}
}
};
@@ -1122,7 +993,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
}
public void pushBookmarks(Account account) {
- Log.d(Config.LOGTAG, account.getJid().toBareJid()+": pushing bookmarks");
+ Logging.d(Config.LOGTAG, account.getJid().toBareJid()+": pushing bookmarks");
IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
Element query = iqPacket.query("jabber:iq:private");
Element storage = query.addChild("storage", "storage:bookmarks");
@@ -1139,12 +1010,12 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
mPhoneContactMergerThread = new Thread(new Runnable() {
@Override
public void run() {
- Log.d(Config.LOGTAG, "start merging phone contacts with roster");
+ Logging.d(Config.LOGTAG, "start merging phone contacts with roster");
for (Account account : accounts) {
List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
for (Bundle phoneContact : phoneContacts) {
if (Thread.interrupted()) {
- Log.d(Config.LOGTAG, "interrupted merging phone contacts");
+ Logging.d(Config.LOGTAG,"interrupted merging phone contacts");
return;
}
Jid jid;
@@ -1159,7 +1030,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
+ phoneContact.getString("lookup");
contact.setSystemAccount(systemAccount);
if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
- getAvatarService().clear(contact);
+ AvatarService.getInstance().clear(contact);
}
contact.setSystemName(phoneContact.getString("displayname"));
withSystemAccounts.remove(contact);
@@ -1168,11 +1039,11 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
contact.setSystemAccount(null);
contact.setSystemName(null);
if (contact.setPhotoUri(null)) {
- getAvatarService().clear(contact);
+ AvatarService.getInstance().clear(contact);
}
}
}
- Log.d(Config.LOGTAG, "finished merging phone contacts");
+ Logging.d(Config.LOGTAG,"finished merging phone contacts");
updateAccountUi();
}
});
@@ -1193,15 +1064,15 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
Runnable runnable = new Runnable() {
@Override
public void run() {
- Log.d(Config.LOGTAG, "restoring roster");
+ Logging.d(Config.LOGTAG, "restoring roster");
for (Account account : accounts) {
databaseBackend.readRoster(account.getRoster());
account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
}
- getBitmapCache().evictAll();
+ ImageUtil.evictBitmapCache();
Looper.prepare();
loadPhoneContacts();
- Log.d(Config.LOGTAG, "restoring messages");
+ Logging.d(Config.LOGTAG, "restoring messages");
for (Conversation conversation : conversations) {
conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
checkDeletedFiles(conversation);
@@ -1214,11 +1085,11 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
}
mNotificationService.finishBacklog(false);
mRestoredFromDatabase = true;
- Log.d(Config.LOGTAG, "restored all messages");
+ Logging.d(Config.LOGTAG,"restored all messages");
updateConversationUi();
}
};
- mDatabaseExecutor.execute(runnable);
+ ConversationsPlusApplication.executeDatabaseOperation(runnable);
}
}
@@ -1237,35 +1108,17 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
@Override
public void onMessageFound(Message message) {
- if (!getFileBackend().isFileAvailable(message)) {
+ if (!FileBackend.isFileAvailable(message)) {
message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
final int s = message.getStatus();
if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
- markMessage(message, Message.STATUS_SEND_FAILED);
+ MessageUtil.markMessage(message, Message.STATUS_SEND_FAILED);
}
}
}
});
}
- private void markFileDeleted(String uuid) {
- for (Conversation conversation : getConversations()) {
- Message message = conversation.findMessageWithFileAndUuid(uuid);
- if (message != null) {
- if (!getFileBackend().isFileAvailable(message)) {
- message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
- final int s = message.getStatus();
- if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
- markMessage(message, Message.STATUS_SEND_FAILED);
- } else {
- updateConversationUi();
- }
- }
- return;
- }
- }
- }
-
public void populateWithOrderedConversations(final List<Conversation> list) {
populateWithOrderedConversations(list, true);
}
@@ -1300,35 +1153,55 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
+ Logging.d("mam", "Query in progress");
return;
} else if (timestamp == 0) {
+ Logging.d("mam", "Query stopped due to timestamp");
return;
}
- Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
+ //TODO Create a separate class for this runnable to store if messages are getting loaded or not. Not really a good idea to do this in the callback.
+ Logging.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
Runnable runnable = new Runnable() {
@Override
public void run() {
+ if (null == callback || !callback.isLoadingInProgress()) { // if a callback is set, ensure that there is no loading in progress
+ if (null != callback) {
+ callback.setLoadingInProgress(); // Tell the callback that the loading is in progress
+ }
final Account account = conversation.getAccount();
List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
+ Logging.d("mam", "runnable load more messages");
if (messages.size() > 0) {
+ Logging.d("mam", "At least one message");
conversation.addAll(0, messages);
checkDeletedFiles(conversation);
callback.onMoreMessagesLoaded(messages.size(), conversation);
} else if (conversation.hasMessagesLeftOnServer()
- && account.isOnlineAndConnected()
- && conversation.getLastClearHistory() == 0) {
+ && account.isOnlineAndConnected()) {
+ Logging.d("mam", "account online and connected and messages left on server");
+ //TODO Check if this needs to be checked before trying anything with regards to MAM
if ((conversation.getMode() == Conversation.MODE_SINGLE && account.getXmppConnection().getFeatures().mam())
|| (conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().mamSupport())) {
- MessageArchiveService.Query query = getMessageArchiveService().query(conversation, 0, timestamp);
- if (query != null) {
- query.setCallback(callback);
- }
+ Logging.d("mam", "mam active");
+ getMessageArchiveService().query(conversation, 0, timestamp - 1, callback);
callback.informUser(R.string.fetching_history_from_server);
+ } else {
+ Logging.d("mam", "mam inactive");
+ callback.onMoreMessagesLoaded(0, conversation);
+ }
+ } else {
+ Logging.d("mam", ((!conversation.hasMessagesLeftOnServer()) ? "no" : "")
+ + " more messages left on server, mam "
+ + ((account.isOnlineAndConnected() && account.getXmppConnection().getFeatures().mam()) ? "" : "not")
+ + " activated, account is " + ((account.isOnlineAndConnected()) ? "" : "not")
+ + " online or connected)");
+ callback.onMoreMessagesLoaded(0, conversation);
+ callback.informUser(R.string.no_more_history_on_server);
}
}
}
};
- mDatabaseExecutor.execute(runnable);
+ ConversationsPlusApplication.executeDatabaseOperation(runnable);
}
public List<Account> getAccounts() {
@@ -1424,7 +1297,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
if (conversation.getMode() == Conversation.MODE_MULTI) {
if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
Bookmark bookmark = conversation.getBookmark();
- if (bookmark != null && bookmark.autojoin() && respectAutojoin()) {
+ if (bookmark != null && bookmark.autojoin() && ConversationsPlusPreferences.autojoin()) {
bookmark.setAutojoin(false);
pushBookmarks(bookmark.getAccount());
}
@@ -1558,7 +1431,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
databaseBackend.deleteAccount(account);
}
};
- mDatabaseExecutor.execute(runnable);
+ ConversationsPlusApplication.executeDatabaseOperation(runnable);
this.accounts.remove(account);
updateAccountUi();
getNotificationService().updateErrorNotification();
@@ -1768,7 +1641,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
}
}
- public boolean checkListeners() {
+ private boolean checkListeners() {
return (this.mOnAccountUpdate == null
&& this.mOnConversationUpdate == null
&& this.mOnRosterUpdate == null
@@ -1790,7 +1663,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
}
}
}
- Log.d(Config.LOGTAG, "app switched into foreground");
+ Logging.d(Config.LOGTAG, "app switched into foreground");
}
private void switchToBackground() {
@@ -1809,7 +1682,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
}
}
this.mNotificationService.setIsInForeground(false);
- Log.d(Config.LOGTAG, "app switched into background");
+ Logging.d(Config.LOGTAG, "app switched into background");
}
private void connectMultiModeConversations(Account account) {
@@ -1839,7 +1712,8 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
final MucOptions mucOptions = conversation.getMucOptions();
final Jid joinJid = mucOptions.getSelf().getFullJid();
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
- PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE);
+ PresencePacket packet = new PresencePacket();
+ packet.setFrom(conversation.getAccount().getJid());
packet.setTo(joinJid);
Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
if (conversation.getMucOptions().getPassword() != null) {
@@ -1853,6 +1727,10 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
// Fallback to muc history
x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
}
+ String sig = account.getPgpSignature();
+ if (sig != null) {
+ packet.addChild("x", "jabber:x:signed").setContent(sig);
+ }
sendPresencePacket(account, packet);
if (onConferenceJoined != null) {
onConferenceJoined.onConferenceJoined(conversation);
@@ -1900,7 +1778,6 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
@Override
public void onIqPacketReceived(Account account, IqPacket packet) {
-
Element query = packet.query("http://jabber.org/protocol/muc#admin");
if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
for(Element child : query.getChildren()) {
@@ -1933,9 +1810,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
if (conversation.getMode() == Conversation.MODE_MULTI) {
conversation.getMucOptions().setPassword(password);
if (conversation.getBookmark() != null) {
- if (respectAutojoin()) {
- conversation.getBookmark().setAutojoin(true);
- }
+ conversation.getBookmark().setAutojoin(ConversationsPlusPreferences.autojoin());
pushBookmarks(conversation.getAccount());
}
databaseBackend.updateConversation(conversation);
@@ -2008,7 +1883,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
sendPresencePacket(conversation.getAccount(), packet);
conversation.getMucOptions().setOffline();
conversation.deregisterWithBookmark();
- Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
+ Logging.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
+ ": leaving muc " + conversation.getJid());
} else {
account.pendingConferenceLeaves.add(conversation);
@@ -2035,7 +1910,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
}
public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
- Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
+ Logging.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
if (account.getStatus() == Account.State.ONLINE) {
try {
String server = findConferenceServer(account);
@@ -2213,11 +2088,11 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
- Log.d(Config.LOGTAG, request.toString());
+ Logging.d(Config.LOGTAG, request.toString());
sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
@Override
public void onIqPacketReceived(Account account, IqPacket packet) {
- Log.d(Config.LOGTAG, packet.toString());
+ Logging.d(Config.LOGTAG, packet.toString());
if (packet.getType() == IqPacket.TYPE.RESULT) {
callback.onRoleChangedSuccessful(nick);
} else {
@@ -2238,7 +2113,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
leaveMuc(conversation, true);
} else {
if (conversation.endOtrIfNeeded()) {
- Log.d(Config.LOGTAG, account.getJid().toBareJid()
+ Logging.d(Config.LOGTAG, account.getJid().toBareJid()
+ ": ended otr session with "
+ conversation.getJid());
}
@@ -2261,11 +2136,6 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
updateConversationUi();
}
- public void updateMessage(Message message, String uuid) {
- databaseBackend.updateMessage(message, uuid);
- updateConversationUi();
- }
-
protected void syncDirtyContacts(Account account) {
for (Contact contact : account.getRoster().getContacts()) {
if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
@@ -2278,8 +2148,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
}
public void createContact(Contact contact) {
- boolean autoGrant = getPreferences().getBoolean("grant_new_contacts", true);
- if (autoGrant) {
+ if (ConversationsPlusPreferences.grantNewContacts()) {
contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
contact.setOption(Contact.Options.ASKING);
}
@@ -2289,7 +2158,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
public void onOtrSessionEstablished(Conversation conversation) {
final Account account = conversation.getAccount();
final Session otrSession = conversation.getOtrSession();
- Log.d(Config.LOGTAG,
+ Logging.d(Config.LOGTAG,
account.getJid().toBareJid() + " otr session established with "
+ conversation.getJid() + "/"
+ otrSession.getSessionID().getUserID());
@@ -2368,272 +2237,6 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
}
}
- public void publishAvatar(Account account, Uri image, UiCallback<Avatar> callback) {
- final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
- final int size = Config.AVATAR_SIZE;
- final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
- if (avatar != null) {
- avatar.height = size;
- avatar.width = size;
- if (format.equals(Bitmap.CompressFormat.WEBP)) {
- avatar.type = "image/webp";
- } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
- avatar.type = "image/jpeg";
- } else if (format.equals(Bitmap.CompressFormat.PNG)) {
- avatar.type = "image/png";
- }
- if (!getFileBackend().save(avatar)) {
- callback.error(R.string.error_saving_avatar, avatar);
- return;
- }
- publishAvatar(account, avatar, callback);
- } else {
- callback.error(R.string.error_publish_avatar_converting, null);
- }
- }
-
- public void publishAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
- final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
- this.sendIqPacket(account, packet, new OnIqPacketReceived() {
-
- @Override
- public void onIqPacketReceived(Account account, IqPacket result) {
- if (result.getType() == IqPacket.TYPE.RESULT) {
- final IqPacket packet = XmppConnectionService.this.mIqGenerator
- .publishAvatarMetadata(avatar);
- sendIqPacket(account, packet, new OnIqPacketReceived() {
- @Override
- public void onIqPacketReceived(Account account, IqPacket result) {
- if (result.getType() == IqPacket.TYPE.RESULT) {
- if (account.setAvatar(avatar.getFilename())) {
- getAvatarService().clear(account);
- databaseBackend.updateAccount(account);
- }
- if (callback != null) {
- callback.success(avatar);
- } else {
- Log.d(Config.LOGTAG,account.getJid().toBareJid()+": published avatar");
- }
- } else {
- if (callback != null) {
- callback.error(
- R.string.error_publish_avatar_server_reject,
- avatar);
- }
- }
- }
- });
- } else {
- if (callback != null) {
- callback.error(
- R.string.error_publish_avatar_server_reject,
- avatar);
- }
- }
- }
- });
- }
-
- public void republishAvatarIfNeeded(Account account) {
- if (account.getAxolotlService().isPepBroken()) {
- Log.d(Config.LOGTAG,account.getJid().toBareJid()+": skipping republication of avatar because pep is broken");
- return;
- }
- IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
- this.sendIqPacket(account, packet, new OnIqPacketReceived() {
-
- private Avatar parseAvatar(IqPacket packet) {
- Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
- if (pubsub != null) {
- Element items = pubsub.findChild("items");
- if (items != null) {
- return Avatar.parseMetadata(items);
- }
- }
- return null;
- }
-
- private boolean errorIsItemNotFound(IqPacket packet) {
- Element error = packet.findChild("error");
- return packet.getType() == IqPacket.TYPE.ERROR
- && error != null
- && error.hasChild("item-not-found");
- }
-
- @Override
- public void onIqPacketReceived(Account account, IqPacket packet) {
- if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
- Avatar serverAvatar = parseAvatar(packet);
- if (serverAvatar == null && account.getAvatar() != null) {
- Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
- if (avatar != null) {
- Log.d(Config.LOGTAG,account.getJid().toBareJid()+": avatar on server was null. republishing");
- publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
- } else {
- Log.e(Config.LOGTAG, account.getJid().toBareJid()+": error rereading avatar");
- }
- }
- }
- }
- });
- }
-
- public void fetchAvatar(Account account, Avatar avatar) {
- fetchAvatar(account, avatar, null);
- }
-
- public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
- final String KEY = generateFetchKey(account, avatar);
- synchronized (this.mInProgressAvatarFetches) {
- if (!this.mInProgressAvatarFetches.contains(KEY)) {
- switch (avatar.origin) {
- case PEP:
- this.mInProgressAvatarFetches.add(KEY);
- fetchAvatarPep(account, avatar, callback);
- break;
- case VCARD:
- this.mInProgressAvatarFetches.add(KEY);
- fetchAvatarVcard(account, avatar, callback);
- break;
- }
- }
- }
- }
-
- private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
- IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
- sendIqPacket(account, packet, new OnIqPacketReceived() {
-
- @Override
- public void onIqPacketReceived(Account account, IqPacket result) {
- synchronized (mInProgressAvatarFetches) {
- mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
- }
- final String ERROR = account.getJid().toBareJid()
- + ": fetching avatar for " + avatar.owner + " failed ";
- if (result.getType() == IqPacket.TYPE.RESULT) {
- avatar.image = mIqParser.avatarData(result);
- if (avatar.image != null) {
- if (getFileBackend().save(avatar)) {
- if (account.getJid().toBareJid().equals(avatar.owner)) {
- if (account.setAvatar(avatar.getFilename())) {
- databaseBackend.updateAccount(account);
- }
- getAvatarService().clear(account);
- updateConversationUi();
- updateAccountUi();
- } else {
- Contact contact = account.getRoster()
- .getContact(avatar.owner);
- contact.setAvatar(avatar);
- getAvatarService().clear(contact);
- updateConversationUi();
- updateRosterUi();
- }
- if (callback != null) {
- callback.success(avatar);
- }
- Log.d(Config.LOGTAG, account.getJid().toBareJid()
- + ": successfully fetched pep avatar for " + avatar.owner);
- return;
- }
- } else {
-
- Log.d(Config.LOGTAG, ERROR + "(parsing error)");
- }
- } else {
- Element error = result.findChild("error");
- if (error == null) {
- Log.d(Config.LOGTAG, ERROR + "(server error)");
- } else {
- Log.d(Config.LOGTAG, ERROR + error.toString());
- }
- }
- if (callback != null) {
- callback.error(0, null);
- }
-
- }
- });
- }
-
- private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
- IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
- this.sendIqPacket(account, packet, new OnIqPacketReceived() {
- @Override
- public void onIqPacketReceived(Account account, IqPacket packet) {
- synchronized (mInProgressAvatarFetches) {
- mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
- }
- if (packet.getType() == IqPacket.TYPE.RESULT) {
- Element vCard = packet.findChild("vCard", "vcard-temp");
- Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
- String image = photo != null ? photo.findChildContent("BINVAL") : null;
- if (image != null) {
- avatar.image = image;
- if (getFileBackend().save(avatar)) {
- Log.d(Config.LOGTAG, account.getJid().toBareJid()
- + ": successfully fetched vCard avatar for " + avatar.owner);
- if (avatar.owner.isBareJid()) {
- Contact contact = account.getRoster()
- .getContact(avatar.owner);
- contact.setAvatar(avatar);
- getAvatarService().clear(contact);
- updateConversationUi();
- updateRosterUi();
- } else {
- Conversation conversation = find(account, avatar.owner.toBareJid());
- if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
- MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
- if (user != null) {
- if (user.setAvatar(avatar)) {
- getAvatarService().clear(user);
- updateConversationUi();
- updateMucRosterUi();
- }
- }
- }
- }
- }
- }
- }
- }
- });
- }
-
- public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
- IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
- this.sendIqPacket(account, packet, new OnIqPacketReceived() {
-
- @Override
- public void onIqPacketReceived(Account account, IqPacket packet) {
- if (packet.getType() == IqPacket.TYPE.RESULT) {
- Element pubsub = packet.findChild("pubsub","http://jabber.org/protocol/pubsub");
- if (pubsub != null) {
- Element items = pubsub.findChild("items");
- if (items != null) {
- Avatar avatar = Avatar.parseMetadata(items);
- if (avatar != null) {
- avatar.owner = account.getJid().toBareJid();
- if (fileBackend.isAvatarCached(avatar)) {
- if (account.setAvatar(avatar.getFilename())) {
- databaseBackend.updateAccount(account);
- }
- getAvatarService().clear(account);
- callback.success(avatar);
- } else {
- fetchAvatarPep(account, avatar, callback);
- }
- return;
- }
- }
- }
- }
- callback.error(0, null);
- }
- });
- }
-
public void deleteContactOnServer(Contact contact) {
contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
contact.resetOption(Contact.Options.DIRTY_PUSH);
@@ -2689,7 +2292,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
}
public void invite(Conversation conversation, Jid contact) {
- Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
+ Logging.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
MessagePacket packet = mMessageGenerator.invite(conversation, contact);
sendMessagePacket(conversation.getAccount(), packet);
}
@@ -2706,7 +2309,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
@Override
public void onMessageFound(Message message) {
- markMessage(message, Message.STATUS_WAITING);
+ MessageUtil.markMessage(message, Message.STATUS_WAITING);
}
});
}
@@ -2721,7 +2324,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
if (message != null) {
- markMessage(message, status);
+ MessageUtil.markMessage(message, status);
}
return message;
}
@@ -2729,68 +2332,6 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
return null;
}
- public boolean markMessage(Conversation conversation, String uuid, int status) {
- if (uuid == null) {
- return false;
- } else {
- Message message = conversation.findSentMessageWithUuid(uuid);
- if (message != null) {
- markMessage(message, status);
- return true;
- } else {
- return false;
- }
- }
- }
-
- public void markMessage(Message message, int status) {
- if (status == Message.STATUS_SEND_FAILED
- && (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
- .getStatus() == Message.STATUS_SEND_DISPLAYED)) {
- return;
- }
- message.setStatus(status);
- databaseBackend.updateMessage(message);
- updateConversationUi();
- }
-
- public SharedPreferences getPreferences() {
- return PreferenceManager
- .getDefaultSharedPreferences(getApplicationContext());
- }
-
- public boolean confirmMessages() {
- return getPreferences().getBoolean("confirm_messages", true);
- }
-
- public boolean allowMessageCorrection() {
- return getPreferences().getBoolean("allow_message_correction", false);
- }
-
- public boolean sendChatStates() {
- return getPreferences().getBoolean("chat_states", false);
- }
-
- public boolean saveEncryptedMessages() {
- return !getPreferences().getBoolean("dont_save_encrypted", false);
- }
-
- private boolean respectAutojoin() {
- return getPreferences().getBoolean("autojoin", true);
- }
-
- public boolean indicateReceived() {
- return getPreferences().getBoolean("indicate_received", false);
- }
-
- public boolean useTorToConnect() {
- return Config.FORCE_ORBOT || getPreferences().getBoolean("use_tor", false);
- }
-
- public boolean showExtendedConnectionOptions() {
- return getPreferences().getBoolean("show_connection_options", false);
- }
-
public int unreadCount() {
int count = 0;
for (Conversation conversation : getConversations()) {
@@ -2884,7 +2425,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
}
}
};
- mDatabaseExecutor.execute(runnable);
+ ConversationsPlusApplication.executeDatabaseOperation(runnable);
updateUnreadCountBadge();
return true;
} else {
@@ -2895,7 +2436,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
public synchronized void updateUnreadCountBadge() {
int count = unreadCount();
if (unreadCount != count) {
- Log.d(Config.LOGTAG, "update unread count to " + count);
+ Logging.d(Config.LOGTAG, "update unread count to " + count);
if (count > 0) {
ShortcutBadger.applyCount(getApplicationContext(), count);
} else {
@@ -2907,11 +2448,12 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
public void sendReadMarker(final Conversation conversation) {
final Message markable = conversation.getLatestMarkableMessage();
+ Logging.d("markRead", "XmppConnectionService.sendReadMarker (" + conversation.getName() + ")");
if (this.markRead(conversation)) {
updateConversationUi();
}
- if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
- Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
+ if (Settings.CONFIRM_MESSAGE_READ && markable != null && markable.getRemoteMsgId() != null) {
+ Logging.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
Account account = conversation.getAccount();
final Jid to = markable.getCounterpart();
MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
@@ -2933,8 +2475,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
public void updateMemorizingTrustmanager() {
final MemorizingTrustManager tm;
- final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
- if (dontTrustSystemCAs) {
+ if (ConversationsPlusPreferences.dontTrustSystemCAs()) {
tm = new MemorizingTrustManager(getApplicationContext(), null);
} else {
tm = new MemorizingTrustManager(getApplicationContext());
@@ -2958,8 +2499,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
databaseBackend.writeRoster(account.getRoster());
}
};
- mDatabaseExecutor.execute(runnable);
-
+ ConversationsPlusApplication.executeDatabaseOperation(runnable);
}
public List<String> getKnownHosts() {
@@ -2999,33 +2539,26 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
return mucServers;
}
+ @Deprecated
public void sendMessagePacket(Account account, MessagePacket packet) {
- XmppConnection connection = account.getXmppConnection();
- if (connection != null) {
- connection.sendMessagePacket(packet);
- }
+ XmppSendUtil.sendMessagePacket(account, packet);
}
+ @Deprecated
public void sendPresencePacket(Account account, PresencePacket packet) {
- XmppConnection connection = account.getXmppConnection();
- if (connection != null) {
- connection.sendPresencePacket(packet);
- }
+ XmppSendUtil.sendPresencePacket(account, packet);
}
public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
- final XmppConnection connection = account.getXmppConnection();
+ XmppConnection connection = account.getXmppConnection();
if (connection != null) {
- IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
- sendIqPacket(account, request, connection.registrationResponseListener);
+ connection.sendCaptchaRegistryRequest(id, data);
}
}
+ @Deprecated
public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
- final XmppConnection connection = account.getXmppConnection();
- if (connection != null) {
- connection.sendIqPacket(packet, callback);
- }
+ XmppSendUtil.sendIqPacket(account, packet, callback);
}
public void sendPresence(final Account account) {
@@ -3039,7 +2572,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
} else {
packet = mPresenceGenerator.selfPresence(account, getTargetPresence());
}
- sendPresencePacket(account, packet);
+ XmppSendUtil.sendPresencePacket(account, packet);
}
public void refreshAllPresences() {
@@ -3059,7 +2592,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
}
public void sendOfflinePresence(final Account account) {
- sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
+ XmppSendUtil.sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
}
public MessageGenerator getMessageGenerator() {
@@ -3108,34 +2641,28 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
}
public void resendFailedMessages(final Message message) {
- final Collection<Message> messages = new ArrayList<>();
- Message current = message;
- while (current.getStatus() == Message.STATUS_SEND_FAILED) {
- messages.add(current);
- if (current.mergeable(current.next())) {
- current = current.next();
- } else {
- break;
- }
- }
- for (final Message msg : messages) {
- msg.setTime(System.currentTimeMillis());
- markMessage(msg, Message.STATUS_WAITING);
- this.resendMessage(msg, false);
+ if (message.getStatus() == Message.STATUS_SEND_FAILED) {
+ message.setTime(System.currentTimeMillis());
+ MessageUtil.markMessage(message, Message.STATUS_WAITING);
+ this.resendMessage(message, false);
}
}
public void clearConversationHistory(final Conversation conversation) {
conversation.clearMessages();
- conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
- conversation.setLastClearHistory(System.currentTimeMillis());
+ /*
+ * In case the history was loaded completely before.
+ * The flag "hasMessagesLeftOnServer" is set to false and no messages will be loaded anymore
+ * Therefore set this flag to true and try to get messages from server
+ */
+ conversation.setHasMessagesLeftOnServer(true);
Runnable runnable = new Runnable() {
@Override
public void run() {
databaseBackend.deleteMessagesInConversation(conversation);
}
};
- mDatabaseExecutor.execute(runnable);
+ ConversationsPlusApplication.executeDatabaseOperation(runnable);
}
public void sendBlockRequest(final Blockable blockable) {
@@ -3177,7 +2704,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
@Override
public void onIqPacketReceived(Account account, IqPacket packet) {
if (packet.getType() == IqPacket.TYPE.ERROR) {
- Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not publish nick");
+ Logging.d(Config.LOGTAG,account.getJid().toBareJid()+": could not publish nick");
}
}
});
@@ -3218,7 +2745,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
databaseBackend.insertDiscoveryResult(disco);
injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco);
} else {
- Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco.getVer());
+ Logging.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco.getVer());
}
}
account.inProgressDiscoFetches.remove(key);
@@ -3326,6 +2853,10 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa
void onMoreMessagesLoaded(int count, Conversation conversation);
void informUser(int r);
+
+ void setLoadingInProgress();
+
+ boolean isLoadingInProgress();
}
public interface OnAccountPasswordChanged {