Commit e602df51 authored by Grigory Fedorov's avatar Grigory Fedorov

Merge branch 'feature/account_color' into develop

parents cfacbc7e f510b01c
...@@ -14,12 +14,6 @@ ...@@ -14,12 +14,6 @@
*/ */
package com.xabber.android.data.account; package com.xabber.android.data.account;
import java.security.KeyPair;
import java.util.Date;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;
import com.xabber.android.data.NetworkException; import com.xabber.android.data.NetworkException;
import com.xabber.android.data.SettingsManager; import com.xabber.android.data.SettingsManager;
import com.xabber.android.data.connection.ConnectionItem; import com.xabber.android.data.connection.ConnectionItem;
...@@ -29,6 +23,12 @@ import com.xabber.android.data.connection.ProxyType; ...@@ -29,6 +23,12 @@ import com.xabber.android.data.connection.ProxyType;
import com.xabber.android.data.connection.TLSMode; import com.xabber.android.data.connection.TLSMode;
import com.xabber.androiddev.R; import com.xabber.androiddev.R;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;
import java.security.KeyPair;
import java.util.Date;
/** /**
* Represent account settings and status. * Represent account settings and status.
* *
...@@ -51,7 +51,7 @@ public class AccountItem extends ConnectionItem { ...@@ -51,7 +51,7 @@ public class AccountItem extends ConnectionItem {
*/ */
private final String account; private final String account;
private final int colorIndex; private int colorIndex;
/** /**
* Whether account is enabled. * Whether account is enabled.
...@@ -436,4 +436,7 @@ public class AccountItem extends ConnectionItem { ...@@ -436,4 +436,7 @@ public class AccountItem extends ConnectionItem {
return Math.min(128, Math.max(-128, priority)); return Math.min(128, Math.max(-128, priority));
} }
public void setColorIndex(int colorIndex) {
this.colorIndex = colorIndex;
}
} }
...@@ -23,6 +23,7 @@ import com.xabber.android.data.NetworkException; ...@@ -23,6 +23,7 @@ import com.xabber.android.data.NetworkException;
import com.xabber.android.data.OnLoadListener; import com.xabber.android.data.OnLoadListener;
import com.xabber.android.data.OnWipeListener; import com.xabber.android.data.OnWipeListener;
import com.xabber.android.data.SettingsManager; import com.xabber.android.data.SettingsManager;
import com.xabber.android.data.connection.ConnectionSettings;
import com.xabber.android.data.connection.ConnectionState; import com.xabber.android.data.connection.ConnectionState;
import com.xabber.android.data.connection.ProxyType; import com.xabber.android.data.connection.ProxyType;
import com.xabber.android.data.connection.TLSMode; import com.xabber.android.data.connection.TLSMode;
...@@ -113,40 +114,35 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -113,40 +114,35 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
private AccountManager() { private AccountManager() {
this.application = Application.getInstance(); this.application = Application.getInstance();
accountItems = new HashMap<String, AccountItem>(); accountItems = new HashMap<>();
enabledAccounts = new HashSet<String>(); enabledAccounts = new HashSet<>();
savedStatuses = new ArrayList<SavedStatus>(); savedStatuses = new ArrayList<>();
authorizationErrorProvider = new BaseAccountNotificationProvider<AccountAuthorizationError>( authorizationErrorProvider = new BaseAccountNotificationProvider<>(R.drawable.ic_stat_error);
R.drawable.ic_stat_error); passwordRequestProvider = new BaseAccountNotificationProvider<>(R.drawable.ic_stat_ic_add_circle);
passwordRequestProvider = new BaseAccountNotificationProvider<PasswordRequest>(
R.drawable.ic_stat_ic_add_circle); TypedArray accountAvatars = application.getResources().obtainTypedArray(R.array.account_avatars);
TypedArray accountAvatars = application.getResources()
.obtainTypedArray(R.array.account_avatars);
colors = accountAvatars.length(); colors = accountAvatars.length();
accountAvatars.recycle(); accountAvatars.recycle();
TypedArray types = application.getResources().obtainTypedArray( TypedArray types = application.getResources().obtainTypedArray(R.array.account_types);
R.array.account_types); accountTypes = new ArrayList<>();
accountTypes = new ArrayList<AccountType>();
for (int index = 0; index < types.length(); index++) { for (int index = 0; index < types.length(); index++) {
int id = types.getResourceId(index, 0); int id = types.getResourceId(index, 0);
TypedArray values = application.getResources().obtainTypedArray(id); TypedArray values = application.getResources().obtainTypedArray(id);
AccountProtocol protocol = AccountProtocol.valueOf(values AccountProtocol protocol = AccountProtocol.valueOf(values.getString(0));
.getString(0));
if (Build.VERSION.SDK_INT < 8 && protocol == AccountProtocol.wlm) { if (Build.VERSION.SDK_INT < 8 && protocol == AccountProtocol.wlm) {
values.recycle(); values.recycle();
continue; continue;
} }
ArrayList<String> servers = new ArrayList<String>(); ArrayList<String> servers = new ArrayList<>();
servers.add(values.getString(9)); servers.add(values.getString(9));
for (int i = 10; i < values.length(); i++) for (int i = 10; i < values.length(); i++) {
servers.add(values.getString(i)); servers.add(values.getString(i));
}
accountTypes.add(new AccountType(id, protocol, values.getString(1), accountTypes.add(new AccountType(id, protocol, values.getString(1),
values.getString(2), values.getString(3), values values.getString(2), values.getString(3), values.getDrawable(4),
.getDrawable(4), values.getBoolean(5, false), values.getBoolean(5, false), values.getString(6), values.getInt(7, 5222),
values.getString(6), values.getInt(7, 5222), values values.getBoolean(8, false), servers));
.getBoolean(8, false), servers));
values.recycle(); values.recycle();
} }
types.recycle(); types.recycle();
...@@ -156,15 +152,14 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -156,15 +152,14 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
@Override @Override
public void onLoad() { public void onLoad() {
final Collection<SavedStatus> savedStatuses = new ArrayList<SavedStatus>(); final Collection<SavedStatus> savedStatuses = new ArrayList<>();
final Collection<AccountItem> accountItems = new ArrayList<AccountItem>(); final Collection<AccountItem> accountItems = new ArrayList<>();
Cursor cursor = StatusTable.getInstance().list(); Cursor cursor = StatusTable.getInstance().list();
try { try {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
do { do {
savedStatuses.add(new SavedStatus(StatusTable savedStatuses.add(new SavedStatus(StatusTable.getStatusMode(cursor),
.getStatusMode(cursor), StatusTable StatusTable.getStatusText(cursor)));
.getStatusText(cursor)));
} while (cursor.moveToNext()); } while (cursor.moveToNext());
} }
} finally { } finally {
...@@ -218,28 +213,28 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -218,28 +213,28 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
}); });
} }
private void onLoaded(Collection<SavedStatus> savedStatuses, private void onLoaded(Collection<SavedStatus> savedStatuses, Collection<AccountItem> accountItems) {
Collection<AccountItem> accountItems) {
this.savedStatuses.addAll(savedStatuses); this.savedStatuses.addAll(savedStatuses);
for (AccountItem accountItem : accountItems) for (AccountItem accountItem : accountItems) {
addAccount(accountItem); addAccount(accountItem);
NotificationManager.getInstance().registerNotificationProvider( }
authorizationErrorProvider); NotificationManager.getInstance().registerNotificationProvider(authorizationErrorProvider);
NotificationManager.getInstance().registerNotificationProvider( NotificationManager.getInstance().registerNotificationProvider(passwordRequestProvider);
passwordRequestProvider);
} }
private void addAccount(AccountItem accountItem) { private void addAccount(AccountItem accountItem) {
accountItems.put(accountItem.getAccount(), accountItem); accountItems.put(accountItem.getAccount(), accountItem);
if (accountItem.isEnabled()) if (accountItem.isEnabled()) {
enabledAccounts.add(accountItem.getAccount()); enabledAccounts.add(accountItem.getAccount());
for (OnAccountAddedListener listener : application }
.getManagers(OnAccountAddedListener.class)) for (OnAccountAddedListener listener : application.getManagers(OnAccountAddedListener.class)) {
listener.onAccountAdded(accountItem); listener.onAccountAdded(accountItem);
}
if (accountItem.isEnabled()) { if (accountItem.isEnabled()) {
onAccountEnabled(accountItem); onAccountEnabled(accountItem);
if (accountItem.getRawStatusMode().isOnline()) if (accountItem.getRawStatusMode().isOnline()) {
onAccountOnline(accountItem); onAccountOnline(accountItem);
}
} }
onAccountChanged(accountItem.getAccount()); onAccountChanged(accountItem.getAccount());
} }
...@@ -256,13 +251,16 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -256,13 +251,16 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
*/ */
int getNextColorIndex() { int getNextColorIndex() {
int[] count = new int[colors]; int[] count = new int[colors];
for (AccountItem accountItem : accountItems.values()) for (AccountItem accountItem : accountItems.values()) {
count[accountItem.getColorIndex() % colors] += 1; count[accountItem.getColorIndex() % colors] += 1;
}
int result = 0; int result = 0;
int value = count[0]; int value = count[0];
for (int index = 0; index < count.length; index++) for (int index = 0; index < count.length; index++) {
if (count[index] < value) if (count[index] < value) {
result = index; result = index;
}
}
return result; return result;
} }
...@@ -280,55 +278,10 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -280,55 +278,10 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
* @param accountItem * @param accountItem
*/ */
void requestToWriteAccount(final AccountItem accountItem) { void requestToWriteAccount(final AccountItem accountItem) {
final AccountProtocol protocol = accountItem.getConnectionSettings()
.getProtocol();
final boolean custom = accountItem.getConnectionSettings().isCustom();
final String host = accountItem.getConnectionSettings().getHost();
final int port = accountItem.getConnectionSettings().getPort();
final String serverName = accountItem.getConnectionSettings()
.getServerName();
final String userName = accountItem.getConnectionSettings()
.getUserName();
final String resource = accountItem.getConnectionSettings()
.getResource();
final boolean storePassword = accountItem.isStorePassword();
final String password = accountItem.getConnectionSettings()
.getPassword();
final int colorIndex = accountItem.getColorIndex();
final int priority = accountItem.getPriority();
final StatusMode statusMode = accountItem.getRawStatusMode();
final String statusText = accountItem.getStatusText();
final boolean enabled = accountItem.isEnabled();
final boolean saslEnabled = accountItem.getConnectionSettings()
.isSaslEnabled();
final TLSMode tlsMode = accountItem.getConnectionSettings()
.getTlsMode();
final boolean compression = accountItem.getConnectionSettings()
.useCompression();
final ProxyType proxyType = accountItem.getConnectionSettings()
.getProxyType();
final String proxyHost = accountItem.getConnectionSettings()
.getProxyHost();
final int proxyPort = accountItem.getConnectionSettings()
.getProxyPort();
final String proxyUser = accountItem.getConnectionSettings()
.getProxyUser();
final String proxyPassword = accountItem.getConnectionSettings()
.getProxyPassword();
final boolean syncable = accountItem.isSyncable();
final KeyPair keyPair = accountItem.getKeyPair();
final Date lastSync = accountItem.getLastSync();
final ArchiveMode archiveMode = accountItem.getArchiveMode();
Application.getInstance().runInBackground(new Runnable() { Application.getInstance().runInBackground(new Runnable() {
@Override @Override
public void run() { public void run() {
accountItem.setId(AccountTable.getInstance().write( accountItem.setId(AccountTable.getInstance().write(accountItem.getId(), accountItem));
accountItem.getId(), protocol, custom, host, port,
serverName, userName, resource, storePassword,
password, colorIndex, priority, statusMode, statusText,
enabled, saslEnabled, tlsMode, compression, proxyType,
proxyHost, proxyPort, proxyUser, proxyPassword,
syncable, keyPair, lastSync, archiveMode));
} }
}); });
} }
...@@ -336,26 +289,25 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -336,26 +289,25 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
/** /**
* Creates new account and starts connection. * Creates new account and starts connection.
*/ */
private AccountItem addAccount(AccountProtocol protocol, boolean custom, private AccountItem addAccount(AccountProtocol protocol, boolean custom, String host, int port,
String host, int port, String serverName, String userName, String serverName, String userName, boolean storePassword,
boolean storePassword, String password, String resource, int color, String password, String resource, int color, int priority,
int priority, StatusMode statusMode, String statusText, StatusMode statusMode, String statusText, boolean enabled,
boolean enabled, boolean saslEnabled, TLSMode tlsMode, boolean saslEnabled, TLSMode tlsMode, boolean compression,
boolean compression, ProxyType proxyType, String proxyHost, ProxyType proxyType, String proxyHost, int proxyPort,
int proxyPort, String proxyUser, String proxyPassword, String proxyUser, String proxyPassword, boolean syncable,
boolean syncable, KeyPair keyPair, Date lastSync, KeyPair keyPair, Date lastSync, ArchiveMode archiveMode,
ArchiveMode archiveMode,
boolean registerNewAccount) { boolean registerNewAccount) {
AccountItem accountItem = new AccountItem(protocol, custom, host, port,
serverName, userName, resource, storePassword, password, color, AccountItem accountItem = new AccountItem(protocol, custom, host, port, serverName, userName,
priority, statusMode, statusText, enabled, saslEnabled, resource, storePassword, password, color, priority, statusMode, statusText, enabled,
tlsMode, compression, proxyType, proxyHost, proxyPort, saslEnabled, tlsMode, compression, proxyType, proxyHost, proxyPort, proxyUser,
proxyUser, proxyPassword, syncable, keyPair, lastSync, proxyPassword, syncable, keyPair, lastSync, archiveMode);
archiveMode);
if(registerNewAccount) { if (registerNewAccount) {
// TODO: attempt to register account, if that fails return null; // TODO: attempt to register account, if that fails return null;
accountItem.registerAccount(); // accountItem.registerAccount();
//return(null); // return(null);
} }
requestToWriteAccount(accountItem); requestToWriteAccount(accountItem);
addAccount(accountItem); addAccount(accountItem);
...@@ -375,37 +327,39 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -375,37 +327,39 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
* @return assigned account name. * @return assigned account name.
* @throws NetworkException if user or server part are invalid. * @throws NetworkException if user or server part are invalid.
*/ */
public String addAccount(String user, String password, public String addAccount(String user, String password, AccountType accountType, boolean syncable,
AccountType accountType, boolean syncable, boolean storePassword, boolean storePassword, boolean useOrbot, boolean registerNewAccount)
boolean useOrbot, throws NetworkException {
boolean registerNewAccount) throws NetworkException {
if (accountType.getProtocol().isOAuth()) { if (accountType.getProtocol().isOAuth()) {
int index = 1; int index = 1;
while (true) { while (true) {
user = String.valueOf(index); user = String.valueOf(index);
boolean found = false; boolean found = false;
for (AccountItem accountItem : accountItems.values()) for (AccountItem accountItem : accountItems.values()) {
if (accountItem.getConnectionSettings().getServerName() if (accountItem.getConnectionSettings().getServerName()
.equals(accountType.getFirstServer()) .equals(accountType.getFirstServer())
&& accountItem.getConnectionSettings() && accountItem.getConnectionSettings().getUserName().equals(user)) {
.getUserName().equals(user)) {
found = true; found = true;
break; break;
} }
if (!found) }
if (!found) {
break; break;
}
index++; index++;
} }
} }
if (user == null) if (user == null) {
throw new NetworkException(R.string.EMPTY_USER_NAME); throw new NetworkException(R.string.EMPTY_USER_NAME);
}
if (user.indexOf("@") == -1) { if (!user.contains("@")) {
if ("".equals(accountType.getFirstServer())) if ("".equals(accountType.getFirstServer())) {
throw new NetworkException(R.string.EMPTY_SERVER_NAME); throw new NetworkException(R.string.EMPTY_SERVER_NAME);
else } else {
user += "@" + accountType.getFirstServer(); user += "@" + accountType.getFirstServer();
}
} }
String serverName = StringUtils.parseServer(user); String serverName = StringUtils.parseServer(user);
...@@ -414,23 +368,26 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -414,23 +368,26 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
String host = accountType.getHost(); String host = accountType.getHost();
int port = accountType.getPort(); int port = accountType.getPort();
boolean tlsRequired = accountType.isTLSRequired(); boolean tlsRequired = accountType.isTLSRequired();
if (useOrbot) if (useOrbot) {
tlsRequired = true; tlsRequired = true;
}
if ("".equals(serverName)) { if ("".equals(serverName)) {
throw new NetworkException(R.string.EMPTY_SERVER_NAME); throw new NetworkException(R.string.EMPTY_SERVER_NAME);
} else if (!accountType.isAllowServer() } else if (!accountType.isAllowServer() && !serverName.equals(accountType.getFirstServer())) {
&& !serverName.equals(accountType.getFirstServer()))
throw new NetworkException(R.string.INCORRECT_USER_NAME); throw new NetworkException(R.string.INCORRECT_USER_NAME);
}
if ("".equals(userName)) if ("".equals(userName)) {
throw new NetworkException(R.string.EMPTY_USER_NAME); throw new NetworkException(R.string.EMPTY_USER_NAME);
if ("".equals(resource)) }
if ("".equals(resource)) {
resource = "android" + StringUtils.randomString(8); resource = "android" + StringUtils.randomString(8);
}
if (accountType.getId() == R.array.account_type_xmpp) { if (accountType.getId() == R.array.account_type_xmpp) {
host = serverName; host = serverName;
for (AccountType check : accountTypes) for (AccountType check : accountTypes) {
if (check.getServers().contains(serverName)) { if (check.getServers().contains(serverName)) {
accountType = check; accountType = check;
host = check.getHost(); host = check.getHost();
...@@ -438,30 +395,30 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -438,30 +395,30 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
tlsRequired = check.isTLSRequired(); tlsRequired = check.isTLSRequired();
break; break;
} }
}
} }
AccountItem accountItem; AccountItem accountItem;
for (; ; ) { while(true) {
if (getAccount(userName + '@' + serverName + '/' + resource) == null) if (getAccount(userName + '@' + serverName + '/' + resource) == null) {
break; break;
}
resource = "android" + StringUtils.randomString(8); resource = "android" + StringUtils.randomString(8);
} }
accountItem = addAccount(accountType.getProtocol(), true, host, port, accountItem = addAccount(accountType.getProtocol(), true, host, port, serverName, userName,
serverName, userName, storePassword, password, resource, storePassword, password, resource, getNextColorIndex(), 0, StatusMode.available,
getNextColorIndex(), 0, StatusMode.available, SettingsManager.statusText(), true, true, tlsRequired ? TLSMode.required : TLSMode.enabled,
SettingsManager.statusText(), true, true, false, useOrbot ? ProxyType.orbot : ProxyType.none, "localhost", 8080,
tlsRequired ? TLSMode.required : TLSMode.enabled, false,
useOrbot ? ProxyType.orbot : ProxyType.none, "localhost", 8080,
"", "", syncable, null, null, ArchiveMode.available, registerNewAccount); "", "", syncable, null, null, ArchiveMode.available, registerNewAccount);
if(accountItem == null) { if (accountItem == null) {
throw new NetworkException(R.string.ACCOUNT_REGISTER_FAILED); throw new NetworkException(R.string.ACCOUNT_REGISTER_FAILED);
} }
onAccountChanged(accountItem.getAccount()); onAccountChanged(accountItem.getAccount());
if (accountItems.size() > 1 if (accountItems.size() > 1 && SettingsManager.contactsEnableShowAccounts()) {
&& SettingsManager.contactsEnableShowAccounts())
SettingsManager.enableContactsShowAccount(); SettingsManager.enableContactsShowAccount();
}
return accountItem.getAccount(); return accountItem.getAccount();
} }
...@@ -476,8 +433,9 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -476,8 +433,9 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
accountItem.setEnabled(false); accountItem.setEnabled(false);
accountItem.updateConnection(true); accountItem.updateConnection(true);
if (wasEnabled) { if (wasEnabled) {
if (accountItem.getRawStatusMode().isOnline()) if (accountItem.getRawStatusMode().isOnline()) {
onAccountOffline(accountItem); onAccountOffline(accountItem);
}
onAccountDisabled(accountItem); onAccountDisabled(accountItem);
} }
Application.getInstance().runInBackground(new Runnable() { Application.getInstance().runInBackground(new Runnable() {
...@@ -488,9 +446,9 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -488,9 +446,9 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
}); });
accountItems.remove(account); accountItems.remove(account);
enabledAccounts.remove(account); enabledAccounts.remove(account);
for (OnAccountRemovedListener listener : application for (OnAccountRemovedListener listener : application.getManagers(OnAccountRemovedListener.class)) {
.getManagers(OnAccountRemovedListener.class))
listener.onAccountRemoved(accountItem); listener.onAccountRemoved(accountItem);
}
removeAuthorizationError(account); removeAuthorizationError(account);
} }
...@@ -527,50 +485,45 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -527,50 +485,45 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
* @param syncable * @param syncable
* @param archiveMode * @param archiveMode
*/ */
public void updateAccount(String account, boolean custom, String host, public void updateAccount(String account, boolean custom, String host, int port, String serverName,
int port, String serverName, String userName, String userName, boolean storePassword, String password, String resource,
boolean storePassword, String password, String resource, int priority, boolean enabled, boolean saslEnabled, TLSMode tlsMode,
int priority, boolean enabled, boolean saslEnabled, boolean compression, ProxyType proxyType, String proxyHost, int proxyPort,
TLSMode tlsMode, boolean compression, ProxyType proxyType, String proxyUser, String proxyPassword, boolean syncable,
String proxyHost, int proxyPort, String proxyUser, ArchiveMode archiveMode, int colorIndex) {
String proxyPassword, boolean syncable, ArchiveMode archiveMode) {
AccountItem result; AccountItem result;
AccountItem accountItem = getAccount(account); AccountItem accountItem = getAccount(account);
if (accountItem.getConnectionSettings().getServerName()
.equals(serverName) if (accountItem.getConnectionSettings().getServerName().equals(serverName)
&& accountItem.getConnectionSettings().getUserName() && accountItem.getConnectionSettings().getUserName().equals(userName)
.equals(userName) && accountItem.getConnectionSettings().getResource().equals(resource)) {
&& accountItem.getConnectionSettings().getResource()
.equals(resource)) {
result = accountItem; result = accountItem;
result.setColorIndex(colorIndex);
boolean reconnect = false; boolean reconnect = false;
if (accountItem.getConnectionSettings().isCustom() != custom if (accountItem.getConnectionSettings().isCustom() != custom
|| !accountItem.getConnectionSettings().getHost() || !accountItem.getConnectionSettings().getHost().equals(host)
.equals(host)
|| accountItem.getConnectionSettings().getPort() != port || accountItem.getConnectionSettings().getPort() != port
|| !accountItem.getConnectionSettings().getPassword() || !accountItem.getConnectionSettings().getPassword().equals(password)
.equals(password)
|| accountItem.getConnectionSettings().getTlsMode() != tlsMode || accountItem.getConnectionSettings().getTlsMode() != tlsMode
|| accountItem.getConnectionSettings().isSaslEnabled() != saslEnabled || accountItem.getConnectionSettings().isSaslEnabled() != saslEnabled
|| accountItem.getConnectionSettings().useCompression() != compression || accountItem.getConnectionSettings().useCompression() != compression
|| accountItem.getConnectionSettings().getProxyType() != proxyType || accountItem.getConnectionSettings().getProxyType() != proxyType
|| !accountItem.getConnectionSettings().getProxyHost() || !accountItem.getConnectionSettings().getProxyHost().equals(proxyHost)
.equals(proxyHost)
|| accountItem.getConnectionSettings().getProxyPort() != proxyPort || accountItem.getConnectionSettings().getProxyPort() != proxyPort
|| !accountItem.getConnectionSettings().getProxyUser() || !accountItem.getConnectionSettings().getProxyUser().equals(proxyUser)
.equals(proxyUser) || !accountItem.getConnectionSettings().getProxyPassword().equals(proxyPassword)) {
|| !accountItem.getConnectionSettings().getProxyPassword() result.updateConnectionSettings(custom, host, port, password, saslEnabled, tlsMode,
.equals(proxyPassword)) { compression, proxyType, proxyHost, proxyPort, proxyUser, proxyPassword);
result.updateConnectionSettings(custom, host, port, password,
saslEnabled, tlsMode, compression, proxyType,
proxyHost, proxyPort, proxyUser, proxyPassword);
reconnect = true; reconnect = true;
} }
if (result.isSyncable() != syncable) { if (result.isSyncable() != syncable) {
result.setSyncable(syncable); result.setSyncable(syncable);
for (OnAccountSyncableChangedListener listener : application for (OnAccountSyncableChangedListener listener :
.getManagers(OnAccountSyncableChangedListener.class)) application.getManagers(OnAccountSyncableChangedListener.class)) {
listener.onAccountSyncableChanged(result); listener.onAccountSyncableChanged(result);
}
} }
result.setStorePassword(storePassword); result.setStorePassword(storePassword);
boolean changed = result.isEnabled() != enabled; boolean changed = result.isEnabled() != enabled;
...@@ -585,15 +538,17 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -585,15 +538,17 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
if (result.getArchiveMode() != archiveMode) { if (result.getArchiveMode() != archiveMode) {
reconnect = (result.getArchiveMode() == ArchiveMode.server) != (archiveMode == ArchiveMode.server); reconnect = (result.getArchiveMode() == ArchiveMode.server) != (archiveMode == ArchiveMode.server);
result.setArchiveMode(archiveMode); result.setArchiveMode(archiveMode);
for (OnAccountArchiveModeChangedListener listener : application for (OnAccountArchiveModeChangedListener listener :
.getManagers(OnAccountArchiveModeChangedListener.class)) application.getManagers(OnAccountArchiveModeChangedListener.class)) {
listener.onAccountArchiveModeChanged(result); listener.onAccountArchiveModeChanged(result);
}
} }
if (changed && enabled) { if (changed && enabled) {
enabledAccounts.add(account); enabledAccounts.add(account);
onAccountEnabled(result); onAccountEnabled(result);
if (result.getRawStatusMode().isOnline()) if (result.getRawStatusMode().isOnline()) {
onAccountOnline(result); onAccountOnline(result);
}
} }
if (changed || reconnect) { if (changed || reconnect) {
result.updateConnection(true); result.updateConnection(true);
...@@ -601,26 +556,23 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -601,26 +556,23 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
} }
if (changed && !enabled) { if (changed && !enabled) {
enabledAccounts.remove(account); enabledAccounts.remove(account);
if (result.getRawStatusMode().isOnline()) if (result.getRawStatusMode().isOnline()) {
onAccountOffline(result); onAccountOffline(result);
}
onAccountDisabled(result); onAccountDisabled(result);
} }
requestToWriteAccount(result); requestToWriteAccount(result);
} else { } else {
int colorIndex = accountItem.getColorIndex();
StatusMode statusMode = accountItem.getRawStatusMode(); StatusMode statusMode = accountItem.getRawStatusMode();
String statusText = accountItem.getStatusText(); String statusText = accountItem.getStatusText();
AccountProtocol protocol = accountItem.getConnectionSettings() AccountProtocol protocol = accountItem.getConnectionSettings().getProtocol();
.getProtocol();
KeyPair keyPair = accountItem.getKeyPair(); KeyPair keyPair = accountItem.getKeyPair();
Date lastSync = accountItem.getLastSync(); Date lastSync = accountItem.getLastSync();
removeAccountWithoutCallback(account); removeAccountWithoutCallback(account);
result = addAccount(protocol, custom, host, port, serverName, result = addAccount(protocol, custom, host, port, serverName, userName, storePassword,
userName, storePassword, password, resource, colorIndex, password, resource, colorIndex, priority, statusMode, statusText, enabled,
priority, statusMode, statusText, enabled, saslEnabled, saslEnabled, tlsMode, compression, proxyType, proxyHost, proxyPort, proxyUser,
tlsMode, compression, proxyType, proxyHost, proxyPort, proxyPassword, syncable, keyPair, lastSync, archiveMode, false);
proxyUser, proxyPassword, syncable, keyPair, lastSync,
archiveMode, false);
} }
onAccountChanged(result.getAccount()); onAccountChanged(result.getAccount());
} }
...@@ -639,75 +591,96 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -639,75 +591,96 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
public void setSyncable(String account, boolean syncable) { public void setSyncable(String account, boolean syncable) {
AccountItem accountItem = getAccount(account); AccountItem accountItem = getAccount(account);
updateAccount(account, accountItem.getConnectionSettings().isCustom(), ConnectionSettings connectionSettings = accountItem.getConnectionSettings();
accountItem.getConnectionSettings().getHost(), accountItem updateAccount(
.getConnectionSettings().getPort(), accountItem account,
.getConnectionSettings().getServerName(), accountItem connectionSettings.isCustom(),
.getConnectionSettings().getUserName(), connectionSettings.getHost(),
accountItem.isStorePassword(), accountItem connectionSettings.getPort(),
.getConnectionSettings().getPassword(), accountItem connectionSettings.getServerName(),
.getConnectionSettings().getResource(), connectionSettings.getUserName(),
accountItem.getPriority(), accountItem.isEnabled(), accountItem accountItem.isStorePassword(),
.getConnectionSettings().isSaslEnabled(), accountItem connectionSettings.getPassword(),
.getConnectionSettings().getTlsMode(), accountItem connectionSettings.getResource(),
.getConnectionSettings().useCompression(), accountItem accountItem.getPriority(),
.getConnectionSettings().getProxyType(), accountItem accountItem.isEnabled(),
.getConnectionSettings().getProxyHost(), accountItem connectionSettings.isSaslEnabled(),
.getConnectionSettings().getProxyPort(), accountItem connectionSettings.getTlsMode(),
.getConnectionSettings().getProxyUser(), accountItem connectionSettings.useCompression(),
.getConnectionSettings().getProxyPassword(), syncable, connectionSettings.getProxyType(),
accountItem.getArchiveMode()); connectionSettings.getProxyHost(),
connectionSettings.getProxyPort(),
connectionSettings.getProxyUser(),
connectionSettings.getProxyPassword(),
syncable,
accountItem.getArchiveMode(),
accountItem.getColorIndex()
);
} }
public void setPassword(String account, boolean storePassword, public void setPassword(String account, boolean storePassword, String password) {
String password) {
AccountItem accountItem = getAccount(account); AccountItem accountItem = getAccount(account);
updateAccount(account, accountItem.getConnectionSettings().isCustom(), ConnectionSettings connectionSettings = accountItem.getConnectionSettings();
accountItem.getConnectionSettings().getHost(), accountItem updateAccount(
.getConnectionSettings().getPort(), accountItem account,
.getConnectionSettings().getServerName(), accountItem connectionSettings.isCustom(),
.getConnectionSettings().getUserName(), storePassword, connectionSettings.getHost(),
password, accountItem.getConnectionSettings().getResource(), connectionSettings.getPort(),
accountItem.getPriority(), accountItem.isEnabled(), accountItem connectionSettings.getServerName(),
.getConnectionSettings().isSaslEnabled(), accountItem connectionSettings.getUserName(),
.getConnectionSettings().getTlsMode(), accountItem storePassword,
.getConnectionSettings().useCompression(), accountItem password,
.getConnectionSettings().getProxyType(), accountItem connectionSettings.getResource(),
.getConnectionSettings().getProxyHost(), accountItem accountItem.getPriority(),
.getConnectionSettings().getProxyPort(), accountItem accountItem.isEnabled(),
.getConnectionSettings().getProxyUser(), accountItem connectionSettings.isSaslEnabled(),
.getConnectionSettings().getProxyPassword(), connectionSettings.getTlsMode(),
accountItem.isSyncable(), accountItem.getArchiveMode()); connectionSettings.useCompression(),
connectionSettings.getProxyType(),
connectionSettings.getProxyHost(),
connectionSettings.getProxyPort(),
connectionSettings.getProxyUser(),
connectionSettings.getProxyPassword(),
accountItem.isSyncable(),
accountItem.getArchiveMode(),
accountItem.getColorIndex()
);
} }
public void setArchiveMode(String account, ArchiveMode archiveMode) { public void setArchiveMode(String account, ArchiveMode archiveMode) {
AccountItem accountItem = AccountManager.getInstance().getAccount( AccountItem accountItem = AccountManager.getInstance().getAccount(account);
account); ConnectionSettings connectionSettings = accountItem.getConnectionSettings();
AccountManager.getInstance().updateAccount(account, AccountManager.getInstance().updateAccount(
accountItem.getConnectionSettings().isCustom(), account,
accountItem.getConnectionSettings().getHost(), connectionSettings.isCustom(),
accountItem.getConnectionSettings().getPort(), connectionSettings.getHost(),
accountItem.getConnectionSettings().getServerName(), connectionSettings.getPort(),
accountItem.getConnectionSettings().getUserName(), connectionSettings.getServerName(),
connectionSettings.getUserName(),
accountItem.isStorePassword(), accountItem.isStorePassword(),
accountItem.getConnectionSettings().getPassword(), connectionSettings.getPassword(),
accountItem.getConnectionSettings().getResource(), connectionSettings.getResource(),
accountItem.getPriority(), accountItem.isEnabled(), accountItem.getPriority(),
accountItem.getConnectionSettings().isSaslEnabled(), accountItem.isEnabled(),
accountItem.getConnectionSettings().getTlsMode(), connectionSettings.isSaslEnabled(),
accountItem.getConnectionSettings().useCompression(), connectionSettings.getTlsMode(),
accountItem.getConnectionSettings().getProxyType(), connectionSettings.useCompression(),
accountItem.getConnectionSettings().getProxyHost(), connectionSettings.getProxyType(),
accountItem.getConnectionSettings().getProxyPort(), connectionSettings.getProxyHost(),
accountItem.getConnectionSettings().getProxyUser(), connectionSettings.getProxyPort(),
accountItem.getConnectionSettings().getProxyPassword(), connectionSettings.getProxyUser(),
accountItem.isSyncable(), archiveMode); connectionSettings.getProxyPassword(),
accountItem.isSyncable(),
archiveMode,
accountItem.getColorIndex()
);
} }
public ArchiveMode getArchiveMode(String account) { public ArchiveMode getArchiveMode(String account) {
AccountItem accountItem = getAccount(account); AccountItem accountItem = getAccount(account);
if (accountItem == null) if (accountItem == null) {
return ArchiveMode.available; return ArchiveMode.available;
}
return accountItem.getArchiveMode(); return accountItem.getArchiveMode();
} }
...@@ -735,34 +708,41 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -735,34 +708,41 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
for (AccountItem accountItem : accountItems.values()) { for (AccountItem accountItem : accountItems.values()) {
ConnectionState state = accountItem.getState(); ConnectionState state = accountItem.getState();
if (state == ConnectionState.connected) if (state == ConnectionState.connected) {
online = true; online = true;
if (RosterManager.getInstance().isRosterReceived( }
accountItem.getAccount())) if (RosterManager.getInstance().isRosterReceived(accountItem.getAccount())) {
roster = true; roster = true;
if (state == ConnectionState.connecting }
|| state == ConnectionState.authentication) if (state == ConnectionState.connecting || state == ConnectionState.authentication) {
connecting = true; connecting = true;
if (state == ConnectionState.waiting) }
if (state == ConnectionState.waiting) {
waiting = true; waiting = true;
if (accountItem.isEnabled()) }
if (accountItem.isEnabled()) {
offline = true; offline = true;
}
disabled = true; disabled = true;
} }
if (online)
if (online) {
return CommonState.online; return CommonState.online;
else if (roster) } else if (roster) {
return CommonState.roster; return CommonState.roster;
else if (connecting) } else if (connecting) {
return CommonState.connecting; return CommonState.connecting;
if (waiting) }
if (waiting) {
return CommonState.waiting; return CommonState.waiting;
else if (offline) } else if (offline) {
return CommonState.offline; return CommonState.offline;
else if (disabled) } else if (disabled) {
return CommonState.disabled; return CommonState.disabled;
else } else {
return CommonState.empty; return CommonState.empty;
}
} }
/** /**
...@@ -772,12 +752,16 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -772,12 +752,16 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
public int getColorLevel(String account) { public int getColorLevel(String account) {
AccountItem accountItem = getAccount(account); AccountItem accountItem = getAccount(account);
int colorIndex; int colorIndex;
if (accountItem == null)
if (accountItem == null) {
return 0; return 0;
else } else {
colorIndex = accountItem.getColorIndex() % colors; colorIndex = accountItem.getColorIndex() % colors;
if (colorIndex < 0) }
if (colorIndex < 0) {
colorIndex += colors; colorIndex += colors;
}
return colorIndex; return colorIndex;
} }
...@@ -790,21 +774,23 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -790,21 +774,23 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
private boolean hasSameBareAddress(String account) { private boolean hasSameBareAddress(String account) {
String bareAddress = Jid.getBareAddress(account); String bareAddress = Jid.getBareAddress(account);
for (AccountItem check : accountItems.values()) for (AccountItem check : accountItems.values()) {
if (!check.getAccount().equals(account) if (!check.getAccount().equals(account)
&& Jid.getBareAddress(check.getAccount()).equals( && Jid.getBareAddress(check.getAccount()).equals(bareAddress)) {
bareAddress))
return true; return true;
}
}
return false; return false;
} }
private boolean hasSameProtocol(String account) { private boolean hasSameProtocol(String account) {
AccountProtocol protocol = getAccount(account).getConnectionSettings() AccountProtocol protocol = getAccount(account).getConnectionSettings().getProtocol();
.getProtocol(); for (AccountItem check : accountItems.values()) {
for (AccountItem check : accountItems.values())
if (!check.getAccount().equals(account) if (!check.getAccount().equals(account)
&& check.getConnectionSettings().getProtocol() == protocol) && check.getConnectionSettings().getProtocol() == protocol) {
return true; return true;
}
}
return false; return false;
} }
...@@ -814,32 +800,32 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -814,32 +800,32 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
*/ */
public String getVerboseName(String account) { public String getVerboseName(String account) {
AccountItem accountItem = getAccount(account); AccountItem accountItem = getAccount(account);
if (accountItem == null) if (accountItem == null) {
return account; return account;
}
if (accountItem.getConnectionSettings().getProtocol().isOAuth()) { if (accountItem.getConnectionSettings().getProtocol().isOAuth()) {
String jid = OAuthManager.getInstance().getAssignedJid(account); String jid = OAuthManager.getInstance().getAssignedJid(account);
AccountProtocol accountProtocol = accountItem AccountProtocol accountProtocol = accountItem.getConnectionSettings().getProtocol();
.getConnectionSettings().getProtocol();
String name; String name;
if (jid == null) { if (jid == null) {
if (hasSameProtocol(account)) if (hasSameProtocol(account)) {
name = accountItem.getConnectionSettings().getUserName(); name = accountItem.getConnectionSettings().getUserName();
else } else {
return application.getString(accountProtocol return application.getString(accountProtocol.getNameResource());
.getNameResource()); }
} else { } else {
name = Jid.getBareAddress(jid); name = Jid.getBareAddress(jid);
if (!hasSameBareAddress(jid)) if (!hasSameBareAddress(jid)) {
return name; return name;
}
} }
return application.getString(accountProtocol.getShortResource()) return application.getString(accountProtocol.getShortResource()) + " - " + name;
+ " - " + name;
} else { } else {
if (hasSameBareAddress(account)) if (hasSameBareAddress(account)) {
return account; return account;
else } else {
return Jid.getBareAddress(account); return Jid.getBareAddress(account);
}
} }
} }
...@@ -850,12 +836,12 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -850,12 +836,12 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
*/ */
public String getNickName(String account) { public String getNickName(String account) {
String jid = OAuthManager.getInstance().getAssignedJid(account); String jid = OAuthManager.getInstance().getAssignedJid(account);
String result = VCardManager.getInstance().getName( String result = VCardManager.getInstance().getName(Jid.getBareAddress(jid));
Jid.getBareAddress(jid)); if ("".equals(result)) {
if ("".equals(result))
return getVerboseName(account); return getVerboseName(account);
else } else {
return result; return result;
}
} }
/** /**
...@@ -865,8 +851,7 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -865,8 +851,7 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
* @param statusMode * @param statusMode
* @param statusText * @param statusText
*/ */
public void setStatus(String account, StatusMode statusMode, public void setStatus(String account, StatusMode statusMode, String statusText) {
String statusText) {
addSavedStatus(statusMode, statusText); addSavedStatus(statusMode, statusText);
AccountItem accountItem = getAccount(account); AccountItem accountItem = getAccount(account);
setStatus(accountItem, statusMode, statusText); setStatus(accountItem, statusMode, statusText);
...@@ -875,24 +860,25 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -875,24 +860,25 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
} catch (NetworkException e) { } catch (NetworkException e) {
} }
boolean found = false; boolean found = false;
for (AccountItem check : accountItems.values()) for (AccountItem check : accountItems.values()) {
if (check.isEnabled() if (check.isEnabled() && SettingsManager.statusMode() == check.getRawStatusMode()) {
&& SettingsManager.statusMode() == check.getRawStatusMode()) {
found = true; found = true;
break; break;
} }
if (!found) }
if (!found) {
SettingsManager.setStatusMode(statusMode); SettingsManager.setStatusMode(statusMode);
}
found = false; found = false;
for (AccountItem check : accountItems.values()) for (AccountItem check : accountItems.values()) {
if (check.isEnabled() if (check.isEnabled() && SettingsManager.statusText().equals(check.getStatusText())) {
&& SettingsManager.statusText().equals(
check.getStatusText())) {
found = true; found = true;
break; break;
} }
if (!found) }
if (!found) {
SettingsManager.setStatusText(statusText); SettingsManager.setStatusText(statusText);
}
onAccountChanged(account); onAccountChanged(account);
} }
...@@ -910,8 +896,9 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -910,8 +896,9 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
* If we are already away or xa, do nothing. * If we are already away or xa, do nothing.
*/ */
public void goAway() { public void goAway() {
if (away || xa) if (away || xa) {
return; return;
}
away = true; away = true;
resendPresence(); resendPresence();
} }
...@@ -922,8 +909,9 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -922,8 +909,9 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
* If we are already xa, do nothing. * If we are already xa, do nothing.
*/ */
public void goXa() { public void goXa() {
if (xa) if (xa) {
return; return;
}
xa = true; xa = true;
resendPresence(); resendPresence();
} }
...@@ -934,8 +922,9 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -934,8 +922,9 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
* If we are already waked up, do nothing. * If we are already waked up, do nothing.
*/ */
public void wakeUp() { public void wakeUp() {
if (!away && !xa) if (!away && !xa) {
return; return;
}
away = false; away = false;
xa = false; xa = false;
resendPresence(); resendPresence();
...@@ -945,12 +934,12 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -945,12 +934,12 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
* Sends new presence information for all accounts. * Sends new presence information for all accounts.
*/ */
public void resendPresence() { public void resendPresence() {
for (AccountItem accountItem : accountItems.values()) for (AccountItem accountItem : accountItems.values()) {
try { try {
PresenceManager.getInstance().resendPresence( PresenceManager.getInstance().resendPresence(accountItem.getAccount());
accountItem.getAccount());
} catch (NetworkException e) { } catch (NetworkException e) {
} }
}
} }
/** /**
...@@ -960,17 +949,17 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -960,17 +949,17 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
* @param statusMode * @param statusMode
* @param statusText * @param statusText
*/ */
private void setStatus(AccountItem accountItem, StatusMode statusMode, private void setStatus(AccountItem accountItem, StatusMode statusMode, String statusText) {
String statusText) {
boolean changed = accountItem.isEnabled() boolean changed = accountItem.isEnabled()
&& accountItem.getRawStatusMode().isOnline() != statusMode && accountItem.getRawStatusMode().isOnline() != statusMode.isOnline();
.isOnline();
accountItem.setStatus(statusMode, statusText); accountItem.setStatus(statusMode, statusText);
if (changed && statusMode.isOnline()) if (changed && statusMode.isOnline()) {
onAccountOnline(accountItem); onAccountOnline(accountItem);
}
accountItem.updateConnection(true); accountItem.updateConnection(true);
if (changed && !statusMode.isOnline()) if (changed && !statusMode.isOnline()) {
onAccountOffline(accountItem); onAccountOffline(accountItem);
}
requestToWriteAccount(accountItem); requestToWriteAccount(accountItem);
} }
...@@ -982,18 +971,19 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -982,18 +971,19 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
*/ */
public void setStatus(StatusMode statusMode, String statusText) { public void setStatus(StatusMode statusMode, String statusText) {
SettingsManager.setStatusMode(statusMode); SettingsManager.setStatusMode(statusMode);
if (statusText != null) { if (statusText != null) {
addSavedStatus(statusMode, statusText); addSavedStatus(statusMode, statusText);
SettingsManager.setStatusText(statusText); SettingsManager.setStatusText(statusText);
} }
for (AccountItem accountItem : accountItems.values()) { for (AccountItem accountItem : accountItems.values()) {
setStatus(accountItem, statusMode, setStatus(accountItem, statusMode,
statusText == null ? accountItem.getStatusText() statusText == null ? accountItem.getStatusText() : statusText);
: statusText);
} }
resendPresence(); resendPresence();
onAccountsChanged(new ArrayList<String>(AccountManager.getInstance() onAccountsChanged(new ArrayList<>(AccountManager.getInstance().getAllAccounts()));
.getAllAccounts()));
} }
/** /**
...@@ -1002,11 +992,11 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -1002,11 +992,11 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
* @param statusMode * @param statusMode
* @param statusText * @param statusText
*/ */
private void addSavedStatus(final StatusMode statusMode, private void addSavedStatus(final StatusMode statusMode, final String statusText) {
final String statusText) {
SavedStatus savedStatus = new SavedStatus(statusMode, statusText); SavedStatus savedStatus = new SavedStatus(statusMode, statusText);
if (savedStatuses.contains(savedStatus)) if (savedStatuses.contains(savedStatus)) {
return; return;
}
savedStatuses.add(savedStatus); savedStatuses.add(savedStatus);
Application.getInstance().runInBackground(new Runnable() { Application.getInstance().runInBackground(new Runnable() {
@Override @Override
...@@ -1023,8 +1013,9 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -1023,8 +1013,9 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
* @param statusText * @param statusText
*/ */
public void removeSavedStatus(final SavedStatus savedStatus) { public void removeSavedStatus(final SavedStatus savedStatus) {
if (!savedStatuses.remove(savedStatus)) if (!savedStatuses.remove(savedStatus)) {
return; return;
}
Application.getInstance().runInBackground(new Runnable() { Application.getInstance().runInBackground(new Runnable() {
@Override @Override
public void run() { public void run() {
...@@ -1063,11 +1054,13 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -1063,11 +1054,13 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
* </ul> * </ul>
*/ */
public String getSelectedAccount() { public String getSelectedAccount() {
if (SettingsManager.contactsShowAccounts()) if (SettingsManager.contactsShowAccounts()) {
return null; return null;
}
String selected = SettingsManager.contactsSelectedAccount(); String selected = SettingsManager.contactsSelectedAccount();
if (enabledAccounts.contains(selected)) if (enabledAccounts.contains(selected)) {
return selected; return selected;
}
return null; return null;
} }
...@@ -1076,8 +1069,7 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -1076,8 +1069,7 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
} }
public void addAuthenticationError(String account) { public void addAuthenticationError(String account) {
authorizationErrorProvider.add(new AccountAuthorizationError(account), authorizationErrorProvider.add(new AccountAuthorizationError(account), true);
true);
} }
public void removePasswordRequest(String account) { public void removePasswordRequest(String account) {
...@@ -1089,7 +1081,7 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -1089,7 +1081,7 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
} }
public void onAccountChanged(String account) { public void onAccountChanged(String account) {
Collection<String> accounts = new ArrayList<String>(1); Collection<String> accounts = new ArrayList<>(1);
accounts.add(account); accounts.add(account);
onAccountsChanged(accounts); onAccountsChanged(accounts);
} }
...@@ -1098,37 +1090,37 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -1098,37 +1090,37 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
Application.getInstance().runOnUiThread(new Runnable() { Application.getInstance().runOnUiThread(new Runnable() {
@Override @Override
public void run() { public void run() {
for (OnAccountChangedListener accountListener : Application for (OnAccountChangedListener accountListener
.getInstance().getUIListeners( : Application.getInstance().getUIListeners(OnAccountChangedListener.class)) {
OnAccountChangedListener.class))
accountListener.onAccountsChanged(accounts); accountListener.onAccountsChanged(accounts);
}
} }
}); });
} }
public void onAccountEnabled(AccountItem accountItem) { public void onAccountEnabled(AccountItem accountItem) {
for (OnAccountEnabledListener listener : application for (OnAccountEnabledListener listener : application.getManagers(OnAccountEnabledListener.class)) {
.getManagers(OnAccountEnabledListener.class))
listener.onAccountEnabled(accountItem); listener.onAccountEnabled(accountItem);
}
} }
public void onAccountOnline(AccountItem accountItem) { public void onAccountOnline(AccountItem accountItem) {
for (OnAccountOnlineListener listener : application for (OnAccountOnlineListener listener : application.getManagers(OnAccountOnlineListener.class)) {
.getManagers(OnAccountOnlineListener.class))
listener.onAccountOnline(accountItem); listener.onAccountOnline(accountItem);
}
} }
public void onAccountOffline(AccountItem accountItem) { public void onAccountOffline(AccountItem accountItem) {
accountItem.clearPassword(); accountItem.clearPassword();
for (OnAccountOfflineListener listener : application for (OnAccountOfflineListener listener : application.getManagers(OnAccountOfflineListener.class)) {
.getManagers(OnAccountOfflineListener.class))
listener.onAccountOffline(accountItem); listener.onAccountOffline(accountItem);
}
} }
public void onAccountDisabled(AccountItem accountItem) { public void onAccountDisabled(AccountItem accountItem) {
for (OnAccountDisabledListener listener : application for (OnAccountDisabledListener listener : application.getManagers(OnAccountDisabledListener.class)) {
.getManagers(OnAccountDisabledListener.class))
listener.onAccountDisabled(accountItem); listener.onAccountDisabled(accountItem);
}
} }
@Override @Override
...@@ -1136,4 +1128,4 @@ public class AccountManager implements OnLoadListener, OnWipeListener { ...@@ -1136,4 +1128,4 @@ public class AccountManager implements OnLoadListener, OnWipeListener {
AccountTable.getInstance().wipe(); AccountTable.getInstance().wipe();
} }
} }
\ No newline at end of file
...@@ -14,16 +14,6 @@ ...@@ -14,16 +14,6 @@
*/ */
package com.xabber.android.data.account; package com.xabber.android.data.account;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;
import android.content.ContentValues; import android.content.ContentValues;
import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.Editor;
import android.database.Cursor; import android.database.Cursor;
...@@ -34,10 +24,21 @@ import android.provider.BaseColumns; ...@@ -34,10 +24,21 @@ import android.provider.BaseColumns;
import com.xabber.android.data.AbstractTable; import com.xabber.android.data.AbstractTable;
import com.xabber.android.data.Application; import com.xabber.android.data.Application;
import com.xabber.android.data.DatabaseManager; import com.xabber.android.data.DatabaseManager;
import com.xabber.android.data.connection.ConnectionSettings;
import com.xabber.android.data.connection.ProxyType; import com.xabber.android.data.connection.ProxyType;
import com.xabber.android.data.connection.TLSMode; import com.xabber.android.data.connection.TLSMode;
import com.xabber.androiddev.R; import com.xabber.androiddev.R;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;
/** /**
* Storage with account settings. * Storage with account settings.
* *
...@@ -181,19 +182,16 @@ class AccountTable extends AbstractTable { ...@@ -181,19 +182,16 @@ class AccountTable extends AbstractTable {
DatabaseManager.execSQL(db, sql); DatabaseManager.execSQL(db, sql);
break; break;
case 34: case 34:
long count = db.compileStatement("SELECT COUNT(*) FROM accounts;") long count = db.compileStatement("SELECT COUNT(*) FROM accounts;").simpleQueryForLong();
.simpleQueryForLong();
Editor editor = PreferenceManager.getDefaultSharedPreferences( Editor editor = PreferenceManager.getDefaultSharedPreferences(
Application.getInstance().getBaseContext()).edit(); Application.getInstance().getBaseContext()).edit();
if (count < 2) if (count < 2) {
editor.putBoolean( editor.putBoolean(Application.getInstance().getString(
Application.getInstance().getString( R.string.contacts_show_accounts_key), false);
R.string.contacts_show_accounts_key), false); } else {
else editor.putBoolean(Application.getInstance().getString(
editor.putBoolean( R.string.contacts_enable_show_accounts_key), false);
Application.getInstance().getString( }
R.string.contacts_enable_show_accounts_key),
false);
editor.commit(); editor.commit();
break; break;
case 36: case 36:
...@@ -266,12 +264,17 @@ class AccountTable extends AbstractTable { ...@@ -266,12 +264,17 @@ class AccountTable extends AbstractTable {
String value = PreferenceManager.getDefaultSharedPreferences( String value = PreferenceManager.getDefaultSharedPreferences(
Application.getInstance().getBaseContext()).getString( Application.getInstance().getBaseContext()).getString(
"chats_history", "all"); "chats_history", "all");
if ("all".equals(value)) switch (value) {
archiveMode = ArchiveMode.available; case "all":
else if ("unread".equals(value)) archiveMode = ArchiveMode.available;
archiveMode = ArchiveMode.unreadOnly; break;
else case "unread":
archiveMode = ArchiveMode.dontStore; archiveMode = ArchiveMode.unreadOnly;
break;
default:
archiveMode = ArchiveMode.dontStore;
break;
}
sql = "UPDATE accounts SET archive_mode = " + archiveMode.ordinal() sql = "UPDATE accounts SET archive_mode = " + archiveMode.ordinal()
+ ";"; + ";";
DatabaseManager.execSQL(db, sql); DatabaseManager.execSQL(db, sql);
...@@ -299,71 +302,65 @@ class AccountTable extends AbstractTable { ...@@ -299,71 +302,65 @@ class AccountTable extends AbstractTable {
} }
} }
/** public long write(Long id, AccountItem accountItem) {
* Adds or updates account. ConnectionSettings connectionSettings = accountItem.getConnectionSettings();
*
* @return Assigned id.
*/
long write(Long id, AccountProtocol protocol, boolean custom, String host,
int port, String serverName, String userName, String resource,
boolean storePassword, String password, int colorIndex,
int priority, StatusMode statusMode, String statusText,
boolean enabled, boolean saslEnabled, TLSMode tlsMode,
boolean compression, ProxyType proxyType, String proxyHost,
int proxyPort, String proxyUser, String proxyPassword,
boolean syncable, KeyPair keyPair, Date lastSync,
ArchiveMode archiveMode) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(Fields.PROTOCOL, protocol.name()); values.put(Fields.PROTOCOL, connectionSettings.getProtocol().name());
values.put(Fields.CUSTOM, custom ? 1 : 0); values.put(Fields.CUSTOM, connectionSettings.isCustom() ? 1 : 0);
values.put(Fields.HOST, host); values.put(Fields.HOST, connectionSettings.getHost());
values.put(Fields.PORT, port); values.put(Fields.PORT, connectionSettings.getPort());
values.put(Fields.SERVER_NAME, serverName); values.put(Fields.SERVER_NAME, connectionSettings.getServerName());
values.put(Fields.USER_NAME, userName); values.put(Fields.USER_NAME, connectionSettings.getUserName());
if (!storePassword)
String password = connectionSettings.getPassword();
if (!accountItem.isStorePassword()) {
password = AccountItem.UNDEFINED_PASSWORD; password = AccountItem.UNDEFINED_PASSWORD;
}
values.put(Fields.PASSWORD, password); values.put(Fields.PASSWORD, password);
values.put(Fields.RESOURCE, resource);
values.put(Fields.COLOR_INDEX, colorIndex); values.put(Fields.RESOURCE, connectionSettings.getResource());
values.put(Fields.PRIORITY, priority); values.put(Fields.COLOR_INDEX, accountItem.getColorIndex());
values.put(Fields.STATUS_MODE, statusMode.ordinal()); values.put(Fields.PRIORITY, accountItem.getPriority());
values.put(Fields.STATUS_TEXT, statusText); values.put(Fields.STATUS_MODE, accountItem.getRawStatusMode().ordinal());
values.put(Fields.ENABLED, enabled ? 1 : 0); values.put(Fields.STATUS_TEXT, accountItem.getStatusText());
values.put(Fields.SASL_ENABLED, saslEnabled ? 1 : 0); values.put(Fields.ENABLED, accountItem.isEnabled() ? 1 : 0);
values.put(Fields.TLS_MODE, tlsMode.ordinal()); values.put(Fields.SASL_ENABLED, connectionSettings.isSaslEnabled() ? 1 : 0);
values.put(Fields.COMPRESSION, compression ? 1 : 0); values.put(Fields.TLS_MODE, connectionSettings.getTlsMode().ordinal());
values.put(Fields.PROXY_TYPE, proxyType.ordinal()); values.put(Fields.COMPRESSION, connectionSettings.useCompression() ? 1 : 0);
values.put(Fields.PROXY_HOST, proxyHost); values.put(Fields.PROXY_TYPE, connectionSettings.getProxyType().ordinal());
values.put(Fields.PROXY_PORT, proxyPort); values.put(Fields.PROXY_HOST, connectionSettings.getProxyHost());
values.put(Fields.PROXY_USER, proxyUser); values.put(Fields.PROXY_PORT, connectionSettings.getProxyPort());
values.put(Fields.PROXY_PASSWORD, proxyPassword); values.put(Fields.PROXY_USER, connectionSettings.getProxyUser());
values.put(Fields.SYNCABLE, syncable ? 1 : 0); values.put(Fields.PROXY_PASSWORD, connectionSettings.getProxyPassword());
values.put(Fields.STORE_PASSWORD, storePassword ? 1 : 0); values.put(Fields.SYNCABLE, accountItem.isSyncable() ? 1 : 0);
values.put(Fields.STORE_PASSWORD, accountItem.isStorePassword() ? 1 : 0);
final KeyPair keyPair = accountItem.getKeyPair();
if (keyPair == null) { if (keyPair == null) {
values.putNull(Fields.PUBLIC_KEY); values.putNull(Fields.PUBLIC_KEY);
values.putNull(Fields.PRIVATE_KEY); values.putNull(Fields.PRIVATE_KEY);
} else { } else {
PublicKey publicKey = keyPair.getPublic(); PublicKey publicKey = keyPair.getPublic();
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec( X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
publicKey.getEncoded());
PrivateKey privateKey = keyPair.getPrivate(); PrivateKey privateKey = keyPair.getPrivate();
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec( PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
privateKey.getEncoded());
byte[] publicKeyBytes = x509EncodedKeySpec.getEncoded(); byte[] publicKeyBytes = x509EncodedKeySpec.getEncoded();
byte[] privateKeyBytes = pkcs8EncodedKeySpec.getEncoded(); byte[] privateKeyBytes = pkcs8EncodedKeySpec.getEncoded();
values.put(Fields.PUBLIC_KEY, publicKeyBytes); values.put(Fields.PUBLIC_KEY, publicKeyBytes);
values.put(Fields.PRIVATE_KEY, privateKeyBytes); values.put(Fields.PRIVATE_KEY, privateKeyBytes);
} }
if (lastSync == null) if (accountItem.getLastSync() == null) {
values.putNull(Fields.LAST_SYNC); values.putNull(Fields.LAST_SYNC);
else } else {
values.put(Fields.LAST_SYNC, lastSync.getTime()); values.put(Fields.LAST_SYNC, accountItem.getLastSync().getTime());
values.put(Fields.ARCHIVE_MODE, archiveMode.ordinal()); }
values.put(Fields.ARCHIVE_MODE, accountItem.getArchiveMode().ordinal());
SQLiteDatabase db = databaseManager.getWritableDatabase(); SQLiteDatabase db = databaseManager.getWritableDatabase();
if (id == null) if (id == null) {
return db.insert(NAME, Fields.USER_NAME, values); return db.insert(NAME, Fields.USER_NAME, values);
db.update(NAME, values, Fields._ID + " = ?", }
new String[]{String.valueOf(id)}); db.update(NAME, values, Fields._ID + " = ?", new String[]{String.valueOf(id)});
return id; return id;
} }
...@@ -375,8 +372,7 @@ class AccountTable extends AbstractTable { ...@@ -375,8 +372,7 @@ class AccountTable extends AbstractTable {
*/ */
void remove(String account, long id) { void remove(String account, long id) {
SQLiteDatabase db = databaseManager.getWritableDatabase(); SQLiteDatabase db = databaseManager.getWritableDatabase();
db.delete(NAME, Fields._ID + " = ?", db.delete(NAME, Fields._ID + " = ?", new String[]{ String.valueOf(id) });
new String[]{String.valueOf(id)});
databaseManager.removeAccount(account); databaseManager.removeAccount(account);
} }
...@@ -404,8 +400,7 @@ class AccountTable extends AbstractTable { ...@@ -404,8 +400,7 @@ class AccountTable extends AbstractTable {
} }
static AccountProtocol getProtocol(Cursor cursor) { static AccountProtocol getProtocol(Cursor cursor) {
return AccountProtocol.valueOf(cursor.getString(cursor return AccountProtocol.valueOf(cursor.getString(cursor.getColumnIndex(Fields.PROTOCOL)));
.getColumnIndex(Fields.PROTOCOL)));
} }
static String getHost(Cursor cursor) { static String getHost(Cursor cursor) {
...@@ -429,8 +424,9 @@ class AccountTable extends AbstractTable { ...@@ -429,8 +424,9 @@ class AccountTable extends AbstractTable {
} }
static String getPassword(Cursor cursor) { static String getPassword(Cursor cursor) {
if (!isStorePassword(cursor)) if (!isStorePassword(cursor)) {
return AccountItem.UNDEFINED_PASSWORD; return AccountItem.UNDEFINED_PASSWORD;
}
return cursor.getString(cursor.getColumnIndex(Fields.PASSWORD)); return cursor.getString(cursor.getColumnIndex(Fields.PASSWORD));
} }
...@@ -447,8 +443,7 @@ class AccountTable extends AbstractTable { ...@@ -447,8 +443,7 @@ class AccountTable extends AbstractTable {
} }
static StatusMode getStatusMode(Cursor cursor) { static StatusMode getStatusMode(Cursor cursor) {
int statusModeIndex = cursor.getInt(cursor int statusModeIndex = cursor.getInt(cursor.getColumnIndex(Fields.STATUS_MODE));
.getColumnIndex(Fields.STATUS_MODE));
return StatusMode.values()[statusModeIndex]; return StatusMode.values()[statusModeIndex];
} }
...@@ -465,8 +460,7 @@ class AccountTable extends AbstractTable { ...@@ -465,8 +460,7 @@ class AccountTable extends AbstractTable {
} }
public static TLSMode getTLSMode(Cursor cursor) { public static TLSMode getTLSMode(Cursor cursor) {
int tlsModeIndex = cursor int tlsModeIndex = cursor.getInt(cursor.getColumnIndex(Fields.TLS_MODE));
.getInt(cursor.getColumnIndex(Fields.TLS_MODE));
return TLSMode.values()[tlsModeIndex]; return TLSMode.values()[tlsModeIndex];
} }
...@@ -483,11 +477,11 @@ class AccountTable extends AbstractTable { ...@@ -483,11 +477,11 @@ class AccountTable extends AbstractTable {
} }
static Date getLastSync(Cursor cursor) { static Date getLastSync(Cursor cursor) {
if (cursor.isNull(cursor.getColumnIndex(Fields.LAST_SYNC))) if (cursor.isNull(cursor.getColumnIndex(Fields.LAST_SYNC))) {
return null; return null;
else } else {
return new Date(cursor.getLong(cursor return new Date(cursor.getLong(cursor.getColumnIndex(Fields.LAST_SYNC)));
.getColumnIndex(Fields.LAST_SYNC))); }
} }
static ArchiveMode getArchiveMode(Cursor cursor) { static ArchiveMode getArchiveMode(Cursor cursor) {
...@@ -517,16 +511,13 @@ class AccountTable extends AbstractTable { ...@@ -517,16 +511,13 @@ class AccountTable extends AbstractTable {
} }
static KeyPair getKeyPair(Cursor cursor) { static KeyPair getKeyPair(Cursor cursor) {
byte[] publicKeyBytes = cursor.getBlob(cursor byte[] publicKeyBytes = cursor.getBlob(cursor.getColumnIndex(Fields.PUBLIC_KEY));
.getColumnIndex(Fields.PUBLIC_KEY)); byte[] privateKeyBytes = cursor.getBlob(cursor.getColumnIndex(Fields.PRIVATE_KEY));
byte[] privateKeyBytes = cursor.getBlob(cursor if (privateKeyBytes == null || publicKeyBytes == null) {
.getColumnIndex(Fields.PRIVATE_KEY));
if (privateKeyBytes == null || publicKeyBytes == null)
return null; return null;
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec( }
publicKeyBytes); X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec( PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
privateKeyBytes);
PublicKey publicKey; PublicKey publicKey;
PrivateKey privateKey; PrivateKey privateKey;
KeyFactory keyFactory; KeyFactory keyFactory;
...@@ -534,9 +525,7 @@ class AccountTable extends AbstractTable { ...@@ -534,9 +525,7 @@ class AccountTable extends AbstractTable {
keyFactory = KeyFactory.getInstance("DSA"); keyFactory = KeyFactory.getInstance("DSA");
publicKey = keyFactory.generatePublic(publicKeySpec); publicKey = keyFactory.generatePublic(publicKeySpec);
privateKey = keyFactory.generatePrivate(privateKeySpec); privateKey = keyFactory.generatePrivate(privateKeySpec);
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new RuntimeException(e);
} catch (InvalidKeySpecException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
return new KeyPair(publicKey, privateKey); return new KeyPair(publicKey, privateKey);
......
...@@ -67,7 +67,6 @@ public class AccountEditor extends ManagedActivity implements ...@@ -67,7 +67,6 @@ public class AccountEditor extends ManagedActivity implements
getFragmentManager().beginTransaction() getFragmentManager().beginTransaction()
.add(R.id.preferences_activity_container, new AccountEditorFragment()).commit(); .add(R.id.preferences_activity_container, new AccountEditorFragment()).commit();
} else { } else {
token = savedInstanceState.getString(SAVED_TOKEN); token = savedInstanceState.getString(SAVED_TOKEN);
} }
...@@ -92,11 +91,11 @@ public class AccountEditor extends ManagedActivity implements ...@@ -92,11 +91,11 @@ public class AccountEditor extends ManagedActivity implements
token = INVALIDATED_TOKEN; token = INVALIDATED_TOKEN;
} else { } else {
String value = OAuthActivity.getToken(data); String value = OAuthActivity.getToken(data);
if (value == null) if (value == null) {
Application.getInstance().onError( Application.getInstance().onError(R.string.AUTHENTICATION_FAILED);
R.string.AUTHENTICATION_FAILED); } else {
else
token = value; token = value;
}
} }
((AccountEditorFragment) getFragmentManager().findFragmentById( ((AccountEditorFragment) getFragmentManager().findFragmentById(
...@@ -109,9 +108,8 @@ public class AccountEditor extends ManagedActivity implements ...@@ -109,9 +108,8 @@ public class AccountEditor extends ManagedActivity implements
@Override @Override
public boolean onPreferenceClick(Preference preference) { public boolean onPreferenceClick(Preference preference) {
if (getString(R.string.account_oauth_key).equals(preference.getKey())) { if (getString(R.string.account_oauth_key).equals(preference.getKey())) {
startActivityForResult(OAuthActivity.createIntent(this, accountItem startActivityForResult(OAuthActivity.createIntent(this,
.getConnectionSettings().getProtocol()), accountItem.getConnectionSettings().getProtocol()), OAUTH_WML_REQUEST_CODE);
OAUTH_WML_REQUEST_CODE);
return true; return true;
} }
return false; return false;
...@@ -120,8 +118,7 @@ public class AccountEditor extends ManagedActivity implements ...@@ -120,8 +118,7 @@ public class AccountEditor extends ManagedActivity implements
@Override @Override
protected Dialog onCreateDialog(int id) { protected Dialog onCreateDialog(int id) {
if (id == ORBOT_DIALOG_ID) { if (id == ORBOT_DIALOG_ID) {
return new OrbotInstallerDialogBuilder(this, ORBOT_DIALOG_ID) return new OrbotInstallerDialogBuilder(this, ORBOT_DIALOG_ID).create();
.create();
} }
return super.onCreateDialog(id); return super.onCreateDialog(id);
} }
...@@ -131,8 +128,7 @@ public class AccountEditor extends ManagedActivity implements ...@@ -131,8 +128,7 @@ public class AccountEditor extends ManagedActivity implements
} }
public static Intent createIntent(Context context, String account) { public static Intent createIntent(Context context, String account) {
return new AccountIntentBuilder(context, AccountEditor.class) return new AccountIntentBuilder(context, AccountEditor.class).setAccount(account).build();
.setAccount(account).build();
} }
@Override @Override
...@@ -152,9 +148,8 @@ public class AccountEditor extends ManagedActivity implements ...@@ -152,9 +148,8 @@ public class AccountEditor extends ManagedActivity implements
@Override @Override
public void onOAuthClick() { public void onOAuthClick() {
startActivityForResult(OAuthActivity.createIntent(this, accountItem startActivityForResult(OAuthActivity.createIntent(this,
.getConnectionSettings().getProtocol()), accountItem.getConnectionSettings().getProtocol()), OAUTH_WML_REQUEST_CODE);
OAUTH_WML_REQUEST_CODE);
} }
@Override @Override
......
...@@ -27,19 +27,19 @@ public class AccountEditorFragment extends BaseSettingsFragment ...@@ -27,19 +27,19 @@ public class AccountEditorFragment extends BaseSettingsFragment
@Override @Override
protected void onInflate(Bundle savedInstanceState) { protected void onInflate(Bundle savedInstanceState) {
AccountProtocol protocol = mListener.getAccountItem().getConnectionSettings() AccountProtocol protocol = mListener.getAccountItem().getConnectionSettings().getProtocol();
.getProtocol(); if (protocol == AccountProtocol.xmpp) {
if (protocol == AccountProtocol.xmpp)
addPreferencesFromResource(R.xml.account_editor_xmpp); addPreferencesFromResource(R.xml.account_editor_xmpp);
else if (protocol == AccountProtocol.gtalk) } else if (protocol == AccountProtocol.gtalk) {
addPreferencesFromResource(R.xml.account_editor_xmpp); addPreferencesFromResource(R.xml.account_editor_xmpp);
else if (protocol == AccountProtocol.wlm) } else if (protocol == AccountProtocol.wlm) {
addPreferencesFromResource(R.xml.account_editor_oauth); addPreferencesFromResource(R.xml.account_editor_oauth);
else } else {
throw new IllegalStateException(); throw new IllegalStateException();
if (!Application.getInstance().isContactsSupported()) }
getPreferenceScreen().removePreference( if (!Application.getInstance().isContactsSupported()) {
findPreference(getString(R.string.account_syncable_key))); getPreferenceScreen().removePreference(findPreference(getString(R.string.account_syncable_key)));
}
oauthPreference = findPreference(getString(R.string.account_oauth_key)); oauthPreference = findPreference(getString(R.string.account_oauth_key));
if (oauthPreference != null) { if (oauthPreference != null) {
...@@ -57,7 +57,9 @@ public class AccountEditorFragment extends BaseSettingsFragment ...@@ -57,7 +57,9 @@ public class AccountEditorFragment extends BaseSettingsFragment
@Override @Override
public boolean onPreferenceChange(Preference preference, Object newValue) { public boolean onPreferenceChange(Preference preference, Object newValue) {
if (getString(R.string.account_port_key).equals(preference.getKey())) String key = preference.getKey();
if (getString(R.string.account_port_key).equals(key)) {
try { try {
Integer.parseInt((String) newValue); Integer.parseInt((String) newValue);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
...@@ -65,45 +67,43 @@ public class AccountEditorFragment extends BaseSettingsFragment ...@@ -65,45 +67,43 @@ public class AccountEditorFragment extends BaseSettingsFragment
Toast.LENGTH_LONG).show(); Toast.LENGTH_LONG).show();
return false; return false;
} }
if (getString(R.string.account_tls_mode_key) }
.equals(preference.getKey())
|| getString(R.string.account_archive_mode_key).equals( if (getString(R.string.account_tls_mode_key).equals(key)
preference.getKey()) || getString(R.string.account_archive_mode_key).equals(key)
|| getString(R.string.account_proxy_type_key).equals( || getString(R.string.account_proxy_type_key).equals(key)
preference.getKey())) || getString(R.string.account_color_key).equals(key)) {
preference.setSummary((String) newValue); preference.setSummary((String) newValue);
else if (!getString(R.string.account_password_key).equals( } else if (!getString(R.string.account_password_key).equals(key)
preference.getKey()) && !getString(R.string.account_proxy_password_key).equals(key)
&& !getString(R.string.account_proxy_password_key).equals( && !getString(R.string.account_priority_key).equals(key)) {
preference.getKey())
&& !getString(R.string.account_priority_key).equals(
preference.getKey()))
super.onPreferenceChange(preference, newValue); super.onPreferenceChange(preference, newValue);
if (getString(R.string.account_proxy_type_key).equals( }
preference.getKey())) {
boolean enabled = !getString(R.string.account_proxy_type_none) if (getString(R.string.account_proxy_type_key).equals(key)) {
.equals(newValue) boolean enabled = !getString(R.string.account_proxy_type_none).equals(newValue)
&& !getString(R.string.account_proxy_type_orbot).equals( && !getString(R.string.account_proxy_type_orbot).equals(newValue);
newValue);
for (int id : new Integer[]{R.string.account_proxy_host_key, for (int id : new Integer[]{R.string.account_proxy_host_key,
R.string.account_proxy_port_key, R.string.account_proxy_port_key, R.string.account_proxy_user_key,
R.string.account_proxy_user_key,
R.string.account_proxy_password_key,}) { R.string.account_proxy_password_key,}) {
Preference proxyPreference = findPreference(getString(id)); Preference proxyPreference = findPreference(getString(id));
if (proxyPreference != null) if (proxyPreference != null) {
proxyPreference.setEnabled(enabled); proxyPreference.setEnabled(enabled);
}
} }
} }
return true; return true;
} }
public void onOAuthChange() { public void onOAuthChange() {
if (oauthPreference == null) if (oauthPreference == null) {
return; return;
if (AccountEditor.INVALIDATED_TOKEN.equals(mListener.getToken())) }
if (AccountEditor.INVALIDATED_TOKEN.equals(mListener.getToken())) {
oauthPreference.setSummary(R.string.account_oauth_invalidated); oauthPreference.setSummary(R.string.account_oauth_invalidated);
else } else {
oauthPreference.setSummary(R.string.account_oauth_summary); oauthPreference.setSummary(R.string.account_oauth_summary);
}
} }
@Override @Override
...@@ -120,59 +120,45 @@ public class AccountEditorFragment extends BaseSettingsFragment ...@@ -120,59 +120,45 @@ public class AccountEditorFragment extends BaseSettingsFragment
Map<String, Object> source = new HashMap<>(); Map<String, Object> source = new HashMap<>();
AccountItem accountItem = mListener.getAccountItem(); AccountItem accountItem = mListener.getAccountItem();
putValue(source, R.string.account_custom_key, accountItem
.getConnectionSettings().isCustom());
putValue(source, R.string.account_host_key, accountItem
.getConnectionSettings().getHost());
putValue(source, R.string.account_port_key, accountItem
.getConnectionSettings().getPort());
putValue(source, R.string.account_server_key, accountItem
.getConnectionSettings().getServerName());
putValue(source, R.string.account_username_key, accountItem
.getConnectionSettings().getUserName());
putValue(source, R.string.account_store_password_key, accountItem.isStorePassword());
putValue(source, R.string.account_password_key, accountItem
.getConnectionSettings().getPassword());
putValue(source, R.string.account_resource_key, accountItem
.getConnectionSettings().getResource());
putValue(source, R.string.account_priority_key, accountItem.getPriority()); putValue(source, R.string.account_priority_key, accountItem.getPriority());
putValue(source, R.string.account_enabled_key, accountItem.isEnabled()); putValue(source, R.string.account_enabled_key, accountItem.isEnabled());
putValue(source, R.string.account_sasl_key, accountItem putValue(source, R.string.account_store_password_key, accountItem.isStorePassword());
.getConnectionSettings().isSaslEnabled()); putValue(source, R.string.account_syncable_key, accountItem.isSyncable());
putValue(source, R.string.account_tls_mode_key, putValue(source, R.string.account_archive_mode_key, accountItem.getArchiveMode().ordinal());
accountItem.getConnectionSettings().getTlsMode().ordinal()); putValue(source, R.string.account_color_key, accountItem.getColorIndex());
putValue(source, R.string.account_compression_key, accountItem
.getConnectionSettings().useCompression()); com.xabber.android.data.connection.ConnectionSettings connectionSettings = accountItem.getConnectionSettings();
putValue(source, R.string.account_proxy_type_key, putValue(source, R.string.account_custom_key, connectionSettings.isCustom());
accountItem.getConnectionSettings().getProxyType().ordinal()); putValue(source, R.string.account_host_key, connectionSettings.getHost());
putValue(source, R.string.account_proxy_host_key, accountItem putValue(source, R.string.account_port_key, connectionSettings.getPort());
.getConnectionSettings().getProxyHost()); putValue(source, R.string.account_server_key, connectionSettings.getServerName());
putValue(source, R.string.account_proxy_port_key, accountItem putValue(source, R.string.account_username_key, connectionSettings.getUserName());
.getConnectionSettings().getProxyPort()); putValue(source, R.string.account_password_key, connectionSettings.getPassword());
putValue(source, R.string.account_proxy_user_key, accountItem putValue(source, R.string.account_resource_key, connectionSettings.getResource());
.getConnectionSettings().getProxyUser()); putValue(source, R.string.account_sasl_key, connectionSettings.isSaslEnabled());
putValue(source, R.string.account_proxy_password_key, accountItem putValue(source, R.string.account_tls_mode_key, connectionSettings.getTlsMode().ordinal());
.getConnectionSettings().getProxyPassword()); putValue(source, R.string.account_compression_key, connectionSettings.useCompression());
putValue(source, R.string.account_syncable_key, putValue(source, R.string.account_proxy_type_key, connectionSettings.getProxyType().ordinal());
accountItem.isSyncable()); putValue(source, R.string.account_proxy_host_key, connectionSettings.getProxyHost());
putValue(source, R.string.account_archive_mode_key, putValue(source, R.string.account_proxy_port_key, connectionSettings.getProxyPort());
accountItem.getArchiveMode().ordinal()); putValue(source, R.string.account_proxy_user_key, connectionSettings.getProxyUser());
putValue(source, R.string.account_proxy_password_key, connectionSettings.getProxyPassword());
return source; return source;
} }
@Override @Override
protected Map<String, Object> getPreferences(Map<String, Object> source) { protected Map<String, Object> getPreferences(Map<String, Object> source) {
Map<String, Object> result = super.getPreferences(source); Map<String, Object> result = super.getPreferences(source);
if (oauthPreference != null) if (oauthPreference != null) {
putValue(result, R.string.account_password_key, mListener.getAccount()); putValue(result, R.string.account_password_key, mListener.getAccount());
}
return result; return result;
} }
@Override @Override
protected boolean setValues(Map<String, Object> source, protected boolean setValues(Map<String, Object> source, Map<String, Object> result) {
Map<String, Object> result) { ProxyType proxyType = ProxyType.values()[getInt(result, R.string.account_proxy_type_key)];
ProxyType proxyType = ProxyType.values()[getInt(result,
R.string.account_proxy_type_key)];
if (proxyType == ProxyType.orbot && !OrbotHelper.isOrbotInstalled()) { if (proxyType == ProxyType.orbot && !OrbotHelper.isOrbotInstalled()) {
mListener.showOrbotDialog(); mListener.showOrbotDialog();
return false; return false;
...@@ -198,13 +184,17 @@ public class AccountEditorFragment extends BaseSettingsFragment ...@@ -198,13 +184,17 @@ public class AccountEditorFragment extends BaseSettingsFragment
getString(result, R.string.account_proxy_user_key), getString(result, R.string.account_proxy_user_key),
getString(result, R.string.account_proxy_password_key), getString(result, R.string.account_proxy_password_key),
getBoolean(result, R.string.account_syncable_key), getBoolean(result, R.string.account_syncable_key),
ArchiveMode.values()[getInt(result, R.string.account_archive_mode_key)]); ArchiveMode.values()[getInt(result, R.string.account_archive_mode_key)],
getInt(result, R.string.account_color_key)
);
return true; return true;
} }
@Override @Override
public void onAttach(Activity activity) { public void onAttach(Activity activity) {
super.onAttach(activity); super.onAttach(activity);
try { try {
mListener = (AccountEditorFragmentInteractionListener) activity; mListener = (AccountEditorFragmentInteractionListener) activity;
} catch (ClassCastException e) { } catch (ClassCastException e) {
...@@ -221,13 +211,9 @@ public class AccountEditorFragment extends BaseSettingsFragment ...@@ -221,13 +211,9 @@ public class AccountEditorFragment extends BaseSettingsFragment
public interface AccountEditorFragmentInteractionListener { public interface AccountEditorFragmentInteractionListener {
public String getAccount(); public String getAccount();
public AccountItem getAccountItem(); public AccountItem getAccountItem();
public String getToken(); public String getToken();
public void onOAuthClick(); public void onOAuthClick();
public void showOrbotDialog(); public void showOrbotDialog();
} }
} }
...@@ -162,4 +162,10 @@ ...@@ -162,4 +162,10 @@
<string name="orbot_required_message">Для использования TOR необходимо установить приложение Orbot и активировать в нём передачу данных. Вы хотите установить его из Google Play?</string> <string name="orbot_required_message">Для использования TOR необходимо установить приложение Orbot и активировать в нём передачу данных. Вы хотите установить его из Google Play?</string>
<string name="orbot_required_title">Установить Orbot?</string> <string name="orbot_required_title">Установить Orbot?</string>
<string name="ACCOUNT_REGISTER_FAILED">Не удалось зарегистрировать аккаунт на сервере.</string> <string name="ACCOUNT_REGISTER_FAILED">Не удалось зарегистрировать аккаунт на сервере.</string>
<string name="account_color_name_green">Зеленый</string>
<string name="account_color_name_orange">Оранжевый</string>
<string name="account_color_name_red">Красный</string>
<string name="account_color_name_blue">Синий</string>
<string name="account_color">Цвет учётной записи</string>
</resources> </resources>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"> <resources>
<!-- http://dl.dropbox.com/u/1029995/com.xabber.android/account_editor_02.png --> <!-- http://dl.dropbox.com/u/1029995/com.xabber.android/account_editor_02.png -->
<string name="account_compression">Use compression</string> <string name="account_compression">Use compression</string>
<!-- http://dl.dropbox.com/u/1029995/com.xabber.android/account_editor_01.png --> <!-- http://dl.dropbox.com/u/1029995/com.xabber.android/account_editor_01.png -->
...@@ -162,4 +162,10 @@ ...@@ -162,4 +162,10 @@
<string name="orbot_required_message">In order to process using TOR you must have Orbot installed and activated to proxy traffic through it. Would you like to install it from Google Play?</string> <string name="orbot_required_message">In order to process using TOR you must have Orbot installed and activated to proxy traffic through it. Would you like to install it from Google Play?</string>
<string name="orbot_required_title">Install Orbot?</string> <string name="orbot_required_title">Install Orbot?</string>
<string name="ACCOUNT_REGISTER_FAILED">Failed to register account on the server.</string> <string name="ACCOUNT_REGISTER_FAILED">Failed to register account on the server.</string>
<string name="account_color_name_green">Green</string>
<string name="account_color_name_orange">Orange</string>
<string name="account_color_name_red">Red</string>
<string name="account_color_name_blue">Blue</string>
<string name="account_color">Account color</string>
</resources> </resources>
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<array name="account_color_names">
<item>@string/account_color_name_green</item>
<item>@string/account_color_name_orange</item>
<item>@string/account_color_name_red</item>
<item>@string/account_color_name_blue</item>
</array>
<array name="account_action_bar"> <array name="account_action_bar">
<item>@color/teal_500</item> <item>@color/teal_500</item>
<item>@color/deep_orange_500</item> <item>@color/deep_orange_500</item>
......
...@@ -397,6 +397,7 @@ ...@@ -397,6 +397,7 @@
<string name="account_proxy_password_key">account_proxy_password</string> <string name="account_proxy_password_key">account_proxy_password</string>
<string name="account_custom_key">account_custom</string> <string name="account_custom_key">account_custom</string>
<string name="account_archive_mode_key">account_archive_mode</string> <string name="account_archive_mode_key">account_archive_mode</string>
<string name="account_color_key">account_color_key</string>
<string-array name="account_tls_entries"> <string-array name="account_tls_entries">
<item>@string/account_tls_enable</item> <item>@string/account_tls_enable</item>
......
...@@ -19,6 +19,12 @@ ...@@ -19,6 +19,12 @@
android:summary="@string/account_enabled_summary" android:summary="@string/account_enabled_summary"
android:key="@string/account_enabled_key" android:key="@string/account_enabled_key"
/> />
<ListPreference
android:title="@string/account_color"
android:key="@string/account_color_key"
android:entries="@array/account_color_names"
android:entryValues="@array/account_color_names"
/>
<CheckBoxPreference <CheckBoxPreference
android:title="@string/account_syncable" android:title="@string/account_syncable"
android:summary="@string/account_syncable_summary" android:summary="@string/account_syncable_summary"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment